Beispiel #1
2
 /**
  * This function is used to re-run the analyser, and re-create the rows corresponding the its
  * results.
  */
 private void refreshReviewTable() {
   reviewPanel.removeAll();
   rows.clear();
   GridBagLayout gbl = new GridBagLayout();
   reviewPanel.setLayout(gbl);
   GridBagConstraints gbc = new GridBagConstraints();
   gbc.fill = GridBagConstraints.HORIZONTAL;
   gbc.gridy = 0;
   try {
     Map<String, Long> sums =
         analyser.processLogFile(config.getLogFilename(), fromDate.getDate(), toDate.getDate());
     for (Entry<String, Long> entry : sums.entrySet()) {
       String project = entry.getKey();
       double hours = 1.0 * entry.getValue() / (1000 * 3600);
       addRow(gbl, gbc, project, hours);
     }
     for (String project : main.getProjectsTree().getTopLevelProjects())
       if (!rows.containsKey(project)) addRow(gbl, gbc, project, 0);
     gbc.insets = new Insets(10, 0, 0, 0);
     addLeftLabel(gbl, gbc, "TOTAL");
     gbc.gridx = 1;
     gbc.weightx = 1;
     totalLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 3));
     gbl.setConstraints(totalLabel, gbc);
     reviewPanel.add(totalLabel);
     gbc.weightx = 0;
     addRightLabel(gbl, gbc);
   } catch (IOException e) {
     e.printStackTrace();
   }
   recomputeTotal();
   pack();
 }
 /**
  * Get the vertex with the maximal label.
  *
  * @param vertexLabels Map that gives a label for each vertex.
  * @return Vertex with the maximal label.
  */
 private V getMaxLabelVertex(Map<V, Integer> vertexLabels) {
   Iterator<Entry<V, Integer>> iterator = vertexLabels.entrySet().iterator();
   Entry<V, Integer> max = iterator.next();
   while (iterator.hasNext()) {
     Entry<V, Integer> e = iterator.next();
     if (e.getValue() > max.getValue()) {
       max = e;
     }
   }
   return max.getKey();
 }
 /**
  * Generates a JavaScript command to update the JavaScript agent's parameter names. Follows this
  * format: <code>agent.updateParameterNames({serial: 'XXXX', parameter: 'YYYY'});</code>
  *
  * @return A JavaScript Command.
  */
 public String generateCommand(String type, Map<String, ?> props) {
   StringBuilder buff = new StringBuilder(agentName);
   buff.append(".update").append(type).append("({");
   for (Entry<String, ?> entry : props.entrySet()) {
     if (entry.getValue() instanceof String) {
       buff.append(entry.getKey()).append(": '").append(entry.getValue()).append("',");
     } else {
       buff.append(entry.getKey()).append(": ").append(entry.getValue()).append(",");
     }
   }
   buff.deleteCharAt(buff.length() - 1);
   buff.append("});");
   return buff.toString();
 }
 /**
  * Returns <tt>true</tt> if this map maps one or more keys to this value. More formally, returns
  * <tt>true</tt> if and only if this map contains at least one mapping to a value <tt>v</tt> such
  * that <tt>(value==null ? v==null : value.equals(v))</tt>. This operation will probably require
  * time linear in the map size for most implementations of map.
  *
  * <p>This implementation iterates over entrySet() searching for an entry with the specified
  * value. If such an entry is found, <tt>true</tt> is returned. If the iteration terminates
  * without finding such an entry, <tt>false</tt> is returned. Note that this implementation
  * requires linear time in the size of the map.
  *
  * @param value value whose presence in this map is to be tested.
  * @return <tt>true</tt> if this map maps one or more keys to this value.
  */
 public boolean containsValue(Object value) {
   Iterator i = entrySet().iterator();
   if (value == null) {
     while (i.hasNext()) {
       Entry e = (Entry) i.next();
       if (e.getValue() == null) return true;
     }
   } else {
     while (i.hasNext()) {
       Entry e = (Entry) i.next();
       if (value.equals(e.getValue())) return true;
     }
   }
   return false;
 }
 @Override
 public Map<String, Set<String>> unmarshal(List<StringSetMapAdapter.Entry> entryList)
     throws Exception {
   Map<String, Set<String>> map = new HashMap<String, Set<String>>();
   for (Entry entry : entryList) {
     if (map.containsKey(entry.getKey())) {
       map.get(entry.getKey()).add(entry.getValue());
     } else {
       Set<String> valueSet = new HashSet<String>();
       valueSet.add(entry.getValue());
       map.put(entry.getKey(), valueSet);
     }
   }
   return map;
 }
 /**
  * Returns the value to which this map maps the specified key. Returns <tt>null</tt> if the map
  * contains no mapping for this key. A return value of <tt>null</tt> does not <i>necessarily</i>
  * indicate that the map contains no mapping for the key; it's also possible that the map
  * explicitly maps the key to <tt>null</tt>. The containsKey operation may be used to distinguish
  * these two cases.
  *
  * <p>This implementation iterates over <tt>entrySet()</tt> searching for an entry with the
  * specified key. If such an entry is found, the entry's value is returned. If the iteration
  * terminates without finding such an entry, <tt>null</tt> is returned. Note that this
  * implementation requires linear time in the size of the map; many implementations will override
  * this method.
  *
  * @param key key whose associated value is to be returned.
  * @return the value to which this map maps the specified key.
  * @throws NullPointerException if the key is <tt>null</tt> and this map does not not permit
  *     <tt>null</tt> keys.
  * @see #containsKey(Object)
  */
 public Object get(Object key) {
   Iterator i = entrySet().iterator();
   if (key == null) {
     while (i.hasNext()) {
       Entry e = (Entry) i.next();
       if (e.getKey() == null) return e.getValue();
     }
   } else {
     while (i.hasNext()) {
       Entry e = (Entry) i.next();
       if (key.equals(e.getKey())) return e.getValue();
     }
   }
   return null;
 }
Beispiel #7
0
  @Nullable
  public InstanceFactory findInstanceFactory(@Nonnull Type mockedType) {
    InstanceFactory instanceFactory = mockedTypesAndInstances.get(mockedType);

    if (instanceFactory != null) {
      return instanceFactory;
    }

    Class<?> mockedClass = getClassType(mockedType);
    //noinspection ReuseOfLocalVariable
    instanceFactory = mockedTypesAndInstances.get(mockedClass);

    if (instanceFactory != null) {
      return instanceFactory;
    }

    boolean abstractType = mockedClass.isInterface() || isAbstract(mockedClass.getModifiers());

    for (Entry<Type, InstanceFactory> entry : mockedTypesAndInstances.entrySet()) {
      Type registeredMockedType = entry.getKey();
      Class<?> registeredMockedClass = getClassType(registeredMockedType);

      if (abstractType) {
        registeredMockedClass = getMockedClassOrInterfaceType(registeredMockedClass);
      }

      if (mockedClass.isAssignableFrom(registeredMockedClass)) {
        instanceFactory = entry.getValue();
        break;
      }
    }

    return instanceFactory;
  }
  @Override
  public AbstractLongList getRawNeighborhood(AtomicQuery query, InternalTitanTransaction tx) {
    Preconditions.checkArgument(
        QueryUtil.queryCoveredByDiskIndexes(query),
        "Raw retrieval is currently does not support in-memory filtering");
    List<Entry> entries = queryForEntries(query, tx.getTxHandle());

    InternalTitanVertex node = query.getNode();
    TitanType titanType = null;
    if (query.hasEdgeTypeCondition()) titanType = query.getTypeCondition();

    AbstractLongList result = new LongArrayList();

    for (Entry entry : entries) {
      if (!query.hasEdgeTypeCondition()) {
        long etid = IDHandler.readEdgeType(entry.getColumn(), idManager);
        if (titanType == null || titanType.getID() != etid) {
          titanType = getTypeFromID(etid, tx);
        }
      }
      if (titanType.isPropertyKey() || (!titanType.isModifiable() && !query.queryUnmodifiable())) {
        continue; // Skip since it does not match query
      }
      // Get neighboring node id
      long iddiff = VariableLong.read(entry.getValue());
      long nghid = iddiff + node.getID();
      result.add(nghid);

      if (result.size() >= query.getLimit()) break;
    }
    return result;
  }
  /**
   * Compares the specified object with this map for equality. Returns <tt>true</tt> if the given
   * object is also a map and the two maps represent the same mappings. More formally, two maps
   * <tt>t1</tt> and <tt>t2</tt> represent the same mappings if
   * <tt>t1.keySet().equals(t2.keySet())</tt> and for every key <tt>k</tt> in <tt>t1.keySet()</tt>,
   * <tt> (t1.get(k)==null ? t2.get(k)==null : t1.get(k).equals(t2.get(k))) </tt>. This ensures that
   * the <tt>equals</tt> method works properly across different implementations of the map
   * interface.
   *
   * <p>This implementation first checks if the specified object is this map; if so it returns
   * <tt>true</tt>. Then, it checks if the specified object is a map whose size is identical to the
   * size of this set; if not, it it returns <tt>false</tt>. If so, it iterates over this map's
   * <tt>entrySet</tt> collection, and checks that the specified map contains each mapping that this
   * map contains. If the specified map fails to contain such a mapping, <tt>false</tt> is returned.
   * If the iteration completes, <tt>true</tt> is returned.
   *
   * @param o object to be compared for equality with this map.
   * @return <tt>true</tt> if the specified object is equal to this map.
   */
  public boolean equals(Object o) {
    if (o == this) return true;

    if (!(o instanceof Map)) return false;
    Map t = (Map) o;
    if (t.size() != size()) return false;

    try {
      Iterator i = entrySet().iterator();
      while (i.hasNext()) {
        Entry e = (Entry) i.next();
        Object key = e.getKey();
        Object value = e.getValue();
        if (value == null) {
          if (!(t.get(key) == null && t.containsKey(key))) return false;
        } else {
          if (!value.equals(t.get(key))) return false;
        }
      }
    } catch (ClassCastException unused) {
      return false;
    } catch (NullPointerException unused) {
      return false;
    }

    return true;
  }
Beispiel #10
0
 /**
  * Parses connection options.
  *
  * @param options options
  * @return connection properties
  */
 private static Properties connProps(final HashMap<String, String> options) {
   final Properties props = new Properties();
   for (final Entry<String, String> entry : options.entrySet()) {
     props.setProperty(entry.getKey(), entry.getValue());
   }
   return props;
 }
  public void checkSlice(
      String[][] values, Set<KeyColumn> removed, int key, int start, int end, int limit) {
    List<Entry> entries;
    if (limit <= 0)
      entries =
          store.getSlice(
              KeyValueStoreUtil.getBuffer(key),
              KeyValueStoreUtil.getBuffer(start),
              KeyValueStoreUtil.getBuffer(end),
              tx);
    else
      entries =
          store.getSlice(
              KeyValueStoreUtil.getBuffer(key),
              KeyValueStoreUtil.getBuffer(start),
              KeyValueStoreUtil.getBuffer(end),
              limit,
              tx);

    int pos = 0;
    for (int i = start; i < end; i++) {
      if (removed.contains(new KeyColumn(key, i))) continue;
      if (limit <= 0 || pos < limit) {
        Entry entry = entries.get(pos);
        int col = KeyValueStoreUtil.getID(entry.getColumn());
        String str = KeyValueStoreUtil.getString(entry.getValue());
        assertEquals(i, col);
        assertEquals(values[key][i], str);
      }
      pos++;
    }
    assertNotNull(entries);
    if (limit > 0 && pos > limit) assertEquals(limit, entries.size());
    else assertEquals(pos, entries.size());
  }
 /**
  * Copies all of the mappings from the specified map to this map (optional operation). These
  * mappings will replace any mappings that this map had for any of the keys currently in the
  * specified map.
  *
  * <p>This implementation iterates over the specified map's <tt>entrySet()</tt> collection, and
  * calls this map's <tt>put</tt> operation once for each entry returned by the iteration.
  *
  * <p>Note that this implementation throws an <tt>UnsupportedOperationException</tt> if this map
  * does not support the <tt>put</tt> operation and the specified map is nonempty.
  *
  * @param t mappings to be stored in this map.
  * @throws UnsupportedOperationException if the <tt>putAll</tt> operation is not supported by this
  *     map.
  * @throws ClassCastException if the class of a key or value in the specified map prevents it from
  *     being stored in this map.
  * @throws IllegalArgumentException if some aspect of a key or value in the specified map prevents
  *     it from being stored in this map.
  * @throws NullPointerException the specified map is <tt>null</tt>, or if this map does not permit
  *     <tt>null</tt> keys or values, and the specified map contains <tt>null</tt> keys or values.
  */
 public void putAll(Map t) {
   Iterator i = t.entrySet().iterator();
   while (i.hasNext()) {
     Entry e = (Entry) i.next();
     put(e.getKey(), e.getValue());
   }
 }
 /**
  * Copies the key/value mappings in <tt>map</tt> into this map. Note that this will be a
  * <b>deep</b> copy, as storage is by primitive value.
  *
  * @param map a <code>Map</code> value
  */
 public void putAll(Map<? extends Character, ? extends Double> map) {
   Iterator<? extends Entry<? extends Character, ? extends Double>> it = map.entrySet().iterator();
   for (int i = map.size(); i-- > 0; ) {
     Entry<? extends Character, ? extends Double> e = it.next();
     this.put(e.getKey(), e.getValue());
   }
 }
Beispiel #14
0
  /** Code completion. */
  private void complete() {
    if (selected()) return;

    // find first character
    final int caret = editor.pos(), startPos = editor.completionStart();
    final String prefix = string(substring(editor.text(), startPos, caret));
    if (prefix.isEmpty()) return;

    // find insertion candidates
    final TreeMap<String, String> tmp = new TreeMap<>();
    for (final Entry<String, String> entry : REPLACE.entrySet()) {
      final String key = entry.getKey();
      if (key.startsWith(prefix)) tmp.put(key, entry.getValue());
    }

    if (tmp.size() == 1) {
      // insert single candidate
      complete(tmp.values().iterator().next(), startPos);
    } else if (!tmp.isEmpty()) {
      // show popup menu
      final JPopupMenu pm = new JPopupMenu();
      final ActionListener al =
          new ActionListener() {
            @Override
            public void actionPerformed(final ActionEvent ae) {
              complete(ae.getActionCommand().replaceAll("^.*?\\] ", ""), startPos);
            }
          };

      for (final Entry<String, String> entry : tmp.entrySet()) {
        final JMenuItem mi = new JMenuItem("[" + entry.getKey() + "] " + entry.getValue());
        pm.add(mi);
        mi.addActionListener(al);
      }
      pm.addSeparator();
      final JMenuItem mi = new JMenuItem(Text.INPUT + Text.COLS + prefix);
      mi.setEnabled(false);
      pm.add(mi);

      final int[] cursor = rend.cursor();
      pm.show(this, cursor[0], cursor[1]);

      // highlight first entry
      final MenuElement[] me = {pm, (JMenuItem) pm.getComponent(0)};
      MenuSelectionManager.defaultManager().setSelectedPath(me);
    }
  }
 /**
  * Copies all of the mappings from the specified map to this one.
  *
  * <p>These mappings replace any mappings that this map had for any of the keys currently in the
  * specified Map.
  *
  * @param t Mappings to be stored in this map.
  */
 public void putAll(Map<? extends K, ? extends V> t) {
   for (Iterator<? extends Map.Entry<? extends K, ? extends V>> it =
           (Iterator<? extends Map.Entry<? extends K, ? extends V>>) t.entrySet().iterator();
       it.hasNext(); ) {
     Entry<? extends K, ? extends V> e = it.next();
     put(e.getKey(), e.getValue());
   }
 }
 /** Format: mapType, num, (key, value) pairs */
 private void writeObject(ObjectOutputStream out) throws IOException {
   out.writeObject(mapType);
   out.writeInt(num);
   for (Entry e : this) {
     out.writeObject(e.getKey());
     out.writeDouble(e.getValue());
   }
 }
 /**
  * Generates a string representation of the configuration options.
  *
  * @return A string
  * @see java.lang.Object#toString()
  */
 public String toString() {
   StringBuilder buff = new StringBuilder("AjaxMetricsFilterConfiguration:");
   buff.append("\n\tParameter Names:");
   for (Entry<String, String> entry : parameterNames.entrySet()) {
     buff.append("\n\t\t").append(entry.getKey()).append(":").append(entry.getValue());
   }
   buff.append("\n\tRun Options:");
   for (Entry<String, Boolean> entry : runOptions.entrySet()) {
     buff.append("\n\t\t").append(entry.getKey()).append(":").append(entry.getValue());
   }
   buff.append("\n\tBatch Options:");
   for (Entry<String, Integer> entry : batchOptions.entrySet()) {
     buff.append("\n\t\t").append(entry.getKey()).append(":").append(entry.getValue());
   }
   buff.append("\n\tListener Class Name:").append(listenerClassName);
   buff.append("\n\tAgent Logging Level:").append(agentLogLevel);
   buff.append("\n\tAgent Name:").append(agentName);
   return buff.toString();
 }
Beispiel #18
0
 public Set entrySet() {
   Set<Entry<Data, Data>> entries = entrySetInternal();
   Set<Entry<K, V>> resultSet = new HashSet<Entry<K, V>>();
   for (Entry<Data, Data> entry : entries) {
     resultSet.add(
         new AbstractMap.SimpleImmutableEntry(
             (K) getService().toObject(entry.getKey()),
             (V) getService().toObject(entry.getValue())));
   }
   return resultSet;
 }
    @Override
    public boolean contains(Object o) {
      if (o == null) return false;

      if (!(o instanceof Entry)) return false;

      Entry e = (Entry) o;

      // Values are primitive and cannot be null.
      if (e.getKey() == null || e.getKey() == null) return false;

      if (!(e.getKey() instanceof String) || !(e.getValue() instanceof Boolean)) return false;

      String key = (String) e.getKey();
      Boolean value = (Boolean) e.getValue();

      int hash = d_keys.number(key);

      // Does not contain the key.
      if (hash == -1) return false;

      return d_values[hash - 1] == value.booleanValue();
    }
Beispiel #20
0
 @SuppressWarnings("unchecked")
 public void putAll(Map<? extends K, ? extends V> map) {
   for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
     V value = entry.getValue();
     // If the map is another DefaultCache instance than the
     // entry values will be CacheObject instances that need
     // to be converted to the normal object form.
     if (value instanceof CacheObject) {
       //noinspection unchecked
       value = ((CacheObject<V>) value).object;
     }
     put(entry.getKey(), value);
   }
 }
Beispiel #21
0
 public XContentBuilder toXContentBuilder() throws IOException {
   if (this == null) {
     return null;
   }
   XContentBuilder builder = JsonXContent.contentBuilder();
   builder.startObject();
   Iterator<Entry<String, Object>> it = this.entrySet().iterator();
   while (it.hasNext()) {
     Entry<String, Object> entry = it.next();
     builder.field(entry.getKey()).value(entry.getValue());
   }
   builder.endObject();
   return builder;
 }
Beispiel #22
0
 private String generateOverviewText() throws InsufficientDataException {
   StringBuilder sb = new StringBuilder();
   final String team = config.getTeam();
   double total = checkTotal();
   final String nl = System.getProperty("line.separator");
   for (Entry<String, Row> entry : rows.entrySet()) {
     double hours = Double.parseDouble(entry.getValue().hoursTF.getText());
     double fraction = hours / total;
     if (fraction < 0.004) continue;
     String line = team + ", " + decimalFormat.format(fraction) + ", " + entry.getKey();
     sb.append(line + nl);
   }
   return sb.toString();
 }
Beispiel #23
0
  /**
   * Convert Titan internal Mutation representation into HBase native commands.
   *
   * @param mutations Mutations to convert into HBase commands.
   * @param putTimestamp The timestamp to use for Put commands.
   * @param delTimestamp The timestamp to use for Delete commands.
   * @return Commands sorted by key converted from Titan internal representation.
   */
  private static Map<ByteBuffer, Pair<Put, Delete>> convertToCommands(
      Map<String, Map<ByteBuffer, KCVMutation>> mutations,
      final long putTimestamp,
      final long delTimestamp) {
    Map<ByteBuffer, Pair<Put, Delete>> commandsPerKey =
        new HashMap<ByteBuffer, Pair<Put, Delete>>();

    for (Map.Entry<String, Map<ByteBuffer, KCVMutation>> entry : mutations.entrySet()) {
      byte[] cfName = entry.getKey().getBytes();

      for (Map.Entry<ByteBuffer, KCVMutation> m : entry.getValue().entrySet()) {
        ByteBuffer key = m.getKey();
        KCVMutation mutation = m.getValue();

        Pair<Put, Delete> commands = commandsPerKey.get(key);

        if (commands == null) {
          commands = new Pair<Put, Delete>();
          commandsPerKey.put(key, commands);
        }

        if (mutation.hasDeletions()) {
          if (commands.getSecond() == null)
            commands.setSecond(new Delete(ByteBufferUtil.getArray(key), delTimestamp, null));

          for (ByteBuffer b : mutation.getDeletions()) {
            commands.getSecond().deleteColumns(cfName, ByteBufferUtil.getArray(b), delTimestamp);
          }
        }

        if (mutation.hasAdditions()) {
          if (commands.getFirst() == null)
            commands.setFirst(new Put(ByteBufferUtil.getArray(key), putTimestamp));

          for (Entry e : mutation.getAdditions()) {
            commands
                .getFirst()
                .add(
                    cfName,
                    ByteBufferUtil.getArray(e.getColumn()),
                    putTimestamp,
                    ByteBufferUtil.getArray(e.getValue()));
          }
        }
      }
    }

    return commandsPerKey;
  }
  @Override
  public long[] indexRetrieval(Object key, TitanKey pt, InternalTitanTransaction tx) {
    Preconditions.checkArgument(
        pt.isSimple(), "Currently, only simple properties are supported for index retrieval");
    Preconditions.checkArgument(
        pt.hasIndex(), "Cannot retrieve for given property key - it does not have an index");

    long[] vertices = null;

    Preconditions.checkArgument(
        pt.getDataType().isInstance(key),
        "Specified object is incompatible with property data type [" + pt.getName() + "]");

    for (int readAttempt = 0; readAttempt < maxReadRetryAttempts; readAttempt++) {
      try {
        if (pt.isUnique()) {
          ByteBuffer value =
              propertyIndex.get(getIndexKey(key), getKeyedIndexColumn(pt), tx.getTxHandle());
          if (value != null) {
            vertices = new long[1];
            vertices[0] = VariableLong.readPositive(value);
          }
        } else {
          ByteBuffer startColumn = VariableLong.positiveByteBuffer(pt.getID());
          List<Entry> entries =
              propertyIndex.getSlice(
                  getIndexKey(key),
                  startColumn,
                  ByteBufferUtil.nextBiggerBuffer(startColumn),
                  tx.getTxHandle());
          vertices = new long[entries.size()];
          int i = 0;
          for (Entry ent : entries) {
            vertices[i++] = VariableLong.readPositive(ent.getValue());
          }
        }

        break;
      } catch (StorageException e) {
        if (e instanceof TemporaryStorageException) {
          if (readAttempt < maxReadRetryAttempts - 1) temporaryStorageException(e);
          else throw readException(e, maxReadRetryAttempts);
        } else throw readException(e);
      }
    }

    if (vertices == null) return new long[0];
    else return vertices;
  }
Beispiel #25
0
    public String toString()
    {
        StringBuilder stringbuilder = new StringBuilder();
        stringbuilder.append("PATH: ");
        stringbuilder.append(uF);
        if (uD != null)
        {
            stringbuilder.append("  PARAMS: ");
            for (Iterator iterator = uD.entrySet().iterator(); iterator.hasNext(); stringbuilder.append(",  "))
            {
                java.util.Entry entry = (java.util.Entry)iterator.next();
                stringbuilder.append((String)entry.getKey());
                stringbuilder.append("=");
                stringbuilder.append((String)entry.getValue());
            }

        }
        return stringbuilder.toString();
    }
  /**
   * Returns a string representation of this map. The string representation consists of a list of
   * key-value mappings in the order returned by the map's <tt>entrySet</tt> view's iterator,
   * enclosed in braces (<tt>"{}"</tt>). Adjacent mappings are separated by the characters <tt>",
   * "</tt> (comma and space). Each key-value mapping is rendered as the key followed by an equals
   * sign (<tt>"="</tt>) followed by the associated value. Keys and values are converted to strings
   * as by <tt>String.valueOf(Object)</tt>.
   *
   * <p>This implementation creates an empty string buffer, appends a left brace, and iterates over
   * the map's <tt>entrySet</tt> view, appending the string representation of each
   * <tt>map.entry</tt> in turn. After appending each entry except the last, the string <tt>",
   * "</tt> is appended. Finally a right brace is appended. A string is obtained from the
   * stringbuffer, and returned.
   *
   * @return a String representation of this map.
   */
  public String toString() {
    StringBuffer buf = new StringBuffer();
    buf.append("{");

    Iterator i = entrySet().iterator();
    boolean hasNext = i.hasNext();
    while (hasNext) {
      Entry e = (Entry) (i.next());
      Object key = e.getKey();
      Object value = e.getValue();
      buf.append((key == this ? "(this Map)" : key) + "=" + (value == this ? "(this Map)" : value));

      hasNext = i.hasNext();
      if (hasNext) buf.append(", ");
    }

    buf.append("}");
    return buf.toString();
  }
    @Override
    public boolean remove(Object o) {
      processQueue();
      if (!(o instanceof Entry)) return false;
      Entry<K, V> e = (Entry<K, V>) o;
      V ev = e.getValue();

      // optimization: do not recreate the key
      myHardKeyInstance.set(e.getKey());
      Key<K> key = myHardKeyInstance;

      V hv = myMap.get(key);
      boolean toRemove = hv == null ? ev == null && myMap.containsKey(key) : hv.equals(ev);
      if (toRemove) {
        myMap.remove(key);
      }
      myHardKeyInstance.clear();
      return toRemove;
    }
  /**
   * Removes the mapping for this key from this map if present (optional operation).
   *
   * <p>This implementation iterates over <tt>entrySet()</tt> searching for an entry with the
   * specified key. If such an entry is found, its value is obtained with its <tt>getValue</tt>
   * operation, the entry is is removed from the Collection (and the backing map) with the
   * iterator's <tt>remove</tt> operation, and the saved value is returned. If the iteration
   * terminates without finding such an entry, <tt>null</tt> is returned. Note that this
   * implementation requires linear time in the size of the map; many implementations will override
   * this method.
   *
   * <p>Note that this implementation throws an <tt>UnsupportedOperationException</tt> if the
   * <tt>entrySet</tt> iterator does not support the <tt>remove</tt> method and this map contains a
   * mapping for the specified key.
   *
   * @param key key whose mapping is to be removed from the map.
   * @return previous value associated with specified key, or <tt>null</tt> if there was no entry
   *     for key. (A <tt>null</tt> return can also indicate that the map previously associated
   *     <tt>null</tt> with the specified key, if the implementation supports <tt>null</tt> values.)
   * @throws UnsupportedOperationException if the <tt>remove</tt> operation is not supported by this
   *     map.
   */
  public Object remove(Object key) {
    Iterator i = entrySet().iterator();
    Entry correctEntry = null;
    if (key == null) {
      while (correctEntry == null && i.hasNext()) {
        Entry e = (Entry) i.next();
        if (e.getKey() == null) correctEntry = e;
      }
    } else {
      while (correctEntry == null && i.hasNext()) {
        Entry e = (Entry) i.next();
        if (key.equals(e.getKey())) correctEntry = e;
      }
    }

    Object oldValue = null;
    if (correctEntry != null) {
      oldValue = correctEntry.getValue();
      i.remove();
    }
    return oldValue;
  }
Beispiel #29
0
  private Date lazyEvaluateDateParam(Object key) {
    // parse date structs automatically
    Map dateParams = new HashMap();
    for (Object o : entrySet()) {
      Entry entry = (Entry) o;
      final Object entryKey = entry.getKey();
      if (entryKey instanceof String) {
        String paramName = (String) entryKey;
        final String prefix = key + "_";
        if (paramName.startsWith(prefix)) {
          dateParams.put(
              paramName.substring(prefix.length(), paramName.length()), entry.getValue());
        }
      }
    }

    DateFormat dateFormat =
        new SimpleDateFormat(GrailsDataBinder.DEFAULT_DATE_FORMAT, LocaleContextHolder.getLocale());
    StructuredPropertyEditor editor = new StructuredDateEditor(dateFormat, true);
    Date d = (Date) editor.assemble(Date.class, dateParams);
    put(key, d);
    return d;
  }
Beispiel #30
0
 // 将Json集合转换为大Json
 public static XContentBuilder parse(List<Json> list, String arrayName) throws IOException {
   XContentBuilder builder = XContentFactory.jsonBuilder();
   builder.startObject();
   if (list == null || list.size() == 0) {
     builder.field("total", 0);
     builder.startArray(arrayName);
   } else {
     builder.field("total", list.size());
     builder.startArray(arrayName);
     for (Json json : list) {
       builder.startObject();
       Iterator<Entry<String, Object>> it = json.entrySet().iterator();
       while (it.hasNext()) {
         Entry<String, Object> entry = it.next();
         builder.field(entry.getKey()).value(entry.getValue());
       }
       builder.endObject();
     }
   }
   builder.endArray();
   builder.endObject();
   return builder;
 }