/**
   * Method used to recursively scan our package map for classes whose names start with a given
   * prefix, ignoring case.
   *
   * @param prefix The prefix that the unqualified class names must match (ignoring case).
   * @param currentPkg The package that <code>map</code> belongs to (i.e. all levels of packages
   *     scanned before this one), separated by '<code>/</code>'.
   * @param addTo The list to add any matching <code>ClassFile</code>s to.
   */
  void getClassesWithNamesStartingWith(
      LibraryInfo info, String prefix, String currentPkg, List<ClassFile> addTo) {

    final int prefixLen = prefix.length();

    for (Map.Entry<String, PackageMapNode> children : subpackages.entrySet()) {
      String key = children.getKey();
      PackageMapNode child = children.getValue();
      child.getClassesWithNamesStartingWith(info, prefix, currentPkg + key + "/", addTo);
    }

    for (Map.Entry<String, ClassFile> cfEntry : classFiles.entrySet()) {
      // If value is null, we only lazily create the ClassFile if
      // necessary (i.e. if the class name does match what they've
      // typed).
      String className = cfEntry.getKey();
      if (className.regionMatches(true, 0, prefix, 0, prefixLen)) {
        ClassFile cf = cfEntry.getValue();
        if (cf == null) {
          String fqClassName = currentPkg + className + ".class";
          try {
            cf = info.createClassFile(fqClassName);
            cfEntry.setValue(cf); // Update the map
          } catch (IOException ioe) {
            ioe.printStackTrace();
          }
        }
        if (cf != null) { // possibly null if IOException above
          addTo.add(cf);
        }
      }
    }
  }
  @Test
  public void tables() throws Exception {

    final String referenceFile = "tables.txt";
    final File testOutputFile =
        File.createTempFile("schemacrawler." + referenceFile + ".", ".test");
    testOutputFile.delete();

    final PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(testOutputFile)));

    final Config config = Config.loadResource("/hsqldb.INFORMATION_SCHEMA.config.properties");
    final SchemaCrawlerOptions schemaCrawlerOptions = new SchemaCrawlerOptions(config);
    schemaCrawlerOptions.setSchemaInfoLevel(SchemaInfoLevel.maximum());
    schemaCrawlerOptions.setSchemaInclusionRule(
        new InclusionRule(InclusionRule.ALL, ".*\\.FOR_LINT"));

    final Database database = getDatabase(schemaCrawlerOptions);
    final Schema[] schemas = database.getSchemas().toArray(new Schema[0]);
    assertEquals("Schema count does not match", 5, schemas.length);
    for (final Schema schema : schemas) {
      final Table[] tables = database.getTables(schema).toArray(new Table[0]);
      Arrays.sort(tables, NamedObjectSort.alphabetical);
      for (final Table table : tables) {
        writer.println(String.format("o--> %s [%s]", table.getFullName(), table.getTableType()));
        final SortedMap<String, Object> tableAttributes =
            new TreeMap<String, Object>(table.getAttributes());
        for (final Entry<String, Object> tableAttribute : tableAttributes.entrySet()) {
          writer.println(
              String.format("      ~ %s=%s", tableAttribute.getKey(), tableAttribute.getValue()));
        }
        final Column[] columns = table.getColumns().toArray(new Column[0]);
        for (final Column column : columns) {
          writer.println(
              String.format("   o--> %s [%s]", column.getFullName(), column.getColumnDataType()));
          final SortedMap<String, Object> columnAttributes =
              new TreeMap<String, Object>(column.getAttributes());
          for (final Entry<String, Object> columnAttribute : columnAttributes.entrySet()) {
            writer.println(
                String.format(
                    "          ~ %s=%s", columnAttribute.getKey(), columnAttribute.getValue()));
          }
        }
      }
    }

    writer.flush();
    writer.close();

    final List<String> failures =
        TestUtility.compareOutput(METADATA_OUTPUT + referenceFile, testOutputFile);
    if (failures.size() > 0) {
      fail(failures.toString());
    }
  }
  /**
   * 保存错误信息到文件中
   *
   * @param throwable
   * @return 返回文件名称,便于将文件传送到服务器
   */
  private String saveCrashInfo2File(Throwable throwable) {

    StringBuffer sb = new StringBuffer();
    sb.append("Device information:\n");
    for (Map.Entry<String, String> entry : mDeviceInfos.entrySet()) {
      String key = entry.getKey();
      String value = entry.getValue();
      sb.append(key + "=" + value + "\n");
    }

    sb.append("\nApplication information:\n");
    for (Map.Entry<String, String> entry : mAppInfos.entrySet()) {
      String key = entry.getKey();
      String value = entry.getValue();
      sb.append(key + "=" + value + "\n");
    }
    sb.append("\nError information:\n");

    Writer writer = new StringWriter();
    PrintWriter printWriter = new PrintWriter(writer);
    throwable.printStackTrace(printWriter);
    Throwable cause = throwable.getCause();
    while (cause != null) {
      cause.printStackTrace(printWriter);
      cause = cause.getCause();
    }
    printWriter.close();
    String result = writer.toString();
    sb.append(result);

    try {
      DateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SSSS", Locale.getDefault());
      String time = formatter.format(new Date(System.currentTimeMillis()));
      String fileName = "crash_" + time + ".log";
      if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        String path = mContext.getPackageName() + "/log/crash";
        File dir = new File(Environment.getExternalStorageDirectory(), path);
        if (!dir.exists()) {
          dir.mkdirs();
        }
        FileOutputStream fos = new FileOutputStream(new File(dir, fileName));
        fos.write(sb.toString().getBytes());
        fos.close();
      }
      return fileName;
    } catch (Exception e) {
      Log.e(TAG, "an error occured while writing file...", e);
    }
    return null;
  }
Esempio n. 4
0
 public synchronized Map<String, String> getAllPrefix(final String prefix) {
   final Map<String, String> all = new TreeMap<String, String>();
   for (final Entry<String, String> e : properties.entrySet())
     if (e.getKey().startsWith(prefix)) {
       all.put(e.getKey(), e.getValue());
     }
   for (final Entry<String, String> e : override.entrySet())
     if (e.getKey().startsWith(prefix))
       if (e.getValue() == null) {
         all.remove(e.getKey());
       } else {
         all.put(e.getKey(), e.getValue());
       }
   return all;
 }
Esempio n. 5
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();
    }
  }
 StringBuilder addCanonicalHeaders(
     SortedMap<String, String> sortedFormattedHeaders, StringBuilder builder) {
   for (Map.Entry<String, String> entry : sortedFormattedHeaders.entrySet()) {
     builder.append(entry.getKey()).append(':').append(entry.getValue()).append('\n');
   }
   return builder;
 }
Esempio n. 7
0
  protected List<List<T>> bide(SequenceDatabase<T> sdb, int minSup, ResultHandler<T> handler) {
    List<T> prefix = sdb.getPrefix();

    if (prefix != null && backScan(sdb)) {
      return Collections.emptyList();
    }

    SortedMap<T, Integer> frequencies = sdb.getItemFrequencies(minSup);
    if (isPrefixClosed(sdb, frequencies)) {
      synchronized (handler) {
        handler.handle(prefix, sdb.getSupportOfPrefix(), sdb);
      }
    }

    List<List<T>> prefixes = new ArrayList<List<T>>();
    for (Map.Entry<T, Integer> entry : frequencies.entrySet()) {
      List<T> extendedPrefix = new ArrayList<T>();
      if (prefix != null) {
        extendedPrefix.addAll(prefix);
      }
      extendedPrefix.add(entry.getKey());
      prefixes.add(extendedPrefix);
    }
    return prefixes;
  }
Esempio n. 8
0
  private void fillColumnCombo(ItemListener listener) {
    // sort column names alphabetically
    final int columnCount = this.list.getTableModel().getColumnCount();
    final String[][] names = new String[columnCount][];
    final int[] indexes = new int[columnCount];
    for (int i = 0; i < columnCount; i++) {
      names[i] = this.list.getColumnNames(i);
      indexes[i] = 0;
    }
    // use column index as columns names are not unique
    final SortedMap<String, Integer> map = solve(names, indexes);
    final List<Column> cols = new ArrayList<Column>(columnCount);
    cols.add(TOUT);
    for (final Entry<String, Integer> e : map.entrySet()) {
      final int colIndex = e.getValue().intValue();
      final String[] colNames = names[colIndex];
      cols.add(new Column(e.getKey(), colNames[colNames.length - 1], colIndex));
    }

    // don't fire when filling, we will fire when selecting
    this.comboColonnePourRecherche.removeItemListener(listener);
    final ListComboBoxModel comboModel =
        (ListComboBoxModel) this.comboColonnePourRecherche.getModel();
    assert !comboModel.isSelectOnAdd() : "Otherwise our following select might not fire";
    comboModel.removeAllElements();
    comboModel.addAll(cols);
    this.comboColonnePourRecherche.addItemListener(listener);
  }
Esempio n. 9
0
  private static XYDatasetMinMax createDeltaDataset(
      String name, SortedMap<TimeAxisKey, DiffStat> aggregatedDiffstats) {

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    int minimum = 0;
    int maximum = 0;

    TimeSeries addedSeries = new TimeSeries(name);
    TimeSeries removedSeries = new TimeSeries(name);
    for (Entry<TimeAxisKey, DiffStat> entry : aggregatedDiffstats.entrySet()) {
      TimeAxisKey timeAxisKey = entry.getKey();
      DiffStat diffStat = entry.getValue();
      RegularTimePeriod period = timeAxisKey.toPeriod();

      int added = diffStat.added();
      maximum = max(maximum, added);
      addedSeries.add(period, Integer.valueOf(added));

      int removed = -diffStat.removed();
      minimum = min(minimum, removed);
      removedSeries.add(period, Integer.valueOf(removed));
    }
    dataset.addSeries(addedSeries);
    dataset.addSeries(removedSeries);

    return new XYDatasetMinMax(dataset, minimum, maximum);
  }
Esempio n. 10
0
  /* If you set jmx.serial.form to "1.2.0" or "1.2.1", then we are
     bug-compatible with those versions.  Specifically, field names
     are forced to lower-case before being written.  This
     contradicts the spec, which, though it does not mention
     serialization explicitly, does say that the case of field names
     is preserved.  But in 1.2.0 and 1.2.1, this requirement was not
     met.  Instead, field names in the descriptor map were forced to
     lower case.  Those versions expect this to have happened to a
     descriptor they deserialize and e.g. getFieldValue will not
     find a field whose name is spelt with a different case.
  */
  private void writeObject(ObjectOutputStream out) throws IOException {
    ObjectOutputStream.PutField fields = out.putFields();
    boolean compat = "1.0".equals(serialForm);
    if (compat) fields.put("currClass", currClass);

    /* Purge the field "targetObject" from the DescriptorSupport before
     * serializing since the referenced object is typically not
     * serializable.  We do this here rather than purging the "descriptor"
     * variable below because that HashMap doesn't do case-insensitivity.
     * See CR 6332962.
     */
    SortedMap<String, Object> startMap = descriptorMap;
    if (startMap.containsKey("targetObject")) {
      startMap = new TreeMap<String, Object>(descriptorMap);
      startMap.remove("targetObject");
    }

    final HashMap<String, Object> descriptor;
    if (compat || "1.2.0".equals(serialForm) || "1.2.1".equals(serialForm)) {
      descriptor = new HashMap<String, Object>();
      for (Map.Entry<String, Object> entry : startMap.entrySet())
        descriptor.put(entry.getKey().toLowerCase(), entry.getValue());
    } else descriptor = new HashMap<String, Object>(startMap);

    fields.put("descriptor", descriptor);
    out.writeFields();
  }
  private void collectTimerReports(
      List<DBObject> docs, SortedMap<String, Timer> timers, Date timestamp) {
    if (timers.isEmpty()) return;
    for (Map.Entry<String, Timer> entry : timers.entrySet()) {
      final BasicDBObject report = getBasicDBObject(timestamp, entry.getKey(), "timer");
      final Timer v = entry.getValue();
      final Snapshot s = v.getSnapshot();
      // meter part
      report.put("count", v.getCount());
      report.put("rate-unit", getRateUnit());
      report.put("1-minute-rate", convertRate(v.getOneMinuteRate()));
      report.put("5-minute-rate", convertRate(v.getFiveMinuteRate()));
      report.put("15-minute-rate", convertRate(v.getFifteenMinuteRate()));
      report.put("mean-rate", convertRate(v.getMeanRate()));

      // histogram part
      report.put("duration-unit", getDurationUnit());
      report.put("75-percentile", convertDuration(s.get75thPercentile()));
      report.put("95-percentile", convertDuration(s.get95thPercentile()));
      report.put("98-percentile", convertDuration(s.get98thPercentile()));
      report.put("99-percentile", convertDuration(s.get99thPercentile()));
      report.put("999-percentile", convertDuration(s.get999thPercentile()));
      report.put("max", convertDuration(s.getMax()));
      report.put("min", convertDuration(s.getMin()));
      report.put("mean", convertDuration(s.getMean()));
      report.put("median", convertDuration(s.getMedian()));
      report.put("stddev", convertDuration(s.getStdDev()));
      docs.add(report);
    }
  }
Esempio n. 12
0
  public static SortedMap<Text, SortedMap<ColumnFQ, Value>> getTabletEntries(
      SortedMap<Key, Value> tabletKeyValues, List<ColumnFQ> columns) {
    TreeMap<Text, SortedMap<ColumnFQ, Value>> tabletEntries =
        new TreeMap<Text, SortedMap<ColumnFQ, Value>>();

    HashSet<ColumnFQ> colSet = null;
    if (columns != null) {
      colSet = new HashSet<ColumnFQ>(columns);
    }

    for (Entry<Key, Value> entry : tabletKeyValues.entrySet()) {

      if (columns != null && !colSet.contains(new ColumnFQ(entry.getKey()))) {
        continue;
      }

      Text row = entry.getKey().getRow();

      SortedMap<ColumnFQ, Value> colVals = tabletEntries.get(row);
      if (colVals == null) {
        colVals = new TreeMap<ColumnFQ, Value>();
        tabletEntries.put(row, colVals);
      }

      colVals.put(new ColumnFQ(entry.getKey()), entry.getValue());
    }

    return tabletEntries;
  }
Esempio n. 13
0
  /** Called after every put. In case of a problem, do nothing but output the error in log. */
  public void save() throws IOException {
    /* currently unused, but may help to fix configuration issues in future */
    putInteger("josm.version", Version.getInstance().getVersion());

    updateSystemProperties();
    File prefFile = new File(getPreferencesDirFile(), "preferences");

    // Backup old preferences if there are old preferences
    if (prefFile.exists()) {
      copyFile(prefFile, new File(prefFile + "_backup"));
    }

    final PrintWriter out =
        new PrintWriter(
            new OutputStreamWriter(new FileOutputStream(prefFile + "_tmp"), "utf-8"), false);
    for (final Entry<String, String> e : properties.entrySet()) {
      String s = defaults.get(e.getKey());
      /* don't save default values */
      if (s == null || !s.equals(e.getValue())) {
        out.println(e.getKey() + "=" + e.getValue());
      }
    }
    out.close();

    File tmpFile = new File(prefFile + "_tmp");
    copyFile(tmpFile, prefFile);
    tmpFile.delete();
  }
Esempio n. 14
0
  private static String createStringToSign(
      SortedMap<String, String> paramMap,
      String sendingContent,
      String requestMethod,
      String domain,
      String path)
      throws UnsupportedEncodingException {
    StringBuilder sb = new StringBuilder();
    sb.append(requestMethod).append("\n").append(domain).append("\n").append(path).append("\n");
    int c = 0;
    for (Entry<String, String> entry : paramMap.entrySet()) {
      if (!excludeSignatureParamSet.contains(entry.getKey())) {
        if (c != 0) {
          sb.append("&");
        }
        sb.append(entry.getKey()).append("=").append(entry.getValue());
        ++c;
      }
    }
    if (c > 0) {
      sb.append("\n");
    }
    if (StringUtils.isNotEmpty(sendingContent)) {
      sb.append(sendingContent).append("\n");
    }

    return sb.toString();
  }
Esempio n. 15
0
 @Override
 public boolean isLinked() {
   for (Map.Entry<Integer, InstructionReference> jumpEntry : jumpTable.entrySet()) {
     if (!jumpEntry.getValue().isResolved()) return false;
   }
   return true;
 }
Esempio n. 16
0
 /**
  * Returns an XML String representing the descriptor.
  *
  * <p>The format is not defined, but an implementation must ensure that the string returned by
  * this method can be used to build an equivalent descriptor when instantiated using the
  * constructor {@link #DescriptorSupport(String) DescriptorSupport(String inStr)}.
  *
  * <p>Fields which are not String objects will have toString() called on them to create the value.
  * The value will be enclosed in parentheses. It is not guaranteed that you can reconstruct these
  * objects unless they have been specifically set up to support toString() in a meaningful format
  * and have a matching constructor that accepts a String in the same format.
  *
  * <p>If the descriptor is empty the following String is returned:
  * &lt;Descriptor&gt;&lt;/Descriptor&gt;
  *
  * @return the XML string.
  * @exception RuntimeOperationsException for illegal value for field Names or field Values. If the
  *     XML formatted string construction fails for any reason, this exception will be thrown.
  */
 public synchronized String toXMLString() {
   final StringBuilder buf = new StringBuilder("<Descriptor>");
   Set<Map.Entry<String, Object>> returnedSet = descriptorMap.entrySet();
   for (Map.Entry<String, Object> currElement : returnedSet) {
     final String name = currElement.getKey();
     Object value = currElement.getValue();
     String valueString = null;
     /* Set valueString to non-null if and only if this is a string that
     cannot be confused with the encoding of an object.  If it
     could be so confused (surrounded by parentheses) then we
     call makeFieldValue as for any non-String object and end
     up with an encoding like "(java.lang.String/(thing))".  */
     if (value instanceof String) {
       final String svalue = (String) value;
       if (!svalue.startsWith("(") || !svalue.endsWith(")")) valueString = quote(svalue);
     }
     if (valueString == null) valueString = makeFieldValue(value);
     buf.append("<field name=\"")
         .append(name)
         .append("\" value=\"")
         .append(valueString)
         .append("\"></field>");
   }
   buf.append("</Descriptor>");
   return buf.toString();
 }
Esempio n. 17
0
 @Override
 public void link(Resolver<ClassData, String> classCache, MethodData methodData)
     throws LinkException {
   for (Map.Entry<Integer, InstructionReference> jumpEntry : jumpTable.entrySet()) {
     jumpEntry.getValue().resolve(methodData);
   }
 }
  public SortedMap<String, Requirement> read() throws IOException {
    SortedMap<String, Requirement> map = new ChildrenFirstOrderedMap();
    File jsonFile = new File(outputDirectory, rootDirectory + ".json");
    if (!jsonFile.exists()) {
      return map;
    }

    SortedMap<String, Requirement> storedRequirementsMap;
    Type requirementsMapType = new TypeToken<SortedMap<String, Requirement>>() {}.getType();
    try (FileReader reader = new FileReader(jsonFile)) {
      storedRequirementsMap = gson.fromJson(reader, requirementsMapType);
      if (storedRequirementsMap == null) {
        storedRequirementsMap = Collections.emptySortedMap();
      }
    }
    map.putAll(storedRequirementsMap);

    // reset the parents
    for (Map.Entry<String, Requirement> entry : storedRequirementsMap.entrySet()) {
      String key = entry.getKey();
      if (key.contains(".")) {
        String parent = key.substring(0, key.lastIndexOf("."));
        Requirement child = entry.getValue();
        updateParentChildren(map, parent, child);
      }
    }
    return map;
  }
  /**
   * @param boundType
   * @return
   * @see javax.xml.bind.annotation.adapters.XmlAdapter#marshal(java.lang.Object)
   */
  @Override
  public S marshal(final Map<K, V> boundType) {
    // Do not generate an empty tag for an empty map
    if ((boundType == null) || boundType.isEmpty()) {
      return null;
    }
    // Sort incoming map
    // Default sort
    SortedMap<K, V> sortedMap = CollectionUtil.newSortedMap();

    // Specified sort
    if (comparator != null) {
      sortedMap = CollectionUtil.newSortedMap(comparator);
    }

    sortedMap.putAll(boundType);

    // Convert to a list
    final List<E> list = CollectionUtil.newList();
    for (final Map.Entry<K, V> entry : sortedMap.entrySet()) {
      final E entryEntity = newEntryTypeInstance();
      entryEntity.setKey(entry.getKey());
      entryEntity.setValue(entry.getValue());
      list.add(entryEntity);
    }

    final S map = newValueTypeInstance();
    setValueTypeArray(map, list);
    return map;
  }
Esempio n. 20
0
  @Override
  public Object getAsObject(FacesContext fc, UIComponent uic, String string) {
    try {
      if (string == null) {
        return null;
      }

      String qstr = string.trim();

      if (qstr.isEmpty()) {
        return null;
      }

      if (timeZoneMap.containsKey(qstr)) {
        return timeZoneMap.get(qstr);
      }

      return timeZoneMap
          .entrySet()
          .stream()
          .filter(it -> it.getKey().equalsIgnoreCase(qstr))
          .map(it -> it.getValue())
          .findFirst()
          .orElse(TimeZone.getTimeZone(string));
    } catch (Exception ex) {
      ex.printStackTrace();
      throw new ConverterException(ex);
    }
  }
Esempio n. 21
0
 public List<NamedTestResult> getNamedTestResults() {
   if (namedTestResults.isEmpty()) {
     return Lists.newArrayList();
   } else {
     return convert(namedTestResults.entrySet(), fromMapEntriesToNamedTestResults());
   }
 }
  /** parses a list of MappingCharFilter style rules into a custom byte[] type table */
  private byte[] parseTypes(Collection<String> rules) {
    SortedMap<Character, Byte> typeMap = new TreeMap<Character, Byte>();
    for (String rule : rules) {
      Matcher m = typePattern.matcher(rule);
      if (!m.find()) throw new RuntimeException("Invalid Mapping Rule : [" + rule + "]");
      String lhs = parseString(m.group(1).trim());
      Byte rhs = parseType(m.group(2).trim());
      if (lhs.length() != 1)
        throw new RuntimeException(
            "Invalid Mapping Rule : [" + rule + "]. Only a single character is allowed.");
      if (rhs == null)
        throw new RuntimeException("Invalid Mapping Rule : [" + rule + "]. Illegal type.");
      typeMap.put(lhs.charAt(0), rhs);
    }

    // ensure the table is always at least as big as DEFAULT_WORD_DELIM_TABLE for performance
    byte types[] =
        new byte
            [Math.max(
                typeMap.lastKey() + 1, WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE.length)];
    for (int i = 0; i < types.length; i++) types[i] = WordDelimiterIterator.getType(i);
    for (Map.Entry<Character, Byte> mapping : typeMap.entrySet())
      types[mapping.getKey()] = mapping.getValue();
    return types;
  }
Esempio n. 23
0
  protected boolean isPrefixClosed(SequenceDatabase<T> sdb, SortedMap<T, Integer> frequencies) {
    List<T> prefix = sdb.getPrefix();
    if (prefix == null) {
      return false;
    }

    int support = sdb.getSupportOfPrefix();
    if (logger.isDebugEnabled()) {
      logger.debug("Testing: {}:{}", prefix, support);
    }

    for (Map.Entry<T, Integer> entry : frequencies.entrySet()) {
      if (entry.getValue() == support) {
        if (logger.isTraceEnabled()) {
          logger.trace(
              "Open: The prefix can be extended by a forward extension item {}.", entry.getKey());
        }
        return false; /* Found a forward extension item */
      }
    }

    if (!hasBackwardExtensionItem(sdb)) {
      if (logger.isDebugEnabled()) {
        logger.debug("Closed: {}:{}", prefix, support);
      }
      return true;
    }
    return false;
  }
  /** @see it.matrix.aod.postel.at.ATParserImpl#getRigheDettaglio(java.util.SortedMap) */
  @Override
  public Dettaglio[] getRigheDettaglio(SortedMap<Integer, String> _map) {
    Dettaglio[] righeDettaglio = new Dettaglio[_map.size()];
    Iterator<Entry<Integer, String>> mit = _map.entrySet().iterator();
    int i = 0;
    while (mit.hasNext()) {
      Entry<Integer, String> entry = (Entry<Integer, String>) mit.next();
      String value = entry.getValue();
      String record = value;
      Dettaglio rigaDettaglio = new Dettaglio();
      rigaDettaglio.setPeriodoRiferimento("");
      if (!record.equals("") && record.length() >= 55) {

        rigaDettaglio.setDescrizione(value.substring(0, 55));
        value = value.substring(rigaDettaglio.getDescrizione().length()).trim();

        if (record.charAt(61) != ' ') {
          rigaDettaglio.setPrezzo(value.substring(0, value.indexOf(' ')));
          value = value.substring(rigaDettaglio.getPrezzo().length()).trim();
        } else {
          rigaDettaglio.setPrezzo("");
        }
        if (record.charAt(68) != ' ') {
          rigaDettaglio.setQuantita(value.substring(0, value.indexOf(' ')));
          value = value.substring(rigaDettaglio.getQuantita().length()).trim();
        } else {
          rigaDettaglio.setQuantita("");
        }
        if (record.charAt(70) != ' ') {
          rigaDettaglio.setAliquotaIva(value.substring(0, value.indexOf(' ')));
          value = value.substring(rigaDettaglio.getQuantita().length()).trim();
        } else {
          rigaDettaglio.setAliquotaIva(value.substring(0, value.indexOf(' ')));
        }

        value = value.substring(rigaDettaglio.getAliquotaIva().length()).trim();
        rigaDettaglio.setImporto(value);

      } else if (!record.equals("") && record.length() < 55) {
        rigaDettaglio.setAliquotaIva("");
        rigaDettaglio.setImporto("");
        rigaDettaglio.setPrezzo("");
        rigaDettaglio.setPeriodoRiferimento("");
        rigaDettaglio.setQuantita("");
        rigaDettaglio.setDescrizione(record.trim());

      } else {
        rigaDettaglio.setAliquotaIva("");
        rigaDettaglio.setDescrizione("");
        rigaDettaglio.setImporto("");
        rigaDettaglio.setPrezzo("");
        rigaDettaglio.setPeriodoRiferimento("");
        rigaDettaglio.setQuantita("");
      }
      righeDettaglio[i] = rigaDettaglio;
      i++;
    }

    return righeDettaglio;
  }
  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);
    }
  }
  public ImponibileIva[] getRigheImponibiliIva(SortedMap<Integer, String> _map) {

    ImponibileIva[] righeImponibiliIva = new ImponibileIva[_map.size()];

    Iterator<Entry<Integer, String>> mit = _map.entrySet().iterator();

    while (mit.hasNext()) {
      Entry<Integer, String> entry = (Entry<Integer, String>) mit.next();
      String value = entry.getValue();

      ImponibileIva imponibileIva = new ImponibileIva();
      imponibileIva.setIndice(entry.getKey());
      if (!value.equals("")) {

        imponibileIva.setImponibile(value.substring(0, value.indexOf(' ')));
        value = value.substring(imponibileIva.getImponibile().length()).trim();
        imponibileIva.setAliquota(value.substring(0, value.indexOf(' ')));
        value = value.substring(imponibileIva.getAliquota().length()).trim();
        imponibileIva.setDescrizione(value);
      } else {

        imponibileIva.setImponibile("");
        imponibileIva.setAliquota("");
        imponibileIva.setDescrizione("");
      }
      righeImponibiliIva[entry.getKey()] = imponibileIva;
    }
    return righeImponibiliIva;
  }
 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;
 }
Esempio n. 28
0
 /**
  * Gets the trap varbinds decode.
  *
  * @param trap the trap object
  * @return the trap varbinds decode
  */
 protected List<Varbindsdecode> getTrapVarbindsDecode(Notification trap) {
   Map<String, Varbindsdecode> decode = new LinkedHashMap<String, Varbindsdecode>();
   int vbNum = 1;
   for (SmiVariable var : trap.getObjects()) {
     String parmName = "parm[#" + vbNum + "]";
     SmiPrimitiveType type = var.getType().getPrimitiveType();
     if (type.equals(SmiPrimitiveType.ENUM)) {
       SortedMap<BigInteger, String> map = new TreeMap<BigInteger, String>();
       for (SmiNamedNumber v : var.getType().getEnumValues()) {
         map.put(v.getValue(), v.getId());
       }
       for (Entry<BigInteger, String> entry : map.entrySet()) {
         if (!decode.containsKey(parmName)) {
           Varbindsdecode newVarbind = new Varbindsdecode();
           newVarbind.setParmid(parmName);
           decode.put(newVarbind.getParmid(), newVarbind);
         }
         Decode d = new Decode();
         d.setVarbinddecodedstring(entry.getValue());
         d.setVarbindvalue(entry.getKey().toString());
         decode.get(parmName).addDecode(d);
       }
     }
     vbNum++;
   }
   return new ArrayList<Varbindsdecode>(decode.values());
 }
Esempio n. 29
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;
  }
Esempio n. 30
0
 /**
  * Loads images into this container. You must call {@link #setContext(Context)} first to set the
  * context for loading images.
  */
 public synchronized void init() {
   if (null != images) return;
   // store images sorted by their file name suffix
   SortedMap<String, Integer> builtinImageIds = new TreeMap<String, Integer>();
   for (Field field : R.drawable.class.getFields())
     try {
       if (Modifier.STATIC == (field.getModifiers() & Modifier.STATIC)
           && Integer.TYPE == field.getType()
           && field.getName().startsWith(IMAGE_FILE_PREFIX)) {
         String suffix = field.getName().substring(IMAGE_FILE_PREFIX.length());
         int id = field.getInt(null);
         builtinImageIds.put(suffix, id);
       }
     } catch (IllegalAccessException skipNoAccess) {
     }
   images = new ImageEntry[builtinImageIds.size()];
   int i = 0;
   // add built-in images
   for (Map.Entry<String, Integer> entry : builtinImageIds.entrySet()) {
     Integer id = entry.getValue();
     Integer difficulty = null;
     try {
       difficulty = Integer.valueOf(entry.getKey());
     } catch (NumberFormatException ignored) {
     }
     ImageEntry image;
     if (null != difficulty && 0 <= difficulty && 3 > difficulty)
       image = new ImageEntry(id, difficulty + 3);
     else image = new ImageEntry(id);
     images[i++] = image;
   }
   updateUserImages();
 }