Ejemplo n.º 1
1
  public static Hashtable findConfidence(Hashtable table) {
    Hashtable confidences = new Hashtable();
    Iterator key_iter = table.keySet().iterator();
    while (key_iter.hasNext()) {
      // System.out.println("here");
      ArrayList<Integer> combo = (ArrayList<Integer>) key_iter.next();
      // System.out.println("current combo"+combo);
      if (combo.size() >= 2) {
        ArrayList<Integer> current_combo =
            new ArrayList<Integer>(combo.subList(0, combo.size() - 1));
        ArrayList<Integer> last_combo =
            new ArrayList<Integer>(combo.subList(combo.size() - 1, combo.size()));
        /*System.out.println(combo);
        System.out.println(current_combo);
        System.out.println(last_combo);
        System.out.println(table.get(current_combo));*/

        if (table.get(current_combo) != null) {
          // System.out.println("it contains!");
          int first = (Integer) table.get(current_combo);
          int second = (Integer) table.get(combo);
          double dub_first = (double) first;
          double dub_second = (double) second;
          double combo_conf = dub_second / dub_first;
          confidences.put(combo, combo_conf);
          // System.out.println("combo:"+combo+" has the confience: "+combo_conf);
        }
      }
    }
    // System.out.println(confidences+"O");

    return confidences;
  }
Ejemplo n.º 2
0
  /**
   * Assigns the given key (that has already been protected) to the given alias.
   *
   * <p>If the protected key is of type <code>java.security.PrivateKey</code>, it must be
   * accompanied by a certificate chain certifying the corresponding public key. If the underlying
   * keystore implementation is of type <code>jks</code>, <code>key</code> must be encoded as an
   * <code>EncryptedPrivateKeyInfo</code> as defined in the PKCS #8 standard.
   *
   * <p>If the given alias already exists, the keystore information associated with it is overridden
   * by the given key (and possibly certificate chain).
   *
   * @param alias the alias name
   * @param key the key (in protected format) to be associated with the alias
   * @param chain the certificate chain for the corresponding public key (only useful if the
   *     protected key is of type <code>java.security.PrivateKey</code>).
   * @exception KeyStoreException if this operation fails.
   */
  public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain)
      throws KeyStoreException {
    permissionCheck();

    synchronized (entries) {
      // key must be encoded as EncryptedPrivateKeyInfo as defined in
      // PKCS#8
      KeyEntry entry = new KeyEntry();
      try {
        EncryptedPrivateKeyInfo privateKey = new EncryptedPrivateKeyInfo(key);
        entry.protectedPrivKey = privateKey.getEncoded();
      } catch (IOException ioe) {
        throw new KeyStoreException("key is not encoded as " + "EncryptedPrivateKeyInfo");
      }

      entry.date = new Date();

      if ((chain != null) && (chain.length != 0)) {
        entry.chain = chain.clone();
        entry.chainRefs = new long[entry.chain.length];
      }

      String lowerAlias = alias.toLowerCase();
      if (entries.get(lowerAlias) != null) {
        deletedEntries.put(lowerAlias, entries.get(alias));
      }
      entries.put(lowerAlias, entry);
      addedEntries.put(lowerAlias, entry);
    }
  }
Ejemplo n.º 3
0
  /**
   * Assigns the given certificate to the given alias.
   *
   * <p>If the given alias already exists in this keystore and identifies a <i>trusted certificate
   * entry</i>, the certificate associated with it is overridden by the given certificate.
   *
   * @param alias the alias name
   * @param cert the certificate
   * @exception KeyStoreException if the given alias already exists and does not identify a
   *     <i>trusted certificate entry</i>, or this operation fails for some other reason.
   */
  public void engineSetCertificateEntry(String alias, Certificate cert) throws KeyStoreException {
    permissionCheck();

    synchronized (entries) {
      Object entry = entries.get(alias.toLowerCase());
      if ((entry != null) && (entry instanceof KeyEntry)) {
        throw new KeyStoreException("Cannot overwrite key entry with certificate");
      }

      // This will be slow, but necessary.  Enumerate the values and then see if the cert matches
      // the one in the trusted cert entry.
      // Security framework doesn't support the same certificate twice in a keychain.
      Collection<Object> allValues = entries.values();

      for (Object value : allValues) {
        if (value instanceof TrustedCertEntry) {
          TrustedCertEntry tce = (TrustedCertEntry) value;
          if (tce.cert.equals(cert)) {
            throw new KeyStoreException(
                "Keychain does not support mulitple copies of same certificate.");
          }
        }
      }

      TrustedCertEntry trustedCertEntry = new TrustedCertEntry();
      trustedCertEntry.cert = cert;
      trustedCertEntry.date = new Date();
      String lowerAlias = alias.toLowerCase();
      if (entries.get(lowerAlias) != null) {
        deletedEntries.put(lowerAlias, entries.get(lowerAlias));
      }
      entries.put(lowerAlias, trustedCertEntry);
      addedEntries.put(lowerAlias, trustedCertEntry);
    }
  }
 void addShortcut(String name) {
   int index1 = name.indexOf('[');
   if (index1 == -1) return;
   int index2 = name.lastIndexOf(']');
   if (index2 <= (index1 + 1)) return;
   String shortcut = name.substring(index1 + 1, index2);
   int len = shortcut.length();
   if (len > 1) shortcut = shortcut.toUpperCase(Locale.US);
   ;
   if (len > 3 || (len > 1 && shortcut.charAt(0) != 'F' && shortcut.charAt(0) != 'N')) return;
   int code = Menus.convertShortcutToCode(shortcut);
   if (code == 0) return;
   if (nShortcuts == 0) removeShortcuts();
   // One character shortcuts go in a separate hash table to
   // avoid conflicts with ImageJ menu shortcuts.
   if (len == 1 || shortcut.equals("N+") || shortcut.equals("N-")) {
     Hashtable macroShortcuts = Menus.getMacroShortcuts();
     macroShortcuts.put(new Integer(code), commandPrefix + name);
     nShortcuts++;
     return;
   }
   Hashtable shortcuts = Menus.getShortcuts();
   if (shortcuts.get(new Integer(code)) != null) {
     if (shortcutsInUse == null) shortcutsInUse = "\n \n";
     shortcutsInUse += "	  " + name + "\n";
     inUseCount++;
     return;
   }
   shortcuts.put(new Integer(code), commandPrefix + name);
   nShortcuts++;
   // IJ.log("addShortcut3: "+name+"	  "+shortcut+"	  "+code);
 }
  /**
   * Initializes the service implementation, and puts it in a sate where it could interoperate with
   * other services. It is strongly recomended that properties in this Map be mapped to property
   * names as specified by <tt>AccountProperties</tt>.
   *
   * @param userID the user id of the ssh account we're currently initializing
   * @param accountID the identifier of the account that this protocol provider represents.
   * @see net.java.sip.communicator.service.protocol.AccountID
   */
  protected void initialize(String userID, AccountID accountID) {
    synchronized (initializationLock) {
      this.accountID = accountID;

      // initialize the presence operationset
      OperationSetPersistentPresenceSSHImpl persistentPresence =
          new OperationSetPersistentPresenceSSHImpl(this);

      supportedOperationSets.put(
          OperationSetPersistentPresence.class.getName(), persistentPresence);

      // register it once again for those that simply need presence and
      // won't be smart enough to check for a persistent presence
      // alternative
      supportedOperationSets.put(OperationSetPresence.class.getName(), persistentPresence);

      // initialize the IM operation set
      basicInstantMessaging = new OperationSetBasicInstantMessagingSSHImpl(this);

      supportedOperationSets.put(
          OperationSetBasicInstantMessaging.class.getName(), basicInstantMessaging);

      // initialze the file transfer operation set
      fileTranfer = new OperationSetFileTransferSSHImpl(this);

      supportedOperationSets.put(OperationSetFileTransfer.class.getName(), fileTranfer);

      isInitialized = true;
    }
  }
Ejemplo n.º 6
0
  // -------------------------------------------
  public static String[] mergeArrays(String[] sa1, String[] sa2) {
    if (sa1 == null) {
      sa1 = new String[0];
    }
    if (sa2 == null) {
      sa2 = new String[0];
    }
    int sa1Len = sa1.length;
    int sa2Len = sa2.length;
    Hashtable tab = new Hashtable(sa1Len + sa2Len);
    for (int i = 0; i < sa1Len; i++) {
      tab.put(sa1[i], sa1[i]);
    }
    for (int i = 0; i < sa2Len; i++) {
      tab.put(sa2[i], sa2[i]);
    }

    int len = tab.size();
    String[] res = new String[len];
    int i = 0;
    for (Enumeration e = tab.keys(); e.hasMoreElements(); ) {
      String s = (String) e.nextElement();
      res[i++] = s;
    }
    return res;
  }
Ejemplo n.º 7
0
  /**
   * Maps a named servlet to a particular path or extension. If the named servlet is unregistered,
   * it will be added and subsequently mapped.
   *
   * <p>Note that the order of resolution to handle a request is:
   *
   * <p>exact mapped servlet (eg /catalog) prefix mapped servlets (eg /foo/bar/*) extension mapped
   * servlets (eg *jsp) default servlet
   */
  public void addServletMapping(String path, String servletName) throws TomcatException {
    if (mappings.get(path) != null) {
      log("Removing duplicate " + path + " -> " + mappings.get(path));
      mappings.remove(path);
      Container ct = (Container) containers.get(path);
      removeContainer(ct);
    }
    ServletWrapper sw = (ServletWrapper) servlets.get(servletName);
    if (sw == null) {
      // Workaround for frequent "bug" in web.xmls
      // Declare a default mapping
      log("Mapping with unregistered servlet " + servletName);
      sw = addServlet(servletName, servletName);
    }
    if ("/".equals(path)) defaultServlet = sw;

    mappings.put(path, sw);

    Container map = new Container();
    map.setContext(this);
    map.setHandler(sw);
    map.setPath(path);
    contextM.addContainer(map);
    containers.put(path, map);
  }
Ejemplo n.º 8
0
  private Hashtable<FieldCmdKind, Object> InitValuesFieldForCmd() {
    Hashtable<FieldCmdKind, Object> fieldsValue =
        new Hashtable<>(); // Набор пар видов полей и значений для них.

    fieldsValue.put(STACK, dataStack); // Стек значений
    fieldsValue.put(CONTEXT, dictionaryDefine); // Словарь замен.

    return fieldsValue;
  }
Ejemplo n.º 9
0
 /** Sets the options. */
 public void setOptions() {
   _optionsDialog.setVisible(false);
   _gameOptions.put("brickCount", _optionsDialog.getBrickCount());
   _gameOptions.put("hitsToRemoveBrick", _optionsDialog.getHitsToRemoveBrick());
   _gameOptions.put("ballsPerLevel", _optionsDialog.getBallsPerLevel());
   _gameOptions.put("nextLevelSpeedJump", _optionsDialog.getLevelSpeedup());
   resetGame();
   repaint();
 }
Ejemplo n.º 10
0
    /** Map publicid to a resource accessible by a classloader. */
    public void registerCatalogEntry(String publicId, String resourceName, ClassLoader loader) {
      if (id2resource == null) id2resource = new Hashtable(17);
      id2resource.put(publicId, resourceName);

      if (loader != null) {
        if (id2loader == null) id2loader = new Hashtable(17);
        id2loader.put(publicId, loader);
      }
    }
Ejemplo n.º 11
0
  public static Hashtable find_combos(Hashtable table, ArrayList<User> users, int r_value) {
    ArrayList<Integer> combinations = new ArrayList<Integer>();
    ArrayList<List<Integer>> combvalues = new ArrayList<List<Integer>>();
    // System.out.println("current hash "+table);
    Iterator iter = table.keySet().iterator();
    while (iter.hasNext()) {
      ArrayList<Integer> hashvalue = (ArrayList<Integer>) iter.next();
      // System.out.println(hashvalue+"::value with support "+table.get(hashvalue));
      if ((Integer) table.get(hashvalue) >= MINSUP) {
        combinations.add((Integer) table.get(hashvalue));
        combvalues.add(hashvalue);
      }
    }
    // System.out.println("combinations that survive: "+combvalues);

    ArrayList<Integer> unique_combo_values = new ArrayList<Integer>();
    for (int i = 0; i < combvalues.size(); i++) {
      for (int k = 0; k < combvalues.get(i).size(); k++) {
        if (!unique_combo_values.contains(combvalues.get(i).get(k))) {
          unique_combo_values.add(combvalues.get(i).get(k));
        }
      }
    }
    ArrayList<List<Integer>> new_combos = new ArrayList<List<Integer>>();
    new_combos = (ArrayList<List<Integer>>) combinations(unique_combo_values, r_value);
    // System.out.println("generated new combinations: "+new_combos);
    Hashtable t = new Hashtable();
    for (int j = 0; j < new_combos.size(); j++) {
      for (int i = 1; i <= num_users; i++) {
        if (users.get(i).hasSameNumbers((new_combos.get(j)))) {
          if (t.containsKey(new_combos.get(j))) {
            int count = (Integer) t.get(new_combos.get(j));
            count++;
            t.put(new_combos.get(j), count);
            // System.out.println("added one to "+new_combos.get(j));
          } else {
            t.put(new_combos.get(j), 1);
            // System.out.println("set to 1"+new_combos.get(j));
          }
        }
      }
    }
    // System.out.println("before weeding "+t);
    Iterator final_iter = t.keySet().iterator();
    while (final_iter.hasNext()) {
      ArrayList<Integer> next = (ArrayList<Integer>) final_iter.next();
      // System.out.println("current support of "+ next+ " is "+t.get(next));
      // System.out.println(MINSUP);
      if ((Integer) t.get(next) < MINSUP || next.isEmpty()) {
        // System.out.println("hi");
        final_iter.remove();
      }
    }

    return t;
  }
Ejemplo n.º 12
0
  public static Hashtable getNodes(Model m) throws ModelException {

    Hashtable t = new Hashtable();
    for (Enumeration en = m.elements(); en.hasMoreElements(); ) {
      Statement s = (Statement) en.nextElement();
      t.put(s.subject(), s.subject());
      t.put(s.object(), s.object());
    }
    return t;
  }
Ejemplo n.º 13
0
  private void count(File f) throws FileNotFoundException, IOException {
    ProgramTokenizer tokenizer = new ProgramTokenizer(new FileReader(f));
    AgillaAssembler.getAssembler().expandMode(tokenizer);

    while (tokenizer.hasMoreInstructions()) {
      Instruction instr = tokenizer.nextInstruction();
      Integer count = (Integer) table.remove(instr);
      if (count == null) table.put(instr.opcode(), new Integer(1));
      else table.put(instr.opcode(), new Integer(count.intValue() + 1));
    }
  }
Ejemplo n.º 14
0
 @SuppressWarnings("unchecked")
 private boolean getOCSPCertificates(String prefix, LinkedHashMap ocsp) {
   ArrayList<String> certificates = (ArrayList<String>) ocsp.get("CERTS");
   if (certificates == null) return false;
   for (int j = 0; j < certificates.size(); j++) {
     if (j == 0) {
       jDigiDocConfiguration.put(prefix + "_CERT", certificates.get(0));
     } else {
       jDigiDocConfiguration.put(prefix + "_CERT_" + j, certificates.get(j));
     }
   }
   return true;
 }
Ejemplo n.º 15
0
  static {
    iconsTable.put(
        ProtocolIcon.ICON_SIZE_16x16, getImageInBytes("service.protocol.yahoo.YAHOO_16x16"));

    iconsTable.put(
        ProtocolIcon.ICON_SIZE_32x32, getImageInBytes("service.protocol.yahoo.YAHOO_32x32"));

    iconsTable.put(
        ProtocolIcon.ICON_SIZE_48x48, getImageInBytes("service.protocol.yahoo.YAHOO_48x48"));

    iconsTable.put(
        ProtocolIcon.ICON_SIZE_64x64, getImageInBytes("service.protocol.yahoo.YAHOO_64x64"));
  }
Ejemplo n.º 16
0
  public static void main(String[] args) throws Exception {
    BufferedReader reader = new BufferedReader(new FileReader("trace"), 1000000);
    String line = reader.readLine();
    Hashtable<String, Integer> table = new Hashtable<String, Integer>();
    int opcodes = 0;
    int keys = 0;
    while (line != null) {
      if (line.startsWith("*STACKTRACESTART*") && line.indexOf("*PROFILE TRACE*") != -1) {
        int index = line.lastIndexOf(':');
        String opcode = line.substring(index + 1);
        for (int i = 0; i < 16; i++) {
          String end = "_" + i;
          if (opcode.endsWith(end)) {
            opcode = opcode.substring(0, opcode.length() - end.length()) + "_n";
          }
        }
        if (!opcode.startsWith("invokenative_")) { // ignore invokenatives
          opcodes++;
          Integer i = (Integer) table.get(opcode);
          if (i == null) {
            table.put(opcode, new Integer(1));
            keys++;
          } else {
            table.put(opcode, new Integer(i.intValue() + 1));
          }
        }
      }
      line = reader.readLine();
    }

    String[] array = new String[keys];
    int pos = 0;
    for (Enumeration e = table.keys(); e.hasMoreElements(); ) {
      String key = (String) e.nextElement();
      Integer i = (Integer) table.get(key);
      float pc = (float) (100 * i.intValue()) / opcodes;
      String out = "";
      if (pc < 10.0) {
        out += "0";
      }
      out += pc;
      while (out.length() < 15) {
        out += " ";
      }
      array[pos++] = out + key;
    }
    Arrays.sort(array);
    for (int i = 0; i < keys; i++) {
      System.out.println(array[i]);
    }
  }
Ejemplo n.º 17
0
  public static void main(String args[]) {
    Hashtable<String, Integer> table = new Hashtable<String, Integer>();

    table.put("Hello", 4);
    table.put("Intro", 24);
    table.put("Auroville", 10);

    // iterate over the keys of the hash table
    Enumeration<String> keys = table.keys();
    while (keys.hasMoreElements()) {
      String k = keys.nextElement();
      System.out.println("found key " + k);
    }
  }
  public static void ComputeOccurenceToWordFromAFile() {
    for (Map.Entry<String, Integer> entry : stringToOccurence.entrySet()) {
      Integer occurence = entry.getValue();

      Integer occurencePair = occurenceToString.get(occurence);

      if (occurencePair == null) {
        occurenceToStrings.put(occurencePair, 1);
      } else {

        occurenceToStrings.put(parts[x], occurence);
      }
    }
  }
Ejemplo n.º 19
0
  private void loadCertificateAuthorityCerts(LinkedHashMap digiDocCA, String caPrefix) {
    logger.debug("");
    ArrayList<String> certificateAuthorityCerts = getCACertsAsArray(digiDocCA);

    jDigiDocConfiguration.put(caPrefix + "_NAME", digiDocCA.get("NAME").toString());
    jDigiDocConfiguration.put(caPrefix + "_TRADENAME", digiDocCA.get("TRADENAME").toString());
    int numberOfCACertificates = certificateAuthorityCerts.size();
    jDigiDocConfiguration.put(caPrefix + "_CERTS", String.valueOf(numberOfCACertificates));

    for (int i = 0; i < numberOfCACertificates; i++) {
      String certFile = certificateAuthorityCerts.get(i);
      jDigiDocConfiguration.put(caPrefix + "_CERT" + (i + 1), certFile);
    }
  }
Ejemplo n.º 20
0
  public void run() {
    // each file is processed into a local hash table and then merged with the global results
    // this will cause much less contention on the global table, but still avoids a sequential
    // update
    Hashtable<String, Integer> local_results =
        new Hashtable<String, Integer>(WordCountJ.HASH_SIZE, WordCountJ.LF);
    // grab a file to work on
    String cf;
    while ((cf = files.poll()) != null) {
      try {
        BufferedReader input = new BufferedReader(new FileReader(cf));
        String text;
        // well go line-by-line... maybe this is not the fastest
        while ((text = input.readLine()) != null) {
          // parse words
          Matcher matcher = pattern.matcher(text);
          while (matcher.find()) {
            String word = matcher.group(1);
            if (local_results.containsKey(word)) {
              local_results.put(word, 1 + local_results.get(word));
            } else {
              local_results.put(word, 1);
            }
          }
        }
        input.close();
      } catch (Exception e) {
        System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage());
        return;
      }
      // merge local hashmap with shared one,could have a
      // seperate thread do this but that might be cheating

      Iterator<Map.Entry<String, Integer>> updates = local_results.entrySet().iterator();
      while (updates.hasNext()) {
        Map.Entry<String, Integer> kv = updates.next();
        String k = kv.getKey();
        Integer v = kv.getValue();
        synchronized (results) {
          if (results.containsKey(k)) {
            results.put(k, v + results.get(k));
          } else {
            results.put(k, v);
          }
        }
      }
      local_results.clear();
    }
  }
Ejemplo n.º 21
0
  // Scans the given file and creates symbols for its functions & label names.
  private void updateSymbolTable(File file, Hashtable symbols, Hashtable functions)
      throws ProgramException {
    BufferedReader reader = null;

    try {
      reader = new BufferedReader(new FileReader(file.getAbsolutePath()));
    } catch (FileNotFoundException fnfe) {
      throw new ProgramException("file " + file.getName() + " does not exist");
    }

    String line;
    String currentFunction = null;
    String label;
    int lineNumber = 0;

    isSlashStar = false;
    try {
      while ((line = unCommentLine(reader.readLine())) != null) {
        lineNumber++;
        if (!line.trim().equals("")) {
          if (line.startsWith("function ")) {
            StringTokenizer tokenizer = new StringTokenizer(line);
            tokenizer.nextToken();
            currentFunction = tokenizer.nextToken();
            if (symbols.containsKey(currentFunction))
              throw new ProgramException("subroutine " + currentFunction + " already exists");
            functions.put(currentFunction, new Short(nextPC));
            symbols.put(currentFunction, new Short(nextPC));
          } else if (line.startsWith("label ")) {
            StringTokenizer tokenizer = new StringTokenizer(line);
            tokenizer.nextToken();
            label = currentFunction + "$" + tokenizer.nextToken();
            symbols.put(label, new Short((short) (nextPC + 1)));
          }

          nextPC++;
        }
      }
      reader.close();
    } catch (IOException ioe) {
      throw new ProgramException("Error while reading from file");
    } catch (NoSuchElementException nsee) {
      throw new ProgramException("In line " + lineNumber + ": unexpected end of command");
    }
    if (isSlashStar) {
      throw new ProgramException("Unterminated /* comment at end of file");
    }
  }
 protected void finished() {
   logger.log(LogService.LOG_DEBUG, "Here is OcdHandler():finished()"); // $NON-NLS-1$
   if (!_isParsedDataValid) return;
   if (_ad_vector.size() == 0) {
     // Schema defines at least one AD is required.
     _isParsedDataValid = false;
     logger.log(
         LogService.LOG_ERROR,
         NLS.bind(
             MetaTypeMsg.MISSING_ELEMENT,
             new Object[] {
               AD,
               OCD,
               elementId,
               _dp_url,
               _dp_bundle.getBundleId(),
               _dp_bundle.getSymbolicName()
             }));
     return;
   }
   // OCD gets all parsed ADs.
   Enumeration<AttributeDefinitionImpl> adKey = _ad_vector.elements();
   while (adKey.hasMoreElements()) {
     AttributeDefinitionImpl ad = adKey.nextElement();
     _ocd.addAttributeDefinition(ad, ad._isRequired);
   }
   _ocd.setIcons(icons);
   _parent_OCDs_hashtable.put(_refID, _ocd);
 }
Ejemplo n.º 23
0
 void newVideoEntry(
     int ivChIndex,
     String ivAcronym,
     String ivCodec,
     int ivQuality,
     String ivImageSize,
     int ivDesiredFR,
     int ivDesiredBW,
     int ivCodecBW,
     int ivSentFR,
     int ivSentBW,
     int ivReceivedBW,
     int ivEnsembledFR,
     int ivPaintFR) {
   videoEntry_t videoEntry =
       new videoEntry_t(
           ivChIndex,
           ivAcronym,
           ivCodec,
           ivQuality,
           ivImageSize,
           ivDesiredFR,
           ivDesiredBW,
           ivCodecBW,
           ivSentFR,
           ivSentBW,
           ivReceivedBW,
           ivEnsembledFR,
           ivPaintFR);
   videoTable.put(new Integer(ivChIndex), videoEntry);
   addNewOids(ivChIndex);
   isSorted = false;
 }
Ejemplo n.º 24
0
 private void newVideoEntry(int ivChIndex) {
   videoEntry_t videoEntry =
       new videoEntry_t(ivChIndex, null, null, 0, null, 0, 0, 0, 0, 0, 0, 0, 0);
   videoTable.put(new Integer(ivChIndex), videoEntry);
   addNewOids(ivChIndex);
   isSorted = false;
 }
Ejemplo n.º 25
0
  public void populate(EvolutionState state, int thread) {
    // should we load individuals from a file? -- duplicates are permitted
    if (loadInds != null) {
      try {
        readSubpopulation(state, new LineNumberReader(new FileReader(loadInds)));
      } catch (IOException e) {
        state.output.fatal(
            "An IOException occurred when trying to read from the file "
                + loadInds
                + ".  The IOException was: \n"
                + e);
      }
    } else {
      Hashtable h = null;
      if (numDuplicateRetries >= 1) h = new Hashtable(individuals.length / 2); // seems reasonable

      for (int x = 0; x < individuals.length; x++) {
        for (int tries = 0; tries <= /* Yes, I see that*/ numDuplicateRetries; tries++) {
          individuals[x] = species.newIndividual(state, thread);

          if (numDuplicateRetries >= 1) {
            // check for duplicates
            Object o = h.get(individuals[x]);
            if (o == null) // found nothing, we're safe
            // hash it and go
            {
              h.put(individuals[x], individuals[x]);
              break;
            }
          }
        } // oh well, we tried to cut down the duplicates
      }
    }
  }
Ejemplo n.º 26
0
  /**
   * Callback method from _scanKeychain. If a trusted certificate is found, this method will be
   * called.
   */
  private void createTrustedCertEntry(
      String alias, long keychainItemRef, long creationDate, byte[] derStream) {
    TrustedCertEntry tce = new TrustedCertEntry();

    try {
      CertificateFactory cf = CertificateFactory.getInstance("X.509");
      InputStream input = new ByteArrayInputStream(derStream);
      X509Certificate cert = (X509Certificate) cf.generateCertificate(input);
      input.close();
      tce.cert = cert;
      tce.certRef = keychainItemRef;

      // Make a creation date.
      if (creationDate != 0) tce.date = new Date(creationDate);
      else tce.date = new Date();

      int uniqueVal = 1;
      String originalAlias = alias;

      while (entries.containsKey(alias.toLowerCase())) {
        alias = originalAlias + " " + uniqueVal;
        uniqueVal++;
      }

      entries.put(alias.toLowerCase(), tce);
    } catch (Exception e) {
      // The certificate will be skipped.
      System.err.println("KeychainStore Ignored Exception: " + e);
    }
  }
Ejemplo n.º 27
0
  public synchronized void messageReceived(int to, Message m) {

    DrainMsg mhMsg = (DrainMsg) m;

    log.debug(
        "incoming: localDest: "
            + to
            + " type:"
            + mhMsg.get_type()
            + " hops:"
            + (16 - mhMsg.get_ttl())
            + " seqNo:"
            + mhMsg.get_seqNo()
            + " source:"
            + mhMsg.get_source()
            + " finalDest:"
            + mhMsg.get_dest());

    // lets assume that the network cannot buffer more than 25 drain msgs from a single source at a
    // time (should be more than reasonable)
    if (seqNos.containsKey(new Integer(mhMsg.get_source()))) {
      int oldSeqNo = ((Integer) seqNos.get(new Integer(mhMsg.get_source()))).intValue();
      int upperBound = mhMsg.get_seqNo() + 25;
      int wrappedUpperBound = 25 - (255 - mhMsg.get_seqNo());
      if ((oldSeqNo >= mhMsg.get_seqNo() && oldSeqNo < upperBound)
          || (oldSeqNo >= 0 && oldSeqNo < wrappedUpperBound)) {
        log.debug(
            "Dropping message from "
                + mhMsg.get_source()
                + " with duplicate seqNo: "
                + mhMsg.get_seqNo());
        return;
      }
    }
    seqNos.put(new Integer(mhMsg.get_source()), new Integer(mhMsg.get_seqNo()));

    if (to != spAddr && to != MoteIF.TOS_BCAST_ADDR && to != TOS_UART_ADDR) {
      log.debug("Dropping message not for me.");
      return;
    }

    HashSet promiscuousSet = (HashSet) idTable.get(new Integer(BCAST_ID));
    HashSet listenerSet = (HashSet) idTable.get(new Integer(mhMsg.get_type()));

    if (listenerSet != null && promiscuousSet != null) {
      listenerSet.addAll(promiscuousSet);
    } else if (listenerSet == null && promiscuousSet != null) {
      listenerSet = promiscuousSet;
    }

    if (listenerSet == null) {
      log.debug("No Listener for type: " + mhMsg.get_type());
      return;
    }

    for (Iterator it = listenerSet.iterator(); it.hasNext(); ) {
      MessageListener ml = (MessageListener) it.next();
      ml.messageReceived(to, mhMsg);
    }
  }
Ejemplo n.º 28
0
 /**
  * Load image from resource path (using getResource). Note that GIFs are loaded as _translucent_
  * indexed images. Images are cached: loading an image with the same name twice will get the
  * cached image the second time. If you want to remove an image from the cache, use purgeImage.
  * Throws JGError when there was an error.
  */
 @SuppressWarnings({"deprecation", "unchecked"})
 public JGImage loadImage(String imgfile) {
   Image img = (Image) loadedimages.get(imgfile);
   if (img == null) {
     URL imgurl = getClass().getResource(imgfile);
     if (imgurl == null) {
       try {
         File imgf = new File(imgfile);
         if (imgf.canRead()) {
           imgurl = imgf.toURL();
         } else {
           imgurl = new URL(imgfile);
           // throw new JGameError(
           //	"File "+imgfile+" not found.",true);
         }
       } catch (MalformedURLException e) {
         // e.printStackTrace();
         throw new JGameError("File not found or malformed path or URL '" + imgfile + "'.", true);
       }
     }
     img = output_comp.getToolkit().createImage(imgurl);
     loadedimages.put(imgfile, img);
   }
   try {
     ensureLoaded(img);
   } catch (Exception e) {
     // e.printStackTrace();
     throw new JGameError("Error loading image " + imgfile);
   }
   return new JREImage(img);
 }
Ejemplo n.º 29
0
  /* Heck there's no getenv, we have to roll one ourselves! */
  public static Hashtable getenv() throws Throwable {
    Process p;
    if (File.separator.equals("\\")) {
      p = Runtime.getRuntime().exec("cmd /c set");
    } else {
      p = Runtime.getRuntime().exec("printenv");
    }

    InputStream in = p.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String line;
    Hashtable table = new Hashtable();

    while ((line = reader.readLine()) != null) {
      int i = line.indexOf('=');
      if (i > 0) {
        String name = line.substring(0, i);
        String value = line.substring(i + 1);
        table.put(name, value);
      }
    }

    in.close();
    p.waitFor();
    return table;
  }
Ejemplo n.º 30
0
    /**
     * Add a named logger.  This does nothing and returns false if a logger
     * with the same name is already registered.
     * <p>
     * The Logger factory methods call this method to register each
     * newly created Logger.
     * <p>
     * The application should retain its own reference to the Logger 
     * object to avoid it being garbage collected.  The LogManager
     * may only retain a weak reference.
     *
     * @param   logger the new logger.
     * @return  true if the argument logger was registered successfully,
     *          false if a logger of that name already exists.
     * @exception NullPointerException if the logger name is null.
     */
    public synchronized boolean addLogger(Logger logger) {
	String name = logger.getName();
	if (name == null) {
	    throw new NullPointerException();
	}

	Logger old = (Logger) loggers.get(name);
	if (old != null) {
	    // We already have a registered logger with the given name.
	    return false;
	}

	// We're adding a new logger.
	// Note that we are creating a strong reference here that will
	// keep the Logger in existence indefinitely.
	loggers.put(name, logger);

	// Apply any initial level defined for the new logger.
	Level level = getLevelProperty(name+".level", null);
	if (level != null) {
	    doSetLevel(logger, level);
	}

	// If any of the logger's parents have levels defined,
	// make sure they are instantiated.
	int ix = 1;
	for (;;) {
	    int ix2 = name.indexOf(".", ix);
	    if (ix2 < 0) {
		break;
	    }
	    String pname = name.substring(0,ix2);
	    if (getProperty(pname+".level") != null) {
		// This pname has a level definition.  Make sure it exists.
		Logger plogger = Logger.getLogger(pname);
	    }
	    ix = ix2+1;
	}

	// Find the new node and its parent.
	LogNode node = findNode(name);
	node.logger = logger;
	Logger parent = null;
	LogNode nodep = node.parent;
	while (nodep != null) {
	    if (nodep.logger != null) {
		parent = nodep.logger;
		break;
	    }
	    nodep = nodep.parent;
	}

	if (parent != null) {
            doSetParent(logger, parent);
	}
	// Walk over the children and tell them we are their new parent.
	node.walkAndSetParent(logger);

	return true;
    }