Пример #1
1
 @Override
 public boolean validateOptions(Map<String, String> options) {
   if (super.validateOptions(options) == false) return false;
   boolean hasStart = false;
   boolean hasEnd = false;
   try {
     if (options.containsKey(START)) {
       hasStart = true;
       String s = options.get(START);
       if (s.startsWith(LONG_PREFIX)) Long.valueOf(s.substring(LONG_PREFIX.length()));
       else dateParser.parse(s);
     }
     if (options.containsKey(END)) {
       hasEnd = true;
       String s = options.get(END);
       if (s.startsWith(LONG_PREFIX)) Long.valueOf(s.substring(LONG_PREFIX.length()));
       else dateParser.parse(s);
     }
     if (!hasStart && !hasEnd)
       throw new IllegalArgumentException(START + " or " + END + " must be specified");
     if (options.get(START_INCL) != null) Boolean.parseBoolean(options.get(START_INCL));
     if (options.get(END_INCL) != null) Boolean.parseBoolean(options.get(END_INCL));
   } catch (Exception e) {
     throw new IllegalArgumentException("invalid options", e);
   }
   return true;
 }
Пример #2
0
 public void initComponents() {
   competitors =
       DB.getCompetitors(turniej.getId())
           .stream()
           .filter(c -> c.getGoesFinal())
           .collect(Collectors.toList());
   competitorMap = competitors.stream().collect(Collectors.toMap(c -> c.getId(), c -> c));
   singleGames =
       DB.getSingleGames(turniej.getId(), true)
           .stream()
           .filter(
               sg ->
                   competitorMap.containsKey(sg.getCompetitorW())
                       && competitorMap.containsKey(sg.getCompetitorB()))
           .collect(Collectors.toList());
   // filtrowanie powyżej, bo baza zwraca również gry,
   // gdzie grali (dostał się do finałów) vs (nie dostał się)
   // można to naprawić w bazie
   for (Competitor c : competitors) {
     competitorGames.put(c, new LinkedList<>());
   }
   for (SingleGame sg : singleGames) {
     competitorGames.get(competitorMap.get(sg.getCompetitorW())).add(sg);
     competitorGames.get(competitorMap.get(sg.getCompetitorB())).add(sg);
   }
   removeAll();
   table = new JTable(new MyTableModel());
   add(new JScrollPane(table));
   updateTables();
 }
  private void doMatches(Map<String, Object> ret, BagQueryResult bqr) {

    for (Entry<Integer, List> pair : bqr.getMatches().entrySet()) {
      Map<String, Object> resultItem;
      InterMineObject imo;
      try {
        imo = im.getObjectStore().getObjectById(pair.getKey());
      } catch (ObjectStoreException e) {
        throw new IllegalStateException("Could not retrieve object reported as match", e);
      }
      String idKey = String.valueOf(imo.getId());
      if (ret.containsKey(idKey)) {
        resultItem = (Map<String, Object>) ret.get(idKey);
      } else {
        resultItem = new HashMap<String, Object>();
        resultItem.put("identifiers", new HashMap<String, Object>());
      }
      if (!resultItem.containsKey("summary")) {
        resultItem.put("summary", getObjectDetails(imo));
      }
      Map<String, Object> identifiers = (Map<String, Object>) resultItem.get("identifiers");
      for (Object o : pair.getValue()) {
        String ident = (String) o;
        if (!identifiers.containsKey(ident)) {
          identifiers.put(ident, new HashSet<String>());
        }
        Set<String> categories = (Set<String>) identifiers.get(ident);
        categories.add("MATCH");
      }
      String className = DynamicUtil.getSimpleClassName(imo.getClass());
      resultItem.put("type", className.replaceAll("^.*\\.", ""));
      ret.put(idKey, resultItem);
    }
  }
Пример #4
0
 public void updateEvictionStrategies() {
   Iterator<String> iterator = evictionStrategyMap.keySet().iterator();
   while (iterator.hasNext()) {
     String levelname = iterator.next();
     Optional<RetentionLevel> level = environment.retentions().getLevelForName(levelname);
     if (!level.isPresent() || !levelIsAccessLevel(level.get())) {
       iterator.remove();
     }
   }
   Collection<RetentionLevel> accessLevels = environment.retentions().getAllAccessLevels();
   for (RetentionLevel accessLevel : accessLevels) {
     if (caches.containsKey(accessLevel.name())
         && !evictionStrategyMap.containsKey(accessLevel.name())) {
       Optional<CachingLevel> cachingLevel =
           environment.cachingConfiguration().findLevelForLevelName(accessLevel.name());
       if (cachingLevel.isPresent()) {
         evictionStrategyMap.put(
             accessLevel.name(),
             new NaiveLRUStrategy(
                 accessLevel.name(),
                 metricStorage,
                 findAllFollowingLevelCaches(accessLevel),
                 cachingLevel.get().visibleCacheSize()));
       }
     }
   }
 }
Пример #5
0
  /**
   * Initializes the services that are available.
   *
   * @param enableDebugger whether or not to enable the ecmascript-debugger service
   */
  private void initializeServices(boolean enableDebugger) {
    exec.init();
    windowManager.init();

    if (versions.containsKey("core") && coreUtils != null) {
      coreUtils.init();
    }

    if (versions.containsKey("prefs") && prefs != null) {
      prefs.init();
    }

    if (versions.containsKey("desktop-window-manager") && desktopWindowManager != null) {
      desktopWindowManager.init();
    }

    if (versions.containsKey("system-input") && systemInputManager != null) {
      systemInputManager.init();
    }

    if (versions.containsKey("desktop-utils") && desktopUtils != null) {
      desktopUtils.init();
    }

    if (enableDebugger) {
      debugger.init();
    }
  }
Пример #6
0
  /** Tests Map.put(Object, Object) */
  public void testMapPut() {
    if (!isAddRemoveModifiable()) return;

    resetEmpty();

    Object[] keys = getSampleKeys();
    Object[] values = getSampleValues();
    Object[] newValues = getNewSampleValues();

    for (int i = 0; i < keys.length; i++) {
      Object o = map.put(keys[i], values[i]);
      confirmed.put(keys[i], values[i]);
      verify();
      assertTrue("First map.put should return null", o == null);
      assertTrue("Map should contain key after put", map.containsKey(keys[i]));
      assertTrue("Map should contain value after put", map.containsValue(values[i]));
    }

    for (int i = 0; i < keys.length; i++) {
      Object o = map.put(keys[i], newValues[i]);
      confirmed.put(keys[i], newValues[i]);
      verify();
      assertEquals("Second map.put should return previous value", values[i], o);
      assertTrue("Map should still contain key after put", map.containsKey(keys[i]));
      assertTrue("Map should contain new value after put", map.containsValue(newValues[i]));

      // if duplicates are allowed, we're not guarunteed that the value
      // no longer exists, so don't try checking that.
      if (!useDuplicateValues()) {
        assertTrue(
            "Map should not contain old value after second put", !map.containsValue(values[i]));
      }
    }
  }
  private Map<String, Double> updateV(
      Map<String, Double> vMap, Map<String, Double> fxiyi, Map<String, Double> fxizi) {

    Set<Map.Entry<String, Double>> entrySet = fxiyi.entrySet();
    for (Map.Entry<String, Double> entry : entrySet) {
      String key = entry.getKey();
      Double value = entry.getValue();
      if (vMap.containsKey(key)) {
        vMap.put(key, vMap.get(key) + value);
      } else {
        vMap.put(key, value);
      }
    }
    entrySet = fxizi.entrySet();
    for (Map.Entry<String, Double> entry : entrySet) {
      String key = entry.getKey();
      Double value = entry.getValue();
      if (vMap.containsKey(key)) {
        vMap.put(key, vMap.get(key) - value);
      } else {
        vMap.put(key, -1 * value);
      }
    }
    return vMap;
  }
  /**
   * Method responsible for deciding if a connection is OK to continue
   *
   * @param session The new session that will be verified
   * @return True if the session meets the criteria, otherwise false
   */
  public boolean isConnectionOk(IoSession session) {
    InetAddress addr = getAddress(session);
    long now = System.currentTimeMillis();
    if (clients.containsKey(addr)) {
      long lastConnTime = clients.get(addr);

      if (now - lastConnTime < allowedInterval) {
        int c = 0;
        if (!counts.containsKey(addr)) counts.put(addr, 0);
        else c = counts.get(addr) + 1;
        if (c >= 350) {

          c = 0;
        }
        counts.put(addr, c);
        // Logger.err("["+host+"] Session dropped (delay="+(now-lastConnTime)+"ms)");
        return false;
      } else {
        clients.put(addr, now);
        return true;
      }
    } else {
      clients.put(addr, now);
      return true;
    }
  }
Пример #9
0
  @Override
  public void validateParams(
      OperationContext operationContext,
      ErrorCollection errorCollectionToAddTo,
      I18nHelper i18n,
      Issue issue,
      FieldScreenRenderLayoutItem fieldScreenRenderLayoutItem) {
    Map fieldValuesHolder = operationContext.getFieldValuesHolder();
    Map<String, Object> commentParams = (Map<String, Object>) fieldValuesHolder.get(getId());
    String body = (String) commentParams.get(getId());

    String groupLevel = (String) commentParams.get(PARAM_GROUP_LEVEL);
    String roleLevel = (String) commentParams.get(PARAM_ROLE_LEVEL);
    Visibility visibility = Visibilities.fromGroupAndStrRoleId(groupLevel, roleLevel);

    ApplicationUser user = authenticationContext.getUser();

    if (commentParams.containsKey(EDIT_COMMENT)) {
      validateEditComment(errorCollectionToAddTo, issue, commentParams, body, visibility, user);
    } else if (commentParams.containsKey(REMOVE_COMMENT)) {
      validateRemoveComment(errorCollectionToAddTo, commentParams, user);
    } else {
      validateCreateComment(errorCollectionToAddTo, issue, commentParams, body, visibility, user);
    }
  }
 private static void guessAtMethodAndClass(
     Map<ArgumentType, CommandLineArgument> commandLineArguments, String potentialClassOrMethod) {
   boolean hasMethod = commandLineArguments.containsKey(ArgumentType.METHOD_ARG);
   boolean hasClass = commandLineArguments.containsKey(ArgumentType.CLASS_ARG);
   try {
     if (potentialClassOrMethod != null) {
       if (!hasClass) {
         commandLineArguments.put(
             ArgumentType.CLASS_ARG,
             new CommandLineArgument(
                 ArgumentType.CLASS_ARG,
                 KoanClassLoader.getInstance().loadClass(potentialClassOrMethod).getName()));
       } else if (!hasMethod) {
         commandLineArguments.put(
             ArgumentType.METHOD_ARG,
             new CommandLineArgument(ArgumentType.METHOD_ARG, potentialClassOrMethod));
       }
     }
   } catch (Exception cnfe2) {
     if (!hasMethod) {
       commandLineArguments.put(
           ArgumentType.METHOD_ARG,
           new CommandLineArgument(ArgumentType.METHOD_ARG, potentialClassOrMethod));
     } else {
       throw new IllegalArgumentException(
           potentialClassOrMethod + " does not match an expected argument, nor value.");
     }
   }
 }
Пример #11
0
    @Override
    public boolean contains(Object needle) {
      if (!(needle instanceof String)) return false;

      String n = (String) needle;
      return names.containsKey(n) || names.containsKey(StringUtils.toLowerCase(n));
    }
Пример #12
0
  @SuppressWarnings("unchecked")
  public <T> List<T> findWithNamedQuery(String queryName, Map<String, Object> params) {
    Set<Entry<String, Object>> rawParameters = params.entrySet();
    Query query = entityManager.createNamedQuery(queryName);

    // if has limit.
    if (params.containsKey(QueryParameters.LIMIT_START)) {
      int start = new Integer(params.get(QueryParameters.LIMIT_START).toString());
      int n = (Integer) params.get(QueryParameters.LIMIT_N);
      params.remove(QueryParameters.LIMIT_START);
      params.remove(QueryParameters.LIMIT_N);
      query.setFirstResult(start);
      query.setMaxResults(n);
    }

    // if has order by.
    if (params.containsKey(QueryParameters.ORDERBY)) {
      String orderbyField = (String) params.get(QueryParameters.ORDERBY);
      params.remove(QueryParameters.ORDERBY);
      query.setParameter("orderby", String.format("%s", orderbyField));
      if (params.containsKey(QueryParameters.ORDERBY_SORT)) {
        params.remove(QueryParameters.ORDERBY_SORT);
      }
    }

    // Add parameters
    for (Entry<String, Object> entry : rawParameters) {
      query.setParameter(entry.getKey(), entry.getValue());
    }

    return query.getResultList();
  }
  /**
   * Determines if a try to connect to a server should be done based on the last time a try was done
   * and failed.
   *
   * @param server the server being checked
   * @return <code>true</code> if it is OK to try and connect
   */
  private boolean isOkToConnect(final ModeShapeServer server) {
    boolean check = false; // check map for time

    try {
      _offlineServersLock.readLock().lock();
      check = _offlineServerMap.containsKey(server);
    } finally {
      _offlineServersLock.readLock().unlock();
    }

    if (check) {
      try {
        _offlineServersLock.writeLock().lock();

        if (_offlineServerMap.containsKey(server)) {
          final long checkTime = _offlineServerMap.get(server);

          // OK to try and connect if last failed attempt was too long ago
          if ((System.currentTimeMillis() - checkTime) > RETRY_DURATION) {
            _offlineServerMap.remove(server);
            refresh(server);
            return true;
          }

          // don't try and connect because we just tried and failed
          return false;
        }
      } finally {
        _offlineServersLock.writeLock().unlock();
      }
    }

    // OK to try and connect
    return true;
  }
  /** Calculate the frequency of every one of the keys of the X axis */
  @Override
  protected void processData(ExperimentSummaryData summaryData) {
    Map<Integer, Integer> valuesIdentified = new HashMap<Integer, Integer>();
    Map<Integer, Integer> valuesUnidentified = new HashMap<Integer, Integer>();

    List<Double> chargeIdentified = summaryData.getPrecChargeVecExp(true);
    int maxChargeFound = 0;
    for (double key : chargeIdentified) {
      int auxKey = (int) key;
      int value = valuesIdentified.containsKey(auxKey) ? valuesIdentified.get(auxKey) + 1 : 1;
      valuesIdentified.put(auxKey, value);
      if (auxKey > maxChargeFound) maxChargeFound = auxKey;
    }

    List<Double> chargeUnidentified = summaryData.getPrecChargeVecExp(false);
    for (double key : chargeUnidentified) {
      int auxKey = (int) key;
      int value = valuesUnidentified.containsKey(auxKey) ? valuesUnidentified.get(auxKey) + 1 : 1;
      valuesUnidentified.put(auxKey, value);
      if (auxKey > maxChargeFound) maxChargeFound = auxKey;
    }

    if (maxChargeFound == 0) {
      recordError("No correct charges has been found");
      return;
    }

    List<SeriesPair<Integer, Integer>> identified = new ArrayList<SeriesPair<Integer, Integer>>();
    // List<SeriesPair<Integer,Integer>> unidentified = new
    // ArrayList<SeriesPair<Integer,Integer>>();
    // With the 'for' loop we ensure that the SeriesPair are added in an ordered way
    for (int key = 1; key <= maxChargeFound; key++) {
      // Only the charges found are stored int the intermediate identified
      if (valuesIdentified.containsKey(key))
        identified.add(new SeriesPair<Integer, Integer>(key, valuesIdentified.get(key)));

      // if(valuesUnidentified.containsKey(key))
      //    unidentified.add(new SeriesPair<Integer, Integer>(key,valuesUnidentified.get(key)));
    }

    if (identified.isEmpty()) {
      recordError("The experiment does not contain identified spectra");
      return;
    }

    intermediateData = new IntermediateData();
    // In this case the type and the name of the series are the same
    intermediateData.addPrideChartSerie(
        new DataSeries<Integer, Integer>(
            DataSeriesType.IDENTIFIED_SPECTRA, "Identified Spectra", identified));
    // intermediateData.addPrideChartSerie(new
    // DataSeries<Integer,Integer>(DataSeriesType.UNIDENTIFIED_SPECTRA, "Unidentified Spectra",
    // unidentified));

    try {
      intermediateData.setVariable("experimentSize", summaryData.size());
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
Пример #15
0
 /**
  * Returns true if the specified S3Object contains encryption info in its metadata, false
  * otherwise.
  *
  * @param retrievedObject An S3Object
  * @return True if the specified S3Object contains encryption info in its metadata, false
  *     otherwise.
  * @deprecated no longer used and will be removed in the future
  */
 @Deprecated
 public static boolean isEncryptionInfoInMetadata(S3Object retrievedObject) {
   Map<String, String> metadata = retrievedObject.getObjectMetadata().getUserMetadata();
   return metadata != null
       && metadata.containsKey(Headers.CRYPTO_IV)
       && metadata.containsKey(Headers.CRYPTO_KEY);
 }
Пример #16
0
  @Override
  public void update(Observable o, Object arg) {
    this.dcAgent = (DCAgent) o;

    for (Resource resource : Registry._INSTANCE.getResources()) {
      if (shouldMonitor(resource)) {
        int newSamplingTime = getSamplingTime(resource);
        if (timerPerResourceId.containsKey(resource.getId())
            && samplingTimePerResourceId.get(resource.getId()) != newSamplingTime) {
          timerPerResourceId.remove(resource.getId()).cancel();
        }
        if (!timerPerResourceId.containsKey(resource.getId())) {
          Timer timer = new Timer();
          timerPerResourceId.put(resource.getId(), timer);
          samplingTimePerResourceId.put(resource.getId(), newSamplingTime);
          String url = Registry._INSTANCE.getResourceUrl(resource);
          String user = getApplicationUser(resource);
          String password = getApplicationPassword(resource);
          createTask(timer, resource, newSamplingTime, url, user, password);
        }
      } else {
        Timer timer = timerPerResourceId.remove(resource.getId());
        if (timer != null) timer.cancel();
        samplingTimePerResourceId.remove(resource.getId());
      }
    }
  }
  public void enrich(EObject model, Element e) {
    String defaultNamespace = e.getAttribute("base");
    sigNodeMap = createMapping(theoryXPath, e, "name");
    viewNodeMap = createMapping(viewXPath, e, "name");
    sigObjMap = new HashMap<String, EObject>();
    viewObjMap = new HashMap<String, EObject>();

    TreeIterator<EObject> iter = model.eAllContents();
    while (iter.hasNext()) {
      EObject obj = iter.next();
      if (obj instanceof signatureDeclaration) {
        signatureDeclaration sig = (signatureDeclaration) obj;
        if (sigNodeMap.containsKey(sig.getSigName())) {
          sigObjMap.put(sig.getSigName(), obj);
          Element elem = sigNodeMap.get(sig.getSigName());
          String bs = defaultNamespace;
          if (elem.hasAttribute("base")) bs = elem.getAttribute("base");
          sig.setFullURI(bs + "?" + sig.getSigName());
          syncConstructs(sig.getDefs().getConstucts(), elem);
        }
      }
      if (obj instanceof viewDeclaration) {
        viewDeclaration view = (viewDeclaration) obj;
        if (viewNodeMap.containsKey(view.getViewID())) {
          Element elem = sigNodeMap.get(view.getViewID());
          viewObjMap.put(view.getViewID(), obj);
          String bs = defaultNamespace;
          if (elem.hasAttribute("base")) bs = elem.getAttribute("base");
          view.setFullURI(bs + "?" + view.getViewID());
          syncConstructs(view.getViewDefs().getConstucts(), elem);
        }
      }
    }
  }
Пример #18
0
  @Test
  public void testDetermineFileGroupIdentifierToFileGroupMap() throws Exception {
    //
    String base = getBase();
    List<File> fileList = new ArrayList<File>();
    fileList.add(new File("C:\\temp\\admin_de_DE.properties"));
    fileList.add(new File("C:\\temp\\admin_en_US.properties"));
    fileList.add(new File("C:\\temp\\article_de_DE.properties"));
    fileList.add(new File("C:\\temp\\article_en_US.properties"));
    fileList.add(new File("C:\\temp\\article_de.properties"));
    fileList.add(new File("C:\\temp\\article_en.properties"));

    //
    FileGrouper fileGrouper = new FileGrouper();
    try {
      fileGrouper.addAllFiles(fileList);
      fileGrouper.setGroupingPatternReplacementToken("{locale}");
      fileGrouper.setGroupingPatternString("(.*?_(\\w{2,3}_\\w{2,3}|\\w{2,3})|.*())\\.\\w*");
      fileGrouper.setGroupingPatternGroupingGroupIndexList(Arrays.asList(2, 3));
    } catch (Exception e) {
      e.printStackTrace();
      Assert.fail();
    }

    //
    Map<String, FileGroup> fileGroupIdentifierToFileGroupMap =
        fileGrouper.determineFileGroupIdentifierToFileGroupMap();

    //
    assertEquals(2, fileGroupIdentifierToFileGroupMap.size());
    Set<String> fileGroupIdentifierSet = fileGroupIdentifierToFileGroupMap.keySet();
    assertTrue(fileGroupIdentifierSet.contains(base + "C:\\temp\\admin_{locale}.properties"));
    assertTrue(fileGroupIdentifierSet.contains(base + "C:\\temp\\article_{locale}.properties"));

    //
    {
      //
      FileGroup fileGroup =
          fileGroupIdentifierToFileGroupMap.get(base + "C:\\temp\\admin_{locale}.properties");

      //
      Map<String, File> groupTokenToFileMap = fileGroup.getGroupTokenToFileMap();
      assertEquals(2, groupTokenToFileMap.size());
      assertTrue(groupTokenToFileMap.containsKey("de_DE"));
      assertTrue(groupTokenToFileMap.containsKey("en_US"));
    }
    {
      //
      FileGroup fileGroup =
          fileGroupIdentifierToFileGroupMap.get(base + "C:\\temp\\article_{locale}.properties");

      //
      Map<String, File> groupTokenToFileMap = fileGroup.getGroupTokenToFileMap();
      assertEquals(4, groupTokenToFileMap.size());
      assertTrue(groupTokenToFileMap.containsKey("de_DE"));
      assertTrue(groupTokenToFileMap.containsKey("en_US"));
      assertTrue(groupTokenToFileMap.containsKey("de"));
      assertTrue(groupTokenToFileMap.containsKey("en"));
    }
  }
    @Override
    public Object getValue(String paramName) throws IllegalArgumentException {
      if (values.containsKey(paramName)) {
        return values.get(paramName);
      }

      if (!parameterExpressions.containsKey(paramName)) {
        Expression[] expressions =
            new Expression[] {
              PARSER.parseExpression(paramName),
              PARSER.parseExpression("#root.![" + paramName + "]")
            };
        ExpressionEvaluatingSqlParameterSourceFactory.this.parameterExpressions.put(
            paramName, expressions);
        this.parameterExpressions.put(paramName, expressions);
      }

      Expression expression = null;

      if (input instanceof Collection<?>) {
        expression = parameterExpressions.get(paramName)[1];
      } else {
        expression = parameterExpressions.get(paramName)[0];
      }

      Object value = evaluateExpression(expression, input);
      values.put(paramName, value);
      if (logger.isDebugEnabled()) {
        logger.debug("Resolved expression " + expression + " to " + value);
      }
      return value;
    }
Пример #20
0
  /**
   * Instantiates multiple underlying SAM writes, one per input SAM reader registered with GATK
   * engine (those will be retrieved from <code>toolkit</code>). The <code>in2out</code> map must
   * contain an entry for each input filename and map it onto a unique output file name.
   *
   * @param toolkit
   * @param in2out
   */
  public void setupByReader(
      GenomeAnalysisEngine toolkit,
      Map<String, String> in2out,
      SAMFileHeader.SortOrder order,
      boolean presorted,
      boolean indexOnTheFly,
      boolean generateMD5,
      SAMProgramRecord pRecord) {
    if (in2out == null)
      throw new StingException("input-output bam filename map for n-way-out writing is NULL");
    for (SAMReaderID rid : toolkit.getReadsDataSource().getReaderIDs()) {

      String fName = toolkit.getReadsDataSource().getSAMFile(rid).getName();

      String outName;
      if (!in2out.containsKey(fName))
        throw new UserException.BadInput(
            "Input-output bam filename map does not contain an entry for the input file " + fName);
      outName = in2out.get(fName);

      if (writerMap.containsKey(rid))
        throw new StingException(
            "nWayOut mode: Reader id for input sam file "
                + fName
                + " is already registered; "
                + "map file likely contains multiple entries for this input file");

      addWriter(rid, outName, order, presorted, indexOnTheFly, generateMD5, pRecord);
    }
  }
Пример #21
0
 private static void handleNonRepeatedField(
     Record record,
     Map<String, Field> valueAsMap,
     String fieldPath,
     Map<String, Set<Descriptors.FieldDescriptor>> messageTypeToExtensionMap,
     Map<String, Object> defaultValueMap,
     Descriptors.Descriptor desc,
     Descriptors.FieldDescriptor f,
     DynamicMessage.Builder builder)
     throws DataGeneratorException {
   Object val;
   String keyName = f.getName();
   if (valueAsMap.containsKey(keyName)) {
     val =
         getValue(
             f,
             valueAsMap.get(keyName),
             record,
             fieldPath + FORWARD_SLASH + f.getName(),
             messageTypeToExtensionMap,
             defaultValueMap);
   } else {
     // record does not contain field, look up default value
     String key = desc.getFullName() + "." + f.getName();
     if (!defaultValueMap.containsKey(key) && !f.isOptional()) {
       throw new DataGeneratorException(Errors.PROTOBUF_04, record.getHeader().getSourceId(), key);
     }
     val = defaultValueMap.get(key);
   }
   if (val != null) {
     builder.setField(f, val);
   }
 }
Пример #22
0
 private static URI fileSystemURI(Map<String, String> match) {
   final String userInfo;
   if (match.containsKey(URIPattern.USERNAME)) {
     if (match.containsKey(URIPattern.PASSWORD)) {
       userInfo = match.get(URIPattern.USERNAME) + ":" + match.get(URIPattern.PASSWORD);
     } else {
       userInfo = match.get(URIPattern.USERNAME);
     }
   } else {
     userInfo = null;
   }
   try {
     int port = UNSPECIFIED_PORT;
     if (match.containsKey(URIPattern.PORT)) {
       try {
         port = Integer.parseInt(match.get(URIPattern.PORT));
       } catch (NumberFormatException e) {
         port = UNSPECIFIED_PORT;
       }
     }
     return new URI(
         match.get(URIPattern.SCHEME),
         userInfo,
         match.get(URIPattern.HOST),
         port,
         "/",
         null,
         null);
   } catch (URISyntaxException ex) {
     throw new DatasetOperationException("[BUG] Could not build FS URI", ex);
   }
 }
 public static boolean isAllowed(Connection connection) {
   if (!allowedIPs.isEmpty()) {
     // The server is using a whitelist so check that the IP address of the client
     // is authorized to connect to the server
     boolean forbidAccess = false;
     try {
       if (!allowedIPs.containsKey(connection.getHostAddress())) {
         byte[] address = connection.getAddress();
         String range1 =
             (address[0] & 0xff) + "." + (address[1] & 0xff) + "." + (address[2] & 0xff) + ".*";
         String range2 = (address[0] & 0xff) + "." + (address[1] & 0xff) + ".*.*";
         String range3 = (address[0] & 0xff) + ".*.*.*";
         if (!allowedIPs.containsKey(range1)
             && !allowedIPs.containsKey(range2)
             && !allowedIPs.containsKey(range3)) {
           forbidAccess = true;
         }
       }
     } catch (UnknownHostException e) {
       forbidAccess = true;
     }
     return !forbidAccess;
   }
   return true;
 }
Пример #24
0
  public String getBamIndexPath() {

    if (indexPath != null) return indexPath;

    if (path.toLowerCase().startsWith("http://") || path.toLowerCase().startsWith("https://")) {
      // See if bam file is specified by parameter
      try {
        URL url = new URL(path);
        String queryString = url.getQuery();
        if (queryString != null) {
          Map<String, String> parameters = HttpUtils.parseQueryString(queryString);
          if (parameters.containsKey("index")) {
            return parameters.get("index");
          } else if (parameters.containsKey("file")) {
            String bamFile = parameters.get("file");
            String bamIndexFile = bamFile + ".bai";
            String newQueryString = queryString.replace(bamFile, bamIndexFile);
            return path.replace(queryString, newQueryString);
          } else {
            String ip = path.replace(url.getPath(), url.getPath() + ".bai");
            return ip;
          }
        }
      } catch (MalformedURLException e) {
        log.error(e.getMessage(), e);
      }
    }

    return path + ".bai";
  }
Пример #25
0
  /**
   * Put together a map of VPF files and their corresponding TableRows
   *
   * @param file
   * @param row
   */
  private Map generateFileRowMap(VPFFile file, SimpleFeature row) throws IOException {
    String tileFileName = null;
    Map rows = new HashMap();
    rows.put(file, row);
    Iterator joinIter = featureType.getFeatureClass().getJoinList().iterator();
    while (joinIter.hasNext()) {
      ColumnPair columnPair = (ColumnPair) joinIter.next();
      VPFFile primaryFile = getVPFFile(columnPair.column1);
      VPFFile joinFile = null;
      joinFile = getVPFFile(columnPair.column2);

      if (!rows.containsKey(joinFile) && rows.containsKey(primaryFile)) {
        SimpleFeature joinRow = (SimpleFeature) rows.get(primaryFile);

        try {
          int joinID =
              Integer.parseInt(joinRow.getAttribute(columnPair.column1.getName()).toString());
          rows.put(
              joinFile,
              getVPFFile(columnPair.column2).getRowFromId(columnPair.column2.getName(), joinID));
        } catch (NullPointerException exc) {
          // Non-matching joins - just put in a NULL
          rows.put(joinFile, null);
        } catch (IllegalAttributeException exc) {
          // I really don't expect to see this one
          exc.printStackTrace();
          rows.put(joinFile, null);
        }
      }
    }
    return rows;
  }
  private void continueTraversal(int pValue, SMGSingleLinkedListCandidate pCandidate) {
    SMGEdgePointsTo pt = smg.getPointer(pValue);
    SMGObject object = pt.getObject();
    if (!candidates.containsKey(object)) {
      startTraversal(object);
    }

    if (inboundPointers.get(pValue) > 1) {
      return;
    }

    Map<Integer, SMGSingleLinkedListCandidate> objectCandidates = candidates.get(object);
    Integer offset = pCandidate.getOffset();

    if (!objectCandidates.containsKey(offset)) {
      // try to infer a pointer presence: either NULL, or uninitialized
      if (smg.isCoveredByNullifiedBlocks(object, offset, AnonymousTypes.dummyPointer)) {
        objectCandidates.put(offset, new SMGSingleLinkedListCandidate(object, offset, 1));
      }
    }

    if (objectCandidates.containsKey(offset)) {
      SMGSingleLinkedListCandidate myCandidate = objectCandidates.get(offset);
      if (pCandidate.isCompatibleWith(myCandidate)) {
        objectCandidates.remove(offset);
        pCandidate.addLength(myCandidate.getLength());
      }
    }
  }
Пример #27
0
  @Test(dependsOnMethods = "testGetMetrics")
  @SuppressWarnings("unchecked")
  public void testGetMetricsWithFilter() {
    MetricFilter filter =
        new MetricFilter() {
          @Override
          public boolean matches(String name, Metric metric) {
            return !name.equals(MetricContext.GOBBLIN_METRICS_NOTIFICATIONS_TIMER_NAME);
          }
        };

    Map<String, Counter> counters = this.context.getCounters(filter);
    Assert.assertEquals(counters.size(), 1);
    Assert.assertTrue(counters.containsKey(RECORDS_PROCESSED));

    Map<String, Meter> meters = this.context.getMeters(filter);
    Assert.assertEquals(meters.size(), 1);
    Assert.assertTrue(meters.containsKey(RECORD_PROCESS_RATE));

    Map<String, Histogram> histograms = this.context.getHistograms(filter);
    Assert.assertEquals(histograms.size(), 1);
    Assert.assertTrue(histograms.containsKey(RECORD_SIZE_DISTRIBUTION));

    Map<String, Timer> timers = this.context.getTimers(filter);
    Assert.assertEquals(timers.size(), 1);
    Assert.assertTrue(timers.containsKey(TOTAL_DURATION));

    Map<String, Gauge> gauges = this.context.getGauges(filter);
    Assert.assertEquals(gauges.size(), 1);
    Assert.assertTrue(gauges.containsKey(QUEUE_SIZE));
  }
Пример #28
0
 public RefundInfo(Map<String, String> map, String prefix) {
   if (map.containsKey(prefix + "receiver" + ".amount")) {
     String newPrefix = prefix + "receiver" + '.';
     this.receiver = new Receiver(map, newPrefix);
   }
   if (map.containsKey(prefix + "refundStatus")) {
     this.refundStatus = map.get(prefix + "refundStatus");
   }
   if (map.containsKey(prefix + "refundNetAmount")) {
     this.refundNetAmount = Double.valueOf(map.get(prefix + "refundNetAmount"));
   }
   if (map.containsKey(prefix + "refundFeeAmount")) {
     this.refundFeeAmount = Double.valueOf(map.get(prefix + "refundFeeAmount"));
   }
   if (map.containsKey(prefix + "refundGrossAmount")) {
     this.refundGrossAmount = Double.valueOf(map.get(prefix + "refundGrossAmount"));
   }
   if (map.containsKey(prefix + "totalOfAllRefunds")) {
     this.totalOfAllRefunds = Double.valueOf(map.get(prefix + "totalOfAllRefunds"));
   }
   if (map.containsKey(prefix + "refundHasBecomeFull")) {
     this.refundHasBecomeFull = Boolean.valueOf(map.get(prefix + "refundHasBecomeFull"));
   }
   if (map.containsKey(prefix + "encryptedRefundTransactionId")) {
     this.encryptedRefundTransactionId = map.get(prefix + "encryptedRefundTransactionId");
   }
   if (map.containsKey(prefix + "refundTransactionStatus")) {
     this.refundTransactionStatus = map.get(prefix + "refundTransactionStatus");
   }
   if (map.containsKey(prefix + "errorList" + ".error(0).errorId")) {
     String newPrefix = prefix + "errorList" + '.';
     this.errorList = new ErrorList(map, newPrefix);
   }
 }
Пример #29
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);
  }
Пример #30
0
 private void addFields(Class<?> clazz) {
   Field[] fields = clazz.getDeclaredFields();
   for (Field field : fields) {
     if (canAccessPrivateMethods()) {
       try {
         field.setAccessible(true);
       } catch (Exception e) {
         // Ignored. This is only a final precaution, nothing we can do.
       }
     }
     if (field.isAccessible()) {
       if (!setMethods.containsKey(field.getName())) {
         // issue #379 - removed the check for final because JDK 1.5 allows
         // modification of final fields through reflection (JSR-133). (JGB)
         // pr #16 - final static can only be set by the classloader
         int modifiers = field.getModifiers();
         if (!(Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers))) {
           addSetField(field);
         }
       }
       if (!getMethods.containsKey(field.getName())) {
         addGetField(field);
       }
     }
   }
   if (clazz.getSuperclass() != null) {
     addFields(clazz.getSuperclass());
   }
 }