public synchronized void transferProgress(
      TransferEvent transferEvent, byte[] buffer, int length) {
    Resource resource = transferEvent.getResource();
    if (!downloads.containsKey(resource)) {
      downloads.put(resource, new Long(length));
    } else {
      Long complete = (Long) downloads.get(resource);
      complete = new Long(complete.longValue() + length);
      downloads.put(resource, complete);
    }

    StringBuffer buf = new StringBuffer();
    for (Iterator i = downloads.entrySet().iterator(); i.hasNext(); ) {
      Map.Entry entry = (Map.Entry) i.next();
      Long complete = (Long) entry.getValue();
      String status =
          getDownloadStatusForResource(
              complete.longValue(), ((Resource) entry.getKey()).getContentLength());
      buf.append(status);
      if (i.hasNext()) {
        buf.append(" ");
      }
    }

    if (buf.length() > maxLength) {
      maxLength = buf.length();
    }

    out.print(buf.toString() + "\r");
  }
 /** {@inheritDoc} */
 public void putAll(Map<? extends Integer, ? extends Integer> map) {
   ensureCapacity(map.size());
   // could optimize this for cases when map instanceof THashMap
   for (Map.Entry<? extends Integer, ? extends Integer> entry : map.entrySet()) {
     this.put(entry.getKey().intValue(), entry.getValue().intValue());
   }
 }
 private static void findIndividualPerSequenceCoverage(
     Calibrator calibrator,
     Map<String, Integer> sequenceLengths,
     Map<String, String> readGroupToSampleId,
     final Map<String, HashMap<String, CalibrationStats>> local,
     RegionRestriction restriction) {
   final Covariate rgCovariate =
       calibrator.getCovariate(calibrator.getCovariateIndex(CovariateEnum.READGROUP));
   final Covariate seqCovariate =
       calibrator.getCovariate(calibrator.getCovariateIndex(CovariateEnum.SEQUENCE));
   for (final Map.Entry<String, Integer> entry : sequenceLengths.entrySet()) {
     final String sequenceName = entry.getKey();
     if (restriction != null && !sequenceName.equals(restriction.getSequenceName())) {
       continue;
     }
     for (final Map.Entry<String, String> e2 : readGroupToSampleId.entrySet()) {
       final String readGroup = e2.getKey();
       final String sampleName = e2.getValue();
       final int rgValue = rgCovariate.valueOf(readGroup);
       final int seqValue = seqCovariate.valueOf(sequenceName);
       if (rgValue == -1 || seqValue == -1) {
         add(local, sampleName, sequenceName, new CalibrationStats(null));
       } else {
         final Calibrator.QuerySpec spec = calibrator.initQuery();
         spec.setValue(CovariateEnum.READGROUP, rgValue);
         spec.setValue(CovariateEnum.SEQUENCE, seqValue);
         calibrator.processStats(new LocalStatsProcessor(local, sampleName, sequenceName), spec);
       }
     }
   }
 }
  @Override
  public Object mergeResults(final Map<String, Object> results) throws Exception {

    if (results.isEmpty()) return null;

    Object aggregatedResult = null;

    for (Map.Entry<String, Object> entry : results.entrySet()) {
      final String nodeName = entry.getKey();
      final Object nodeResult = entry.getValue();

      if (nodeResult instanceof Collection) {
        if (aggregatedResult == null) aggregatedResult = new ArrayList();

        ((List) aggregatedResult).addAll((Collection<?>) nodeResult);

      } else if (nodeResult instanceof Exception)

        // RECEIVED EXCEPTION
        throw (Exception) nodeResult;
      else if (nodeResult instanceof OIdentifiable) {
        if (aggregatedResult == null) aggregatedResult = new ArrayList();

        ((List) aggregatedResult).add(nodeResult);

      } else if (nodeResult instanceof Number) {
        if (aggregatedResult == null) aggregatedResult = nodeResult;
        else OMultiValue.add(aggregatedResult, nodeResult);
      }
    }

    return aggregatedResult;
  }
Esempio n. 5
1
  /**
   * 是否财付通签名,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
   *
   * @return boolean
   */
  public boolean isTenpaySign() {
    StringBuffer sb = new StringBuffer();
    Set es = this.parameters.entrySet();
    Iterator it = es.iterator();
    while (it.hasNext()) {
      Map.Entry entry = (Map.Entry) it.next();
      String k = (String) entry.getKey();
      String v = (String) entry.getValue();
      if (!"sign".equals(k) && null != v && !"".equals(v)) {
        sb.append(k + "=" + v + "&");
      }
    }

    sb.append("key=" + this.getKey());

    // 算出摘要
    String enc = "UTF-8";
    String sign = MD5Util.MD5Encode(sb.toString(), enc).toLowerCase();

    String tenpaySign = this.getParameter("sign").toLowerCase();

    // debug信息
    this.setDebugInfo(sb.toString() + " => sign:" + sign + " tenpaySign:" + tenpaySign);

    return tenpaySign.equals(sign);
  }
Esempio n. 6
1
  @SuppressWarnings({"unchecked", "rawtypes"})
  public static void main(String[] args) {
    String dataSource = "oracleSource";
    String sql = "select s.* from sep_log s where s.log_id in (?)";
    Object[] params = new Object[] {"5020350"};

    ConnectionProvider connProvider = DataSourceProvider.prepare(dataSource);
    Object obj = OracleClient.executeQuerySingle(connProvider, sql, params);
    System.out.println(obj);

    sql = "update sep_log s set s.user_id = ? where s.log_id = ?";
    params = new Object[] {"1", "5020350"};
    int uptCnt = OracleClient.executeUpdate(connProvider, sql, params);
    System.out.println(uptCnt);

    sql = "select s.* from sep_log s where s.log_id in (?)";
    params = new Object[] {"5020350"};

    List<Object> list = OracleClient.executeQuery(connProvider, sql, params);
    for (Object object : list) {
      Map<String, Object> map = (Map<String, Object>) object;
      Iterator iter = map.entrySet().iterator();
      System.out.println("=====================================");
      while (iter.hasNext()) {
        Map.Entry entry = (Map.Entry) iter.next();
        Object key = entry.getKey();
        Object val = entry.getValue();
        System.out.println(key + " -- " + val);
      }
    }

    DataSourceProvider.cleanup(connProvider);
  }
Esempio n. 7
1
 private Map<String, Object> query(HttpServletRequest req) {
   final Map<String, Object> map = new HashMap<>();
   for (Map.Entry<String, String[]> entry : req.getParameterMap().entrySet()) {
     map.put(entry.getKey(), entry.getValue());
   }
   return map;
 }
 protected Object execute(Request request, HttpUriRequest httpReq) throws Exception {
   for (Map.Entry<String, String> entry : request.entrySet()) {
     httpReq.setHeader(entry.getKey(), entry.getValue());
   }
   HttpResponse resp = executeRequestWithTimeout(httpReq);
   HttpEntity entity = resp.getEntity();
   int status = resp.getStatusLine().getStatusCode();
   if (entity == null) {
     if (status < 400) {
       return null;
     }
     throw new RemoteException(status, "ServerError", "Server Error", (Throwable) null);
   }
   Header ctypeHeader = entity.getContentType();
   if (ctypeHeader == null) { // handle broken responses with no ctype
     if (status != 200) {
       // this may happen when login failed
       throw new RemoteException(status, "ServerError", "Server Error", (Throwable) null);
     }
     return null; // cannot handle responses with no ctype
   }
   String ctype = ctypeHeader.getValue();
   String disp = null;
   Header[] hdisp = resp.getHeaders("Content-Disposition");
   if (hdisp != null && hdisp.length > 0) {
     disp = hdisp[0].getValue();
   }
   return request.handleResult(status, ctype, disp, entity.getContent());
 }
Esempio n. 9
1
  /**
   * Create job arguments that are used by CrowdClient to build a POST request for a new job on
   * Crowdflower
   */
  void createArgumentMaps() {
    argumentMap = new LinkedMultiValueMap<String, String>();
    includedCountries = new Vector<String>();
    excludedCountries = new Vector<String>();

    Iterator<Map.Entry<String, JsonNode>> jsonRootIt = template.fields();

    for (Map.Entry<String, JsonNode> elt; jsonRootIt.hasNext(); ) {
      elt = jsonRootIt.next();

      JsonNode currentNode = elt.getValue();
      String currentKey = elt.getKey();

      if (currentNode.isContainerNode()) {
        // special processing for these arrays:
        if (currentKey.equals(includedCountriesKey) || currentKey.equals(excludedCountriesKey)) {
          Iterator<JsonNode> jsonSubNodeIt = currentNode.elements();
          for (JsonNode subElt; jsonSubNodeIt.hasNext(); ) {
            subElt = jsonSubNodeIt.next();
            (currentKey.equals(includedCountriesKey) ? includedCountries : excludedCountries)
                .addElement(subElt.path(countryCodeKey).asText());
          }
        }
      } else if (!currentNode.isNull() && argumentFilterSet.contains(currentKey)) {
        argumentMap.add(jobKey + "[" + currentKey + "]", currentNode.asText());
      }
      if (currentKey == idKey) {
        this.id = currentNode.asText();
      }
    }
  }
  @Override
  public boolean action(InternalSession is, Map<String, Long> sessions) {

    String nextExpiringSessionID = null;
    long smallestExpTime = Long.MAX_VALUE;
    for (Map.Entry<String, Long> entry : sessions.entrySet()) {
      String sid = entry.getKey();
      long expirationTime = entry.getValue();
      if (expirationTime < smallestExpTime) {
        smallestExpTime = expirationTime;
        nextExpiringSessionID = sid;
      }
    }
    if (nextExpiringSessionID != null) {
      SessionID sessID = new SessionID(nextExpiringSessionID);
      try {
        Session s = sessionCache.getSession(sessID);
        s.destroySession(s);
      } catch (SessionException e) {
        if (debug.messageEnabled()) {
          debug.message("Failed to destroy the next " + "expiring session.", e);
        }
        // deny the session activation request
        // in this case
        return true;
      }
    }
    return false;
  }
Esempio n. 11
0
 public void printStoreContent() {
   System.out.println("entryOID = " + ((OID) entryOID).getId());
   Map<IOID, ISBAObject> treeMap = new TreeMap<IOID, ISBAObject>(store);
   for (Map.Entry<IOID, ISBAObject> entry : treeMap.entrySet()) {
     System.out.println(entry.getValue().toString());
   }
 }
  private void compareChildren(CompareContext context) {
    Set<String> legacyChildTypes = context.getLegacyDefinition().getChildTypes();
    Set<String> currentChildTypes = context.getCurrentDefinition().getChildTypes();

    compareSetsAndRemoveMissing(context, "child types", currentChildTypes, legacyChildTypes);

    for (String type : legacyChildTypes) {
      Map<String, ModelNode> legacyChildren = context.getLegacyDefinition().getChildren(type);
      Map<String, ModelNode> currentChildren = context.getCurrentDefinition().getChildren(type);

      compareKeySetsAndRemoveMissing(
          context, "child names for type=" + type, currentChildren, legacyChildren);

      for (Map.Entry<String, ModelNode> legacyChildEntry : legacyChildren.entrySet()) {
        String name = legacyChildEntry.getKey();
        ModelNode legacyChildDescription = legacyChildEntry.getValue();
        ModelNode currentChildDescription = currentChildren.get(name);

        CompareContext childContext;
        try {
          childContext =
              new CompareContext(
                  context.getRootAddress(),
                  context.getPathAddress().append(PathElement.pathElement(type, name)),
                  context.isCore(),
                  new ResourceDefinition(currentChildDescription, currentModelVersions),
                  new ResourceDefinition(legacyChildDescription, legacyModelVersions));
        } catch (RuntimeException e) {
          System.out.println(context.getPathAddress() + " + " + type + "=" + name);
          throw e;
        }
        compareModel(childContext);
      }
    }
  }
  @Override
  public Long getUniqueDevicesSupportingBluetooth(
      Company company, Date eventDate, Campaign campaign, Device device) {
    String query =
        "SELECT COUNT(DISTINCT b.macAddress) FROM BluetoothSend b WHERE b.eventDate BETWEEN ?1 AND ?2 AND b.company = ?3 AND b.sendStatus in (1, 2, 3, 4, 5, 7) ";
    int paramCount = 3;
    HashMap<Integer, Object> params = new HashMap<Integer, Object>();
    if (campaign != null) {
      paramCount++;
      query += " AND b.campaign = ?" + paramCount + " ";
      params.put(paramCount, campaign);
    }
    if (device != null) {
      paramCount++;
      query += " AND b.device = ?" + paramCount + " ";
      params.put(paramCount, device);
    }
    Query q = em.createQuery(query);

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

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

    Long countResult = (Long) q.getSingleResult();
    return countResult;
  }
  @Override
  public Long getTotalContentDownloads(
      Company company, Date eventDate, Campaign campaign, Device device) {
    String query =
        "SELECT COUNT(b.id) FROM BluetoothSend b WHERE b.sendStatus = ?1 AND b.eventDate BETWEEN ?2 AND ?3 AND b.company = ?4 ";
    int paramCount = 4;
    HashMap<Integer, Object> params = new HashMap<Integer, Object>();
    if (campaign != null) {
      paramCount++;
      query += " AND b.campaign = ?" + paramCount + " ";
      params.put(paramCount, campaign);
    }
    if (device != null) {
      paramCount++;
      query += " AND b.device = ?" + paramCount + " ";
      params.put(paramCount, device);
    }

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

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

    Long countResult = (Long) q.getSingleResult();
    return countResult;
  }
Esempio n. 15
0
  private void registerCommands() {
    try {
      commandMap = Bukkit.getServer().getClass().getDeclaredField("commandMap");
      commandMap.setAccessible(true);
      knownCommands = SimpleCommandMap.class.getDeclaredField("knownCommands");
      knownCommands.setAccessible(true);
    } catch (Exception e) {
      /* do nothing */
    }

    if (commandMap != null && knownCommands != null) {

      Iterator<Map.Entry<String[], TNECommand>> i = commands.entrySet().iterator();

      while (i.hasNext()) {
        Map.Entry<String[], TNECommand> entry = i.next();

        for (String s : entry.getKey()) {
          if (entry.getValue().activated("", "")) {
            if (registered(s)) {
              unregister(s);
            }
            register(s);
          }
        }
      }
    }
  }
 /*     */ public boolean equals(Object o) {
   /* 146 */ if (!(o instanceof Map.Entry)) return false;
   /* 147 */ Map.Entry e = (Map.Entry) o;
   /*     */
   /* 149 */ return (Long2ReferenceMaps.Singleton.this.key == ((Long) e.getKey()).longValue())
       && (Long2ReferenceMaps.Singleton.this.value == e.getValue());
   /*     */ }
  /**
   * Tests that the UnwovenClassFiles have the correct path when there is no outputDir but there is
   * an OutputLocationManager. Is a simple project that has no inpath setting
   */
  public void testCorrectInfoWhenNoOutputPath() {
    build("inpathTesting");
    AjState state = getState();

    Map classNameToFileMap = state.getClassNameToFileMap();
    assertFalse("expected there to be classes ", classNameToFileMap.isEmpty());
    Set entrySet = classNameToFileMap.entrySet();
    for (Iterator iterator = entrySet.iterator(); iterator.hasNext(); ) {
      Map.Entry entry = (Map.Entry) iterator.next();
      String className = (String) entry.getKey();
      String fullClassName =
          expectedOutputDir
              + File.separator
              + className.replace('.', File.separatorChar)
              + ".class";
      File file = (File) entry.getValue();
      assertEquals(
          "expected file to have path \n"
              + fullClassName
              + ", but"
              + " found path \n"
              + file.getAbsolutePath(),
          fullClassName,
          file.getAbsolutePath());
    }
  }
 private void processHeader() {
   Iterator it = headerParams.entrySet().iterator();
   while (it.hasNext()) {
     Map.Entry pair = (Map.Entry) it.next();
     connection.setRequestProperty(pair.getKey().toString(), pair.getValue().toString());
   }
 }
  public void updateView(Map<String, FrameRange> frameRangeMap) {
    createNewAnimationTable();
    animationsList.clear();

    for (Map.Entry<String, FrameRange> entry : frameRangeMap.entrySet()) {
      String animationName = entry.getKey();
      FrameRange range = entry.getValue();

      VisTable row = new VisTable();

      VisImageButton trashBtn = new VisImageButton("trash-button");

      row.add(StandardWidgetsFactory.createLabel(animationName)).width(120).left();
      row.add(StandardWidgetsFactory.createLabel(range.startFrame + "")).width(50).left();
      row.add(StandardWidgetsFactory.createLabel(range.endFrame + "")).width(50).left();
      row.add(trashBtn).padLeft(10);
      row.row();

      animationsList.add(row).left();
      animationsList.row();

      trashBtn.addListener(
          new ClickListener() {
            @Override
            public void clicked(InputEvent event, float x, float y) {
              facade.sendNotification(DELETE_BUTTON_PRESSED, animationName);
            }
          });
    }

    invalidateHeight();
  }
  @Override
  public List<BluetoothFileSendSummary> fetchBluetoothFileSendSummaries(
      Date eventDate, Company company, Campaign campaign, Device device) {
    String query =
        "SELECT b FROM BluetoothFileSendSummary b WHERE b.eventDate BETWEEN ?1 AND ?2 AND b.company = ?3 ";
    int paramCount = 3;
    HashMap<Integer, Object> params = new HashMap<Integer, Object>();
    if (campaign != null) {
      paramCount++;
      query += " AND b.campaign = ?" + paramCount + " ";
      params.put(paramCount, campaign);
    }
    if (device != null) {
      paramCount++;
      query += " AND b.device = ?" + paramCount + " ";
      params.put(paramCount, device);
    }

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

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

    List<BluetoothFileSendSummary> results = (List<BluetoothFileSendSummary>) q.getResultList();
    return results;
  }
Esempio n. 21
0
  /**
   * Creates a new attribute service using the given providers and user provided default attribute
   * values.
   */
  public AttributeService(
      Iterable<? extends AttributeProvider> providers, Map<String, ?> userProvidedDefaults) {
    ImmutableMap.Builder<String, AttributeProvider> byViewNameBuilder = ImmutableMap.builder();
    ImmutableMap.Builder<Class<?>, AttributeProvider> byViewTypeBuilder = ImmutableMap.builder();
    ImmutableMap.Builder<Class<?>, AttributeProvider> byAttributesTypeBuilder =
        ImmutableMap.builder();

    ImmutableList.Builder<FileAttribute<?>> defaultAttributesBuilder = ImmutableList.builder();

    for (AttributeProvider provider : providers) {
      byViewNameBuilder.put(provider.name(), provider);
      byViewTypeBuilder.put(provider.viewType(), provider);
      if (provider.attributesType() != null) {
        byAttributesTypeBuilder.put(provider.attributesType(), provider);
      }

      for (Map.Entry<String, ?> entry : provider.defaultValues(userProvidedDefaults).entrySet()) {
        defaultAttributesBuilder.add(new SimpleFileAttribute<>(entry.getKey(), entry.getValue()));
      }
    }

    this.providersByName = byViewNameBuilder.build();
    this.providersByViewType = byViewTypeBuilder.build();
    this.providersByAttributesType = byAttributesTypeBuilder.build();
    this.defaultValues = defaultAttributesBuilder.build();
  }
  @Override
  public Long getUniqueDevicesAcceptingPush(
      Company company, Date eventDate, Campaign campaign, Device device) {
    String query =
        "SELECT COUNT(DISTINCT b.macAddress) FROM BluetoothSend b WHERE (b.acceptStatus = ?1 OR b.sendStatus = ?2) AND b.eventDate BETWEEN ?3 AND ?4 AND b.company = ?5 ";
    int paramCount = 5;
    HashMap<Integer, Object> params = new HashMap<Integer, Object>();
    if (campaign != null) {
      paramCount++;
      query += " AND b.campaign = ?" + paramCount + " ";
      params.put(paramCount, campaign);
    }
    if (device != null) {
      paramCount++;
      query += " AND b.device = ?" + paramCount + " ";
      params.put(paramCount, device);
    }
    Query q = em.createQuery(query);

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

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

    Long countResult = (Long) q.getSingleResult();
    return countResult;
  }
Esempio n. 23
0
  static void itTest4(Map s, int size, int pos) {
    IdentityHashMap seen = new IdentityHashMap(size);
    reallyAssert(s.size() == size);
    int sum = 0;
    timer.start("Iter XEntry            ", size);
    Iterator it = s.entrySet().iterator();
    Object k = null;
    Object v = null;
    for (int i = 0; i < size - pos; ++i) {
      Map.Entry x = (Map.Entry) (it.next());
      k = x.getKey();
      v = x.getValue();
      seen.put(k, k);
      if (x != MISSING) ++sum;
    }
    reallyAssert(s.containsKey(k));
    it.remove();
    reallyAssert(!s.containsKey(k));
    while (it.hasNext()) {
      Map.Entry x = (Map.Entry) (it.next());
      Object k2 = x.getKey();
      seen.put(k2, k2);
      if (x != MISSING) ++sum;
    }

    reallyAssert(s.size() == size - 1);
    s.put(k, v);
    reallyAssert(seen.size() == size);
    timer.finish();
    reallyAssert(sum == size);
    reallyAssert(s.size() == size);
  }
  private List<String> getAMRFromAuthModules(
      OAuth2Request request, OAuth2ProviderSettings providerSettings) throws ServerException {
    List<String> amr = null;

    String authModules;
    if (request.getToken(AuthorizationCode.class) != null) {
      authModules = request.getToken(AuthorizationCode.class).getAuthModules();
    } else if (request.getToken(RefreshToken.class) != null) {
      authModules = request.getToken(RefreshToken.class).getAuthModules();
    } else {
      authModules = getAuthModulesFromSSOToken(request);
    }

    if (authModules != null) {
      Map<String, String> amrMappings = providerSettings.getAMRAuthModuleMappings();
      if (!amrMappings.isEmpty()) {
        amr = new ArrayList<String>();
        List<String> modulesUsed = Arrays.asList(authModules.split("\\|"));
        for (Map.Entry<String, String> amrToModuleMapping : amrMappings.entrySet()) {
          if (modulesUsed.contains(amrToModuleMapping.getValue())) {
            amr.add(amrToModuleMapping.getKey());
          }
        }
      }
    }

    return amr;
  }
Esempio n. 25
0
  /**
   * {@inheritDoc}
   *
   * <p>This implementation composes a string by iterating its entry set. If this map contains
   * itself as a key or a value, the string "(this Map)" will appear in its place.
   */
  @Override
  public String toString() {
    if (isEmpty()) {
      return "{}";
    }

    StringBuilder buffer = new StringBuilder(size() * 28);
    buffer.append('{');
    Iterator<Map.Entry<K, V>> it = entrySet().iterator();
    while (it.hasNext()) {
      Map.Entry<K, V> entry = it.next();
      Object key = entry.getKey();
      if (key != this) {
        buffer.append(key);
      } else {
        buffer.append("(this Map)");
      }
      buffer.append('=');
      Object value = entry.getValue();
      if (value != this) {
        buffer.append(value);
      } else {
        buffer.append("(this Map)");
      }
      if (it.hasNext()) {
        buffer.append(", ");
      }
    }
    buffer.append('}');
    return buffer.toString();
  }
Esempio n. 26
0
  private static Node createVlanNode(String nodeLabel, Pane canvas, ContextMenu contextMenu) {
    int infNumber = 0;

    if (Data.hubMap.size() == 0) {
      infNumber = 1;
    } else {
      for (Map.Entry<String, HUB> entry : Data.hubMap.entrySet()) {
        if (entry.getValue().getInfs().size() == 0) {
          infNumber += 1;
        } else {
          infNumber += entry.getValue().getInfs().size();
        }
      }
    }
    int vlanHeight = ((infNumber * 100) + ((infNumber - 1) * 50));
    Rectangle node = new Rectangle(Data.nodeWidth, vlanHeight);
    node.setFill(Color.ORANGE);

    Label lnodeName = new Label(nodeLabel);

    StackPane nodeContainer = new StackPane();
    nodeContainer.getChildren().addAll(node, lnodeName);
    nodeContainer.relocate(Data.vlanstartPosX, Data.vlanstartPosY);

    return nodeContainer;
  }
Esempio n. 27
0
 @Override
 public void mergeLabels(Map<String, String> srcMap, Map<String, String> destMap) {
   if (srcMap == null || destMap == null) {
     return;
   }
   for (Map.Entry<String, String> entry : srcMap.entrySet()) {
     String key = entry.getKey();
     if (key.toLowerCase().startsWith("io.rancher")) {
       key = key.toLowerCase();
     }
     String value = entry.getValue();
     if (key.startsWith("io.rancher.scheduler.affinity")) {
       // merge labels
       String destValue = destMap.get(key);
       if (StringUtils.isEmpty(destValue)) {
         destMap.put(key, value);
       } else if (StringUtils.isEmpty(value)) {
         continue;
       } else if (!destValue.toLowerCase().contains(value.toLowerCase())) {
         destMap.put(key, destValue + "," + value);
       }
     } else {
       // overwrite label value
       destMap.put(key, value);
     }
   }
 }
  private void compareSubsystemModels() {
    System.out.println("====== Comparing subsystem models ======");
    ResourceDefinition rootCurrentDefinition =
        new ResourceDefinition(trimNonSubsystem(currentResourceDefinitions), currentModelVersions);
    ResourceDefinition rootLegacyDefinition =
        new ResourceDefinition(trimNonSubsystem(legacyResourceDefinitions), legacyModelVersions);
    Map<String, ModelNode> currentSubsystems = rootCurrentDefinition.getChildren(SUBSYSTEM);
    Map<String, ModelNode> legacySubsystems = rootLegacyDefinition.getChildren(SUBSYSTEM);

    CompareContext context =
        new CompareContext(
            PathAddress.EMPTY_ADDRESS,
            PathAddress.EMPTY_ADDRESS,
            true,
            rootCurrentDefinition,
            rootLegacyDefinition);
    compareKeySetsAndRemoveMissing(context, "subsystems", currentSubsystems, legacySubsystems);

    for (Map.Entry<String, ModelNode> legacyEntry : legacySubsystems.entrySet()) {
      PathAddress subsystemAddress =
          PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM, legacyEntry.getKey()));
      ResourceDefinition currentDefinition =
          new ResourceDefinition(currentSubsystems.get(legacyEntry.getKey()), currentModelVersions);
      ResourceDefinition legacyDefinition =
          new ResourceDefinition(legacyEntry.getValue(), legacyModelVersions);
      context =
          new CompareContext(
              subsystemAddress, subsystemAddress, false, currentDefinition, legacyDefinition);
      if (!context.continuteWithCheck()) {
        continue;
      }
      compareModel(context);
    }
  }
  private void compareValueType(
      CompareContext context, String id, ModelNode current, ModelNode legacy) {
    ModelNode currentValueType = current.get(VALUE_TYPE);
    ModelNode legacyValueType = legacy.get(VALUE_TYPE);
    if (!currentValueType.isDefined() && !legacyValueType.isDefined()) {
      return;
    }
    if (isType(legacyValueType) || isType(currentValueType)) {
      if (!currentValueType.equals(legacyValueType)) {
        context.println(
            "Different 'value-type' for "
                + id
                + ". Current: "
                + current.get(VALUE_TYPE)
                + "; legacy: "
                + legacy.get(VALUE_TYPE));
      }
    } else {
      Map<String, ModelNode> legacyValueTypes = createMapIndexedByKey(legacyValueType);
      Map<String, ModelNode> currentValueTypes = createMapIndexedByKey(currentValueType);

      compareKeySetsAndRemoveMissing(
          context, "value-type for " + id, currentValueTypes, legacyValueTypes);
      for (Map.Entry<String, ModelNode> entry : currentValueTypes.entrySet()) {
        ModelNode currentEntry = entry.getValue();
        ModelNode legacyEntry = legacyValueTypes.get(entry.getKey());
        compareAttributeOrOperationParameter(
            context,
            "value-type key '" + entry.getKey() + "' for " + id,
            currentEntry,
            legacyEntry);
      }
    }
  }
  @Override
  public List<byte[]> getKeyHandlesByIssuerAndAppId(String issuer, String application) {
    List<byte[]> result = new ArrayList<byte[]>();

    final SharedPreferences keySettings =
        context.getSharedPreferences(U2F_KEY_PAIR_FILE, Context.MODE_PRIVATE);
    Map<String, String> keyTokens = (Map<String, String>) keySettings.getAll();
    for (Map.Entry<String, String> keyToken : keyTokens.entrySet()) {
      String tokenEntryString = keyToken.getValue();

      TokenEntry tokenEntry = new Gson().fromJson(tokenEntryString, TokenEntry.class);

      if (((issuer == null) || issuer.equals(tokenEntry.getIssuer()))
          && ((application == null) || application.equals(tokenEntry.getApplication()))) {
        String keyHandleKey = keyToken.getKey();
        try {
          byte[] keyHandle = keyToKeyHandle(keyHandleKey);
          result.add(keyHandle);
        } catch (DecoderException ex) {
          Log.e(TAG, "Invalid keyHandle: " + keyHandleKey, ex);
        }
      }
    }
    return result;
  }