예제 #1
0
  public static PackageInfo[] chooseModulePackages() {
    ClassInfo[] classes = Converter.rootClasses();
    SortedMap<String, PackageInfo> sorted = new TreeMap<String, PackageInfo>();
    for (ClassInfo cl : classes) {
      if (!cl.isModule()) {
        continue;
      }

      PackageInfo pkg = cl.containingPackage();
      String name;
      if (pkg == null) {
        name = "";
      } else {
        name = pkg.name();
      }
      sorted.put(name, pkg);
    }

    ArrayList<PackageInfo> result = new ArrayList<PackageInfo>();

    for (String s : sorted.keySet()) {
      PackageInfo pkg = sorted.get(s);

      result.add(pkg);
    }

    return result.toArray(new PackageInfo[result.size()]);
  }
예제 #2
0
  /**
   * This method builds the custom data collections used on the form
   *
   * @param customAttributeGroups
   */
  @SuppressWarnings("unchecked")
  public void buildCustomDataCollectionsOnNewDocument(
      SortedMap<String, List> customAttributeGroups) {
    for (Map.Entry<String, CustomAttributeDocument> customAttributeDocumentEntry :
        getCustomAttributeDocuments().entrySet()) {
      String temp = customAttributeDocumentEntry.getValue().getCustomAttribute().getValue();
      String groupName =
          customAttributeDocumentEntry.getValue().getCustomAttribute().getGroupName();

      T newCustomData = getNewCustomData();
      newCustomData.setCustomAttribute(
          customAttributeDocumentEntry.getValue().getCustomAttribute());
      newCustomData.setCustomAttributeId(
          customAttributeDocumentEntry.getValue().getCustomAttributeId().longValue());
      newCustomData.setValue(
          customAttributeDocumentEntry.getValue().getCustomAttribute().getDefaultValue());
      getCustomDataList().add(newCustomData);

      if (StringUtils.isEmpty(groupName)) {
        groupName = "No Group";
      }

      List<CustomAttributeDocument> customAttributeDocumentList =
          customAttributeGroups.get(groupName);
      if (customAttributeDocumentList == null) {
        customAttributeDocumentList = new ArrayList<CustomAttributeDocument>();
        customAttributeGroups.put(groupName, customAttributeDocumentList);
      }
      customAttributeDocumentList.add(
          getCustomAttributeDocuments()
              .get(customAttributeDocumentEntry.getValue().getCustomAttributeId().toString()));
      Collections.sort(customAttributeDocumentList, new LabelComparator());
    }
  }
예제 #3
0
  /**
   * Finds a suitable analyzer class for a magic signature
   *
   * @param signature the magic signature look up
   * @return the analyzer factory to use
   */
  private static FileAnalyzerFactory find(byte[] signature) throws IOException {
    // XXX this assumes ISO-8859-1 encoding (and should work in most cases
    // for US-ASCII, UTF-8 and other ISO-8859-* encodings, but not always),
    // we should try to be smarter than this...
    char[] chars = new char[signature.length > 8 ? 8 : signature.length];
    for (int i = 0; i < chars.length; i++) {
      chars[i] = (char) (0xFF & signature[i]);
    }

    String sig = new String(chars);

    FileAnalyzerFactory a = magics.get(sig);
    if (a == null) {
      String sigWithoutBOM = stripBOM(signature);
      for (Map.Entry<String, FileAnalyzerFactory> entry : magics.entrySet()) {
        if (sig.startsWith(entry.getKey())) {
          return entry.getValue();
        }
        // See if text files have the magic sequence if we remove the
        // byte-order marker
        if (sigWithoutBOM != null
            && entry.getValue().getGenre() == Genre.PLAIN
            && sigWithoutBOM.startsWith(entry.getKey())) {
          return entry.getValue();
        }
      }
    }
    return a;
  }
예제 #4
0
 private void nastavPatterned() {
   if (blokujEventy) {
     return;
   }
   final RenderSettings.Patterned p = patterned.copy();
   final int index = getSelectedIndex();
   // aby tam vůbec vešel
   if (index >= 0) {
     final String key = keys.get(index);
     if (!geotaggingPatterns.isEmpty()) { // mame data geotaggingu
       p.setPatternNumberCilovy(key);
       if (souradnicovePatterns.containsKey(key)) {
         p.setPatternNumberPredbezny(key);
       }
     } else { // mame jen zakladni data
       p.setPatternNumberPredbezny(key);
       if (p.getPatternNumberCilovy() != null
           && souradnicovePatterns.containsKey(p.getPatternNumberCilovy())) {
         p.setPatternNumberCilovy(key);
       }
     }
   }
   p.setText((String) getSelectedItem());
   setPatterned(p);
 }
 /**
  * Returns the number of option values amongst all internal option containers.
  *
  * @return the number of option values amongst all internal option containers
  */
 public int getNumberOfOptionValues() {
   SortedSet<Option> union = new TreeSet<Option>(savedOptionMap.keySet());
   union.addAll(dependenciesResolvedOptionMap.keySet());
   union.addAll(commandLineOptionMap.keySet());
   union.addAll(optionFileOptionMap.keySet());
   return union.size();
 }
예제 #6
0
 public CArray(Target t, int initialCapacity, Construct... items) {
   super("{}", ConstructType.ARRAY, t);
   if (initialCapacity == -1) {
     associative_mode = true;
   } else if (items != null) {
     for (Construct item : items) {
       if (item instanceof CEntry) {
         // it's an associative array
         associative_mode = true;
         break;
       }
     }
   }
   associative_array = new TreeMap<>(comparator);
   array =
       associative_mode
           ? new ArrayList<Construct>()
           : initialCapacity > 0
               ? new ArrayList<Construct>(initialCapacity)
               : items != null
                   ? new ArrayList<Construct>(items.length)
                   : new ArrayList<Construct>();
   if (associative_mode) {
     if (items != null) {
       for (Construct item : items) {
         if (item instanceof CEntry) {
           associative_array.put(
               normalizeConstruct(((CEntry) item).ckey), ((CEntry) item).construct);
         } else {
           int max = Integer.MIN_VALUE;
           for (String key : associative_array.keySet()) {
             try {
               int i = Integer.parseInt(key);
               max = java.lang.Math.max(max, i);
             } catch (NumberFormatException e) {
             }
           }
           if (max == Integer.MIN_VALUE) {
             max = -1; // Special case, there are no integer indexes in here yet.
           }
           associative_array.put(Integer.toString(max + 1), item);
           if (item instanceof CArray) {
             ((CArray) item).parent = this;
           }
         }
       }
     }
   } else {
     if (items != null) {
       for (Construct item : items) {
         array.add(item);
         if (item instanceof CArray) {
           ((CArray) item).parent = this;
         }
       }
     }
     this.next_index = array.size();
   }
   regenValue(new HashSet<CArray>());
 }
 private DropdownMenu getDropDownOfQueries(String key, IWContext iwc)
     throws RemoteException, FinderException {
   SortedMap sortedMap = new TreeMap(new StringAlphabeticalComparator(iwc.getCurrentLocale()));
   DropdownMenu drp = new DropdownMenu(key);
   Iterator iterator = getQueryService(iwc).getQueries(iwc).iterator();
   while (iterator.hasNext()) {
     EntityRepresentation userQuery = (EntityRepresentation) iterator.next();
     String name = (String) userQuery.getColumnValue(QueryRepresentation.NAME_KEY);
     String id = userQuery.getPrimaryKey().toString();
     if (sortedMap.containsKey(name)) {
       // usually the items have different names therefore we implement
       // a very simple solution
       name += " (1)";
     }
     sortedMap.put(name, id);
   }
   Iterator sortedIterator = sortedMap.entrySet().iterator();
   while (sortedIterator.hasNext()) {
     Map.Entry entry = (Map.Entry) sortedIterator.next();
     String id = (String) entry.getValue();
     String name = (String) entry.getKey();
     drp.addMenuElement(id, name);
   }
   return drp;
 }
예제 #8
0
    private void equivalent(int p1, int p2) {
      BitSet b = equivalence.get(p1);
      b.set(p2);

      b = equivalence.get(p2);
      b.set(p1);
    }
  private void populateVMs(VirtualNetworkInfo vn, VmwareVirtualNetworkInfo vmwareVN) {
    SandeshObjectList<VirtualMachineInfo> vMachines = vn.getVMachines();

    if (vMachines == null) {
      return;
    }
    SortedMap<String, VmwareVirtualMachineInfo> map = vmwareVN.getVmInfo();

    if (map == null) {
      return;
    }
    for (Map.Entry<String, VmwareVirtualMachineInfo> entry : map.entrySet()) {
      VmwareVirtualMachineInfo vmwareVM = entry.getValue();

      if (!vrouter.getEsxiHost().trim().equals(vmwareVM.getHostName().trim())) {
        continue;
      }

      VirtualMachineInfo vm = new VirtualMachineInfo();
      vm.setName(vmwareVM.getName());
      vm.setIpAddr(vmwareVM.getIpAddress());
      vm.setMacAddr(vmwareVM.getMacAddress());
      vm.setEsxiHost(vmwareVM.getHostName());
      vm.setPowerState(vmwareVM.getPowerState().name());
      vm.setNetwork(vn.getName());

      vMachines.add(vm);
    }
  }
 SortedMap<String, String> sortedFormattedHeaders(Header[] headers) {
   SortedMap<String, String> sortedHeaders = new TreeMap<>();
   for (Header header : headers) {
     sortedHeaders.put(header.getName().toLowerCase(), header.getValue().trim());
   }
   return sortedHeaders;
 }
예제 #11
0
  private List<ChatMessage> sanitizeMap(final SortedMap<Date, ChatMessage> aMap) {
    if (aMap.isEmpty() || aMap.size() == 1) return Lists.newArrayList(aMap.values());

    final LinkedList<ChatMessage> ret = Lists.newLinkedList(aMap.values());
    final ListIterator<ChatMessage> i = ret.listIterator();
    ChatMessage prevMsg = i.next();
    do {
      ChatMessage msg = i.next();
      if (!msg.getPreviousMessageDate().equals(prevMsg.getDate())) {
        if (msg.getPreviousMessageDate().before(prevMsg.getDate())) {
          msg.setPreviousMessageDate(prevMsg.getDate());
        } else {
          final ChatMessage tmp =
              createLostMessageBetween(
                  msg.getRoom(), prevMsg.getDate(), msg.getPreviousMessageDate());
          aMap.put(tmp.getDate(), tmp);
          i.previous();
          i.add(tmp);
          i.next();
          msg = tmp;
        }
      }
      prevMsg = msg;
    } while (i.hasNext());

    return ret;
  }
 public SortedMap<String, T> getAsMap() {
   SortedMap<String, T> map = new TreeMap<String, T>();
   for (T o : getStore()) {
     map.put(namer.determineName(o), o);
   }
   return map;
 }
예제 #13
0
  protected static SortedMap<Integer, AgreementSummaryInstance> getAgreementSummaryList(
      List<Object[]> objects, boolean primary, boolean siteSearch) throws Exception {
    SortedMap<Integer, AgreementSummaryInstance> agreementMap =
        new TreeMap<Integer, AgreementSummaryInstance>();
    AgreementSummaryInstance instance = null;
    for (Object[] row : objects) {
      if (row.length >= 1 && row[0] instanceof Agreement) {
        Agreement agreement = (Agreement) row[0];
        if (agreementMap.containsKey(agreement.getId())) {
          instance = agreementMap.get(agreement.getId());
        } else {
          instance = getAgreementSummaryInstance(agreement, primary, siteSearch);
          agreementMap.put(instance.getId(), instance);
        }
      }
      if (row.length == 2
          && row[0] instanceof Agreement
          && row[1] != null
          && row[1] instanceof AgreementTerm) {
        AgreementTerm agreementTerm = (AgreementTerm) row[1];
        applyAgreementTerm(instance, agreementTerm);
      } else if (row.length != 2
          || !(row[0] instanceof Agreement)
          || !(row[1] == null || row[1] instanceof Agreement))
        throw new Exception("Unexpected SQL result in getAgreementSummaryList");
    }

    return agreementMap;

    //        List<AgreementSummaryInstance> results = new ArrayList<AgreementSummaryInstance>();
    //        results.addAll(agreementMap.values());
    //
    //        return results;
  }
예제 #14
0
 public static SortedMap<Integer, AgreementSummaryInstance> findAllAgreementSummaries(
     int ucn, List<Integer> ucns, boolean primary, char status, char neStatus) throws Exception {
   SortedMap<Integer, AgreementSummaryInstance> agreementMap =
       findBillAgreementSummaries(ucn, null, primary, status, neStatus);
   agreementMap.putAll(findSiteAgreementSummaries(ucn, primary, status, neStatus));
   return agreementMap;
 }
예제 #15
0
 /**
  * @param index
  * @param c
  */
 public void set(Construct index, Construct c, Target t) {
   if (!associative_mode) {
     try {
       int indx = Static.getInt32(index, t);
       if (indx > next_index || indx < 0) {
         throw ConfigRuntimeException.BuildException(
             "", ExceptionType.IndexOverflowException, Target.UNKNOWN);
       } else if (indx == next_index) {
         this.push(c, t);
       } else {
         array.set(indx, c);
       }
     } catch (ConfigRuntimeException e) {
       // Not a number. Convert to associative.
       associative_array = new TreeMap<String, Construct>(comparator);
       for (int i = 0; i < array.size(); i++) {
         associative_array.put(Integer.toString(i), array.get(i));
       }
       associative_mode = true;
       array = null; // null out the original array container so it can be GC'd
     }
   }
   if (associative_mode) {
     associative_array.put(normalizeConstruct(index), c);
   }
   if (c instanceof CArray) {
     ((CArray) c).parent = this;
   }
   regenValue(new HashSet<CArray>());
 }
예제 #16
0
  /**
   * return the contents of the buffer. The order of the chunks returned is determined by the
   * ejection policy, such that the chunk most likely to be given the book is first.
   */
  @Override
  protected Collection<IChunk> getSourceChunksInternal(Collection<IChunk> container) {
    /*
     * there is nothing to return..
     */
    if (_sourceChunks.size() == 0) return container;

    List<IChunk> list = null;
    if (container instanceof List) list = (List<IChunk>) container;
    else list = new ArrayList<IChunk>(_sourceChunks.size());

    list.addAll(_sourceChunks.values());

    switch (getEjectionPolicy()) {
      case MostRecentlyAdded:
      case MostRecentlyMatched:
      case MostRecentlyUsed:
        Collections.reverse(list);
        break;
    }

    if (!(container instanceof List)) container.addAll(list);

    return container;
  }
예제 #17
0
 @Override
 public Construct get(Construct index, Target t) {
   if (!associative_mode) {
     try {
       return array.get(Static.getInt32(index, t));
     } catch (IndexOutOfBoundsException e) {
       throw ConfigRuntimeException.BuildException(
           "The element at index \"" + index.val() + "\" does not exist",
           ExceptionType.IndexOverflowException,
           t,
           e);
     }
   } else {
     if (associative_array.containsKey(normalizeConstruct(index))) {
       Construct val = associative_array.get(normalizeConstruct(index));
       if (val instanceof CEntry) {
         return ((CEntry) val).construct();
       }
       return val;
     } else {
       // Create this so we can at least attach a stacktrace.
       @SuppressWarnings({"ThrowableInstanceNotThrown", "ThrowableInstanceNeverThrown"})
       IndexOutOfBoundsException ioobe = new IndexOutOfBoundsException();
       throw ConfigRuntimeException.BuildException(
           "The element at index \"" + index.val() + "\" does not exist",
           ExceptionType.IndexOverflowException,
           t,
           ioobe);
     }
   }
 }
예제 #18
0
  private String createParameterString() {

    // put required parameters
    for (OauthConstants constant : OauthConstants.values()) {
      String key = OAuth.percentEncode(constant.name());
      String value = OAuth.percentEncode(properties.getProperty(constant.name()));
      if (constant.equals(OauthConstants.oauth_nonce)) {
        value = OAuth.percentEncode(nonce);
      }
      if (constant.equals(OauthConstants.oauth_timestamp)) {
        value = OAuth.percentEncode(String.valueOf(timestamp));
      }
      parameterMap.put(key, value);
    }

    // put optional parameters
    for (Object key_ : optionalParameters.keySet()) {
      String keyStr = (String) key_;
      String key = OAuth.percentEncode(keyStr);
      String value = OAuth.percentEncode(optionalParameters.get(keyStr).toString());
      parameterMap.put(key, value);
    }

    StringBuilder builder = new StringBuilder();

    for (String s : parameterMap.keySet()) {
      builder.append(s).append('=').append(parameterMap.get(s)).append("&");
    }
    builder.setLength(builder.lastIndexOf("&"));
    return builder.toString();
  }
예제 #19
0
  @Test
  public void testOrderBy() {
    final JPAEnvironment env = getEnvironment();
    final EntityManager em = env.getEntityManager();
    final SortedMap<String, Employee> attendeeMap = new TreeMap<String, Employee>();
    try {
      env.beginTransaction(em);
      final Course course = createAndPersistCourse(em);
      final Long courseId = Long.valueOf(course.getCourseId());
      final Employee employee1 = em.find(Employee.class, EMP_ID_DORIS);
      attendeeMap.put(employee1.getLastName(), employee1);
      final Employee employee2 = em.find(Employee.class, EMP_ID_SABINE);
      attendeeMap.put(employee2.getLastName(), employee2);
      env.commitTransactionAndClear(em);

      env.beginTransaction(em);
      final Course storedCourse = em.find(Course.class, courseId);
      verify(storedCourse != null, "didnt find course again");
      final List<Employee> attendees = storedCourse.getAttendees();
      verify(attendees != null, "course lost attendees");
      final Iterator<Employee> orderedEmployees = attendees.iterator();
      for (final String lastName : attendeeMap.keySet()) {
        Employee nextEmployee = orderedEmployees.next();
        verify(
            nextEmployee.getLastName().equals(lastName),
            "wrong order of employees, expected name: "
                + lastName
                + ", but got name: "
                + nextEmployee.getLastName());
      }
      env.commitTransactionAndClear(em);
    } finally {
      closeEntityManager(em);
    }
  }
예제 #20
0
 public List<EntityKnowledge> getAllies() {
   List<EntityKnowledge> res = new LinkedList<>();
   for (SortedMap<Integer, EntityKnowledge> map : allies.values()) {
     res.addAll(map.values());
   }
   return res;
 }
예제 #21
0
  /**
   * Takes a query string, separates the constituent name-value pairs, and stores them in a
   * SortedMap ordered by lexicographical order.
   *
   * @param queryString the query string
   * @return Null if there is no query string.
   */
  private static SortedMap<String, String> createParameterMap(final String queryString) {
    if (queryString == null || queryString.isEmpty()) {
      return null;
    }

    final String[] pairs = queryString.split("&");
    final SortedMap<String, String> params = new TreeMap<>();

    for (final String pair : pairs) {
      if (pair.length() == 0) {
        continue;
      }

      String[] tokens = pair.split("=", 2);
      switch (tokens.length) {
        case 1:
          if (pair.charAt(0) == '=') {
            params.put("", tokens[0]);
          } else {
            params.put(tokens[0], "");
          }
          break;
        case 2:
          params.put(tokens[0], tokens[1]);
          break;
      }
    }
    return params;
  }
  @Override
  public synchronized void updateAccessData(
      String karafInstanceUrl,
      String karafInstanceUserName,
      String karafInstancePassword,
      Boolean remoteIsAccessible,
      Boolean allowUpdateMessages,
      String karafInstance) {

    if (karafInstance == null) throw new RuntimeException("karafInstance cannot be null");
    if (karafInstanceUserName == null) throw new RuntimeException("username cannot be null");
    if (karafInstancePassword == null) throw new RuntimeException("password cannot be null");
    if (remoteIsAccessible == null) throw new RuntimeException("remoteIsAccessible cannot be null");
    if (allowUpdateMessages == null)
      throw new RuntimeException("allowUpdateMessages cannot be null");

    SortedMap<String, KarafManifestEntryJaxb> karafInstances = getKarafInstances();
    if (!karafInstances.containsKey(karafInstance))
      throw new RuntimeException("system does not know karafInstance=" + karafInstance);

    KarafManifestEntryJaxb ki = karafInstances.get(karafInstance);
    ki.setKarafInstancePassword(karafInstancePassword);
    ki.setKarafInstanceUserName(karafInstanceUserName);
    ki.setKarafInstanceUrl(karafInstanceUrl);
    ki.setRemoteIsAccessible(remoteIsAccessible);
    ki.setAllowUpdateMessages(allowUpdateMessages);

    persist();
  }
예제 #23
0
    public Channel getChannel(String name) {
      synchronized (channels) {
        Channel channel = channels.get(name);
        if (channel == null) {
          boolean resize = false;

          channel = channels.remove(INITIAL);
          if (channel == null) {
            channel = new Channel(name);
            resize = true;
          } else {
            channel.setName(name);
          }

          channels.put(name, channel);
          channelArray = channels.values().toArray(new Channel[channels.size()]);

          if (resize) {
            getDisplay()
                .syncExec(
                    new Runnable() {
                      public void run() {
                        controlResized(null);
                      }
                    });
          }
        }

        return channel;
      }
    }
예제 #24
0
파일: UIUtils.java 프로젝트: ralic/dbeaver
 public static Combo createEncodingCombo(Composite parent, String curCharset) {
   if (curCharset == null) {
     curCharset = GeneralUtils.getDefaultFileEncoding();
   }
   Combo encodingCombo = new Combo(parent, SWT.DROP_DOWN);
   encodingCombo.setVisibleItemCount(30);
   SortedMap<String, Charset> charsetMap = Charset.availableCharsets();
   int index = 0;
   int defIndex = -1;
   for (String csName : charsetMap.keySet()) {
     Charset charset = charsetMap.get(csName);
     encodingCombo.add(charset.displayName());
     if (charset.displayName().equalsIgnoreCase(curCharset)) {
       defIndex = index;
     }
     if (defIndex < 0) {
       for (String alias : charset.aliases()) {
         if (alias.equalsIgnoreCase(curCharset)) {
           defIndex = index;
         }
       }
     }
     index++;
   }
   if (defIndex >= 0) {
     encodingCombo.select(defIndex);
   } else {
     log.warn("Charset '" + curCharset + "' is not recognized"); // $NON-NLS-1$ //$NON-NLS-2$
   }
   return encodingCombo;
 }
예제 #25
0
 /**
  * This method builds the custom data collections used on the form and populates the values from
  * the collection of AwardCustomData on the Award.
  *
  * @param customAttributeGroups
  */
 @SuppressWarnings("unchecked")
 public void buildCustomDataCollectionsOnExistingDocument(
     SortedMap<String, List> customAttributeGroups) {
   for (Map.Entry<String, CustomAttributeDocument> customAttributeDocumentEntry :
       getCustomAttributeDocuments().entrySet()) {
     T loopAwardCustomData = null;
     for (T awardCustomData : getCustomDataList()) {
       if (awardCustomData.getCustomAttributeId()
           == (long) customAttributeDocumentEntry.getValue().getCustomAttribute().getId()) {
         loopAwardCustomData = awardCustomData;
         break;
       }
     }
     if (loopAwardCustomData != null) {
       String groupName =
           getCustomAttributeDocuments()
               .get(loopAwardCustomData.getCustomAttributeId().toString())
               .getCustomAttribute()
               .getGroupName();
       List<CustomAttributeDocument> customAttributeDocumentList =
           customAttributeGroups.get(groupName);
       if (customAttributeDocumentList == null) {
         customAttributeDocumentList = new ArrayList<CustomAttributeDocument>();
         customAttributeGroups.put(groupName, customAttributeDocumentList);
       }
       customAttributeDocumentList.add(
           getCustomAttributeDocuments()
               .get(loopAwardCustomData.getCustomAttributeId().toString()));
       Collections.sort(customAttributeDocumentList, new LabelComparator());
     }
   }
 }
예제 #26
0
  private void resolveFields() {
    for (Method method : objectType.getMethods()) {
      if ((method.getModifiers() & Modifier.STATIC) != 0) {
        continue;
      }

      String fieldName = null;
      if (method.getName().startsWith("get")) {
        if (method.getName().equals("getId") || method.getName().length() <= 3) {
          continue;
        }
        // Found a field!
        fieldName = getFieldName(method.getName());
      } else if (method.getName().startsWith("is")) {
        if (method.getName().length() <= 2) {
          continue;
        }
        // Found a field!
        fieldName = getFieldName(method.getName());
      }

      if (fieldName != null) {
        fieldTypeMap.put(fieldName, method.getReturnType());
      }
    }

    int index = 0;
    for (String fieldName : fieldTypeMap.keySet()) {
      fieldIndexMap.put(fieldName, index++);
    }
  }
예제 #27
0
  private void printGameStats(HttpServletResponse resp) throws IOException {
    resp.setContentType(GAME_STATS_CONTENT_TYPE);

    PrintWriter writer = resp.getWriter();
    SortedMap<Date, Game> games = db.getProcessedGames();
    for (Entry<Date, Game> entry : games.entrySet()) {
      Game game = entry.getValue();

      writer.println(
          entry.getKey()
              + GAME_STATS_DELIMITER
              + game.getHomeScore()
              + GAME_STATS_DELIMITER
              + game.getAwayScore());
      for (String player : game.getHomeTeam())
        writer.println(
            player
                + GAME_STATS_DELIMITER
                + num(game.getDeltaMu(), player)
                + GAME_STATS_DELIMITER
                + num(game.getDeltaSigma(), player));

      writer.println(GAME_STATS_VERSUS);

      for (String player : game.getAwayTeam())
        writer.println(
            player
                + GAME_STATS_DELIMITER
                + num(game.getDeltaMu(), player)
                + GAME_STATS_DELIMITER
                + num(game.getDeltaSigma(), player));

      writer.println();
    }
  }
예제 #28
0
 /**
  * Pushes a new Construct onto the end of the array. If the index is specified, this works like a
  * "insert" operation, in that all values are shifted to the right, starting with the value at
  * that index. If the array is associative though, you MUST send null, otherwise an {@link
  * IllegalArgumentException} is thrown. Ideally, you should use {@link #set} anyways for an
  * associative array.
  *
  * @param c The Construct to add to the array
  * @throws IllegalArgumentException If index is not null, and this is an associative array.
  * @throws IndexOutOfBoundsException If the index is not null, and the index specified is out of
  *     range.
  */
 public void push(Construct c, Integer index, Target t)
     throws IllegalArgumentException, IndexOutOfBoundsException {
   if (!associative_mode) {
     if (index != null) {
       array.add(index, c);
     } else {
       array.add(c);
     }
     next_index++;
   } else {
     if (index != null) {
       throw new IllegalArgumentException("Cannot insert into an associative array");
     }
     int max = 0;
     for (String key : associative_array.keySet()) {
       try {
         int i = Integer.parseInt(key);
         max = java.lang.Math.max(max, i);
       } catch (NumberFormatException e) {
       }
     }
     if (c instanceof CEntry) {
       associative_array.put(Integer.toString(max + 1), ((CEntry) c).construct());
     } else {
       associative_array.put(Integer.toString(max + 1), c);
     }
   }
   if (c instanceof CArray) {
     ((CArray) c).parent = this;
   }
   regenValue(new HashSet<CArray>());
 }
예제 #29
0
    @Override
    protected void reportInContext(
        MetricContext context,
        SortedMap<String, Gauge> gauges,
        SortedMap<String, Counter> counters,
        SortedMap<String, Histogram> histograms,
        SortedMap<String, Meter> meters,
        SortedMap<String, Timer> timers) {

      Assert.assertEquals(context.getName(), CONTEXT_NAME);

      Assert.assertEquals(gauges.size(), 1);
      Assert.assertTrue(gauges.containsKey(QUEUE_SIZE));

      Assert.assertEquals(counters.size(), 1);
      Assert.assertTrue(counters.containsKey(RECORDS_PROCESSED));

      Assert.assertEquals(histograms.size(), 1);
      Assert.assertTrue(histograms.containsKey(RECORD_SIZE_DISTRIBUTION));

      Assert.assertEquals(meters.size(), 1);
      Assert.assertTrue(meters.containsKey(RECORD_PROCESS_RATE));

      Assert.assertEquals(timers.size(), 2);
      Assert.assertTrue(timers.containsKey(TOTAL_DURATION));
    }
예제 #30
0
  /**
   * 删除节点。 @Title: removeCacheNode
   *
   * @author: zzh
   * @date: 2016年12月4日 下午8:34:15
   * @version: v1.0.0
   */
  private static void removeCacheNode(String nodeIp) {

    // 删除当前IP的虚拟节点信息
    CacheNode cacheNode = new CacheNode(nodeIp);
    // 获取当前节点的虚拟节点信息
    List<VisualCacheNode> vNodesList = genVisualCacheNode(cacheNode);
    // 从hash环中删除虚拟节点信息
    for (VisualCacheNode c : vNodesList) {
      String vNodeName = c.getNodeName();
      String md5VisualNodeKey = DigestUtils.md5Hex(vNodeName); // 使用common-codec工具包
      int hashNodeName = DJBHash(md5VisualNodeKey);

      visualNodeMap.remove(hashNodeName);

      System.out.println("删除虚拟节点,虚拟节点名称:" + vNodeName + ",真实节点:" + c.getRealCacheNode());

      // 删除后,受到影响的节点:即数据和流量需要迁移到的节点信息
      SortedMap<Integer, VisualCacheNode> vs = visualNodeMap.tailMap(hashNodeName);
      VisualCacheNode nodeInfo = null;
      if (vs != null && vs.size() > 0) {
        int affectVnshash = vs.firstKey();
        nodeInfo = visualNodeMap.get(affectVnshash);
      } else {
        nodeInfo = visualNodeMap.get(visualNodeMap.firstKey());
      }
      System.out.println("删除当前虚拟节点" + vNodeName + " , 受到影响的虚拟节点(原本虚拟节点的数据和流量将迁移到此节点):" + nodeInfo);
    }

    // 踢出真实节点
    removeRealCache(nodeIp);
  }