private Class<?> findClassInComponents(final String name) throws ClassNotFoundException {
   final String classFilename = this.getClassFilename(name);
   final Enumeration<File> e = this.pathComponents.elements();
   while (e.hasMoreElements()) {
     final File pathComponent = e.nextElement();
     InputStream stream = null;
     try {
       stream = this.getResourceStream(pathComponent, classFilename);
       if (stream != null) {
         this.log("Loaded from " + pathComponent + " " + classFilename, 4);
         return this.getClassFromStream(stream, name, pathComponent);
       }
       continue;
     } catch (SecurityException se) {
       throw se;
     } catch (IOException ioe) {
       this.log(
           "Exception reading component " + pathComponent + " (reason: " + ioe.getMessage() + ")",
           3);
     } finally {
       FileUtils.close(stream);
     }
   }
   throw new ClassNotFoundException(name);
 }
 public URL getResource(final String name) {
   URL url = null;
   if (this.isParentFirst(name)) {
     url = ((this.parent == null) ? super.getResource(name) : this.parent.getResource(name));
   }
   if (url != null) {
     this.log("Resource " + name + " loaded from parent loader", 4);
   } else {
     final Enumeration<File> e = this.pathComponents.elements();
     while (e.hasMoreElements() && url == null) {
       final File pathComponent = e.nextElement();
       url = this.getResourceURL(pathComponent, name);
       if (url != null) {
         this.log("Resource " + name + " loaded from ant loader", 4);
       }
     }
   }
   if (url == null && !this.isParentFirst(name)) {
     if (this.ignoreBase) {
       url = ((this.getRootLoader() == null) ? null : this.getRootLoader().getResource(name));
     } else {
       url = ((this.parent == null) ? super.getResource(name) : this.parent.getResource(name));
     }
     if (url != null) {
       this.log("Resource " + name + " loaded from parent loader", 4);
     }
   }
   if (url == null) {
     this.log("Couldn't load Resource " + name, 4);
   }
   return url;
 }
Esempio n. 3
0
  /**
   * Looks up providers, and returns the property (and its associated provider) mapping the key, if
   * any. The order in which the providers are looked up is the provider-preference order, as
   * specificed in the security properties file.
   */
  private static ProviderProperty getProviderProperty(String key) {
    ProviderProperty entry = null;

    List providers = Providers.getProviderList().providers();
    for (int i = 0; i < providers.size(); i++) {

      String matchKey = null;
      Provider prov = (Provider) providers.get(i);
      String prop = prov.getProperty(key);

      if (prop == null) {
        // Is there a match if we do a case-insensitive property name
        // comparison? Let's try ...
        for (Enumeration e = prov.keys(); e.hasMoreElements() && prop == null; ) {
          matchKey = (String) e.nextElement();
          if (key.equalsIgnoreCase(matchKey)) {
            prop = prov.getProperty(matchKey);
            break;
          }
        }
      }

      if (prop != null) {
        ProviderProperty newEntry = new ProviderProperty();
        newEntry.className = prop;
        newEntry.provider = prov;
        return newEntry;
      }
    }

    return entry;
  }
Esempio n. 4
0
  /**
   * Returns a Set of Strings containing the names of all available algorithms or types for the
   * specified Java cryptographic service (e.g., Signature, MessageDigest, Cipher, Mac, KeyStore).
   * Returns an empty Set if there is no provider that supports the specified service or if
   * serviceName is null. For a complete list of Java cryptographic services, please see the <a
   * href="../../../guide/security/CryptoSpec.html">Java Cryptography Architecture API Specification
   * &amp; Reference</a>. Note: the returned set is immutable.
   *
   * @param serviceName the name of the Java cryptographic service (e.g., Signature, MessageDigest,
   *     Cipher, Mac, KeyStore). Note: this parameter is case-insensitive.
   * @return a Set of Strings containing the names of all available algorithms or types for the
   *     specified Java cryptographic service or an empty set if no provider supports the specified
   *     service.
   * @since 1.4
   */
  public static Set<String> getAlgorithms(String serviceName) {

    if ((serviceName == null) || (serviceName.length() == 0) || (serviceName.endsWith("."))) {
      return Collections.EMPTY_SET;
    }

    HashSet result = new HashSet();
    Provider[] providers = Security.getProviders();

    for (int i = 0; i < providers.length; i++) {
      // Check the keys for each provider.
      for (Enumeration e = providers[i].keys(); e.hasMoreElements(); ) {
        String currentKey = ((String) e.nextElement()).toUpperCase();
        if (currentKey.startsWith(serviceName.toUpperCase())) {
          // We should skip the currentKey if it contains a
          // whitespace. The reason is: such an entry in the
          // provider property contains attributes for the
          // implementation of an algorithm. We are only interested
          // in entries which lead to the implementation
          // classes.
          if (currentKey.indexOf(" ") < 0) {
            result.add(currentKey.substring(serviceName.length() + 1));
          }
        }
      }
    }
    return Collections.unmodifiableSet(result);
  }
Esempio n. 5
0
  protected void unpackComponents() throws IOException, FileNotFoundException {
    File applicationPackage = new File(getApplication().getPackageResourcePath());
    File componentsDir = new File(sGREDir, "components");
    if (componentsDir.lastModified() == applicationPackage.lastModified()) return;

    componentsDir.mkdir();
    componentsDir.setLastModified(applicationPackage.lastModified());

    GeckoAppShell.killAnyZombies();

    ZipFile zip = new ZipFile(applicationPackage);

    byte[] buf = new byte[32768];
    try {
      if (unpackFile(zip, buf, null, "removed-files")) removeFiles();
    } catch (Exception ex) {
      // This file may not be there, so just log any errors and move on
      Log.w(LOG_FILE_NAME, "error removing files", ex);
    }

    // copy any .xpi file into an extensions/ directory
    Enumeration<? extends ZipEntry> zipEntries = zip.entries();
    while (zipEntries.hasMoreElements()) {
      ZipEntry entry = zipEntries.nextElement();
      if (entry.getName().startsWith("extensions/") && entry.getName().endsWith(".xpi")) {
        Log.i("GeckoAppJava", "installing extension : " + entry.getName());
        unpackFile(zip, buf, entry, entry.getName());
      }
    }
  }
Esempio n. 6
0
 public Set<String> listResources(String subdir) {
   try {
     Set<String> result = new HashSet<String>();
     if (resourceURL != null) {
       String protocol = resourceURL.getProtocol();
       if (protocol.equals("jar")) {
         String resPath = resourceURL.getPath();
         int pling = resPath.lastIndexOf("!");
         URL jarURL = new URL(resPath.substring(0, pling));
         String resDirInJar = resPath.substring(pling + 2);
         String prefix = resDirInJar + subdir + "/";
         // System.out.printf("BaseMod.listResources: looking for names starting with %s\n",
         // prefix);
         JarFile jar = new JarFile(new File(jarURL.toURI()));
         Enumeration<JarEntry> entries = jar.entries();
         while (entries.hasMoreElements()) {
           String name = entries.nextElement().getName();
           if (name.startsWith(prefix) && !name.endsWith("/") && !name.contains("/.")) {
             // System.out.printf("BaseMod.listResources: name = %s\n", name);
             result.add(name.substring(prefix.length()));
           }
         }
       } else throw new RuntimeException("Resource URL protocol " + protocol + " not supported");
     }
     return result;
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
 public void addJavaLibraries() {
   final Vector<String> packages = JavaEnvUtils.getJrePackages();
   final Enumeration<String> e = packages.elements();
   while (e.hasMoreElements()) {
     final String packageName = e.nextElement();
     this.addSystemPackageRoot(packageName);
   }
 }
 private InputStream loadResource(final String name) {
   InputStream stream = null;
   File pathComponent;
   for (Enumeration<File> e = this.pathComponents.elements();
       e.hasMoreElements() && stream == null;
       stream = this.getResourceStream(pathComponent, name)) {
     pathComponent = e.nextElement();
   }
   return stream;
 }
Esempio n. 9
0
 private OncFilter makeLevelListFilter(Hashtable keywords) {
   // Create a filter
   OncFilter filter = new OncFilter(false);
   OncTreeNode rootNode = filter.getRootNode();
   OncTreeNode orNode = new OncTreeNode(TcapLogicalOperator.OR, Persistible.DO_NOT_SAVE);
   OncTreeNode keywordNode;
   for (Enumeration e = keywords.keys(); e.hasMoreElements(); ) {
     Object obj = e.nextElement();
     if (obj instanceof Keyword) orNode.add(new OncTreeNode(obj, (Persistible.DO_NOT_SAVE)));
   }
   rootNode.add(orNode);
   return filter;
 }
Esempio n. 10
0
  public String toString() {
    String s = "[" + helper_type + ";";
    for (Enumeration e = seq.elements(); e.hasMoreElements(); ) {
      try {
        Class c = (Class) e.nextElement();
        s += c.getName() + ",";
      } catch (NoSuchElementException ee) {
        s += "???" + ",";
      }
    }

    return s + "]";
  }
 public String getClasspath() {
   final StringBuilder sb = new StringBuilder();
   boolean firstPass = true;
   final Enumeration<File> componentEnum = this.pathComponents.elements();
   while (componentEnum.hasMoreElements()) {
     if (!firstPass) {
       sb.append(System.getProperty("path.separator"));
     } else {
       firstPass = false;
     }
     sb.append(componentEnum.nextElement().getAbsolutePath());
   }
   return sb.toString();
 }
Esempio n. 12
0
  public static void toJSON(ConfigurationAdmin admin, Writer osw, String filter) throws Exception {

    Configuration[] list = admin.listConfigurations(filter);
    Encoder encoder = codec.enc().to(osw);

    Protocol p = new Protocol();
    p.version = 1;
    p.date = new Date();
    p.size = list.length;
    encoder.put(p).append('\n');

    if (list != null)
      for (Configuration c : list) {
        Dictionary<String, Object> d = c.getProperties();
        Export export = new Export();
        export.values = new HashMap<String, Object>();
        export.factoryPid = c.getFactoryPid();
        export.pid = c.getPid();

        for (Enumeration<String> e = d.keys(); e.hasMoreElements(); ) {
          String k = e.nextElement();
          Object v = d.get(k);

          if (!(v instanceof String)) {

            if (export.types == null) export.types = new HashMap<String, Type>();

            Type type = new Type();

            Class<?> clazz = v.getClass();
            if (v instanceof Collection) {
              Collection<?> coll = (Collection<?>) v;
              clazz = String.class;
              if (coll.size() > 0) type.vectorOf = shortName(coll.iterator().next().getClass());
              else type.vectorOf = shortName(String.class);
            } else if (v.getClass().isArray()) {
              type.arrayOf = shortName(clazz.getComponentType());
            } else type.scalar = shortName(v.getClass());

            export.types.put(k, type);
          }
          export.values.put(k, v);
        }

        encoder.mark().put(export);
        // encoder.put(encoder.digest());
        encoder.append('\n');
      }
    osw.flush();
  }
 public synchronized void cleanup() {
   final Enumeration<JarFile> e = this.jarFiles.elements();
   while (e.hasMoreElements()) {
     final JarFile jarFile = e.nextElement();
     try {
       jarFile.close();
     } catch (IOException ex) {
     }
   }
   this.jarFiles = new Hashtable<File, JarFile>();
   if (this.project != null) {
     this.project.removeBuildListener(this);
   }
   this.project = null;
 }
Esempio n. 14
0
 /** Returns the property (if any) mapping the key for the given provider. */
 private static String getProviderProperty(String key, Provider provider) {
   String prop = provider.getProperty(key);
   if (prop == null) {
     // Is there a match if we do a case-insensitive property name
     // comparison? Let's try ...
     for (Enumeration e = provider.keys(); e.hasMoreElements() && prop == null; ) {
       String matchKey = (String) e.nextElement();
       if (key.equalsIgnoreCase(matchKey)) {
         prop = provider.getProperty(matchKey);
         break;
       }
     }
   }
   return prop;
 }
  /** Prepares the factory for bundle shutdown. */
  public void stop() {
    if (logger.isTraceEnabled()) logger.trace("Preparing to stop all protocol providers of" + this);

    synchronized (registeredAccounts) {
      for (Enumeration<ServiceRegistration> registrations = registeredAccounts.elements();
          registrations.hasMoreElements(); ) {
        ServiceRegistration reg = registrations.nextElement();

        stop(reg);

        reg.unregister();
      }

      registeredAccounts.clear();
    }
  }
  /**
   * This looks through a list of object classes in an attribute until it finds a unique editor
   * corresponding to a particular value. If no editor is found 'null' is returned. Note that If
   * multiple unique editors exist, which one is returned is undefined.
   *
   * <p>
   *
   * @param oc the objectClass attribute; a list of object classes
   * @return the unique pluggable editor corresponding to one particular object class value, or null
   *     if none is found.
   */
  public PluggableEditor getUniqueEditor(Attribute oc) {
    try {
      Enumeration values = oc.getAll();
      while (values.hasMoreElements()) {
        String objectClassName = (String) values.nextElement();

        PluggableEditor editor = getEditor(objectClassName);
        if (editor != null) {
          if (editor.isUnique()) return editor;
        }
      }
      return null;
    } catch (Exception e) {
      log.log(Level.FINE, "Unable to find unique pluggable editor: ", e);
      return null;
    }
  }
Esempio n. 17
0
File: Macro.java Progetto: bramk/bnd
 /**
  * Take all the properties and translate them to actual values. This method takes the set
  * properties and traverse them over all entries, including the default properties for that
  * properties. The values no longer contain macros.
  *
  * @return A new Properties with the flattened values
  */
 public Properties getFlattenedProperties() {
   // Some macros only work in a lower processor, so we
   // do not report unknown macros while flattening
   flattening = true;
   try {
     Properties flattened = new Properties();
     Properties source = domain.getProperties();
     for (Enumeration<?> e = source.propertyNames(); e.hasMoreElements(); ) {
       String key = (String) e.nextElement();
       if (!key.startsWith("_"))
         if (key.startsWith("-")) flattened.put(key, source.getProperty(key));
         else flattened.put(key, process(source.getProperty(key)));
     }
     return flattened;
   } finally {
     flattening = false;
   }
 }
Esempio n. 18
0
    public void define()
    {
        org.jacorb.util.Debug.output(2, "Struct " + name +  " defining...");
        for( Enumeration e = containedLocals.elements();
             e.hasMoreElements();
             ((IRObject)e.nextElement()).define())
            ;

        for( int i = 0; i < members.length; i++ )
        {
            members[i].type_def = IDLType.create( members[i].type, containing_repository);
            org.jacorb.util.Debug.assert( members[i].type_def != null,
                                      "No type_def for member " + members[i].name + 
                                      " in struct " +  full_name );
        }
        defined = true;
        org.jacorb.util.Debug.output(2, "Struct " + name +  " defined");

    }
Esempio n. 19
0
    public org.omg.CORBA.Contained[] lookup_name( String search_name, 
                                                  int levels_to_search, 
                                                  org.omg.CORBA.DefinitionKind limit_type, 
                                                  boolean exclude_inherited )
    {
        if( levels_to_search == 0 )
            return null;

        org.omg.CORBA.Contained[] c = contents( limit_type, exclude_inherited );
        Hashtable found = new Hashtable();

        for( int i = 0; i < c.length; i++)
            if( c[i].name().equals( search_name ) )
                found.put( c[i], "" );

        if( levels_to_search > 1 || levels_to_search == -1 )
        {
            // search up to a specific depth or undefinitely
            for( int i = 0; i < c.length; i++)
            {
                if( c[i] instanceof org.omg.CORBA.Container )
                {
                    org.omg.CORBA.Contained[] tmp_seq = 
                        ((org.omg.CORBA.Container)c[i]).lookup_name( search_name, 
                                                                     levels_to_search-1, 
                                                                     limit_type, 
                                                                     exclude_inherited);
                    if( tmp_seq != null )
                        for( int j = 0; j < tmp_seq.length; j++)
                            found.put( tmp_seq[j], "" );
                }
            } 			
        }

		
        org.omg.CORBA.Contained[] result = new org.omg.CORBA.Contained[ found.size() ];
        int idx = 0;

        for( Enumeration e = found.keys(); e.hasMoreElements(); )
            result[ idx++] = (org.omg.CORBA.Contained)e.nextElement();

        return result;
    }
 private boolean isParentFirst(final String resourceName) {
   boolean useParentFirst = this.parentFirst;
   Enumeration<String> e = this.systemPackages.elements();
   while (e.hasMoreElements()) {
     final String packageName = e.nextElement();
     if (resourceName.startsWith(packageName)) {
       useParentFirst = true;
       break;
     }
   }
   e = this.loaderPackages.elements();
   while (e.hasMoreElements()) {
     final String packageName = e.nextElement();
     if (resourceName.startsWith(packageName)) {
       useParentFirst = false;
       break;
     }
   }
   return useParentFirst;
 }
Esempio n. 21
0
  public boolean equals(Object another) {
    if (another instanceof HelperCacheKey) {
      HelperCacheKey another_key = (HelperCacheKey) another;

      if (!this.helper_type.equals(another_key.helper_type)) return false;

      Enumeration e1, e2;
      for (e1 = this.seq.elements(), e2 = another_key.seq.elements(); e1.hasMoreElements(); ) {
        Object o1, o2;
        try {
          o1 = e1.nextElement();
        } catch (NoSuchElementException ex) {
          throw new RuntimeException("HelperCacheKey.equals: should never happen, " + ex);
        }
        try {
          o2 = e2.nextElement();
        } catch (NoSuchElementException ex) {
          return false;
        } // e2 has fewer elements than e2, no match

        if (!o1.equals(o2)) return false;
      }

      if (e2.hasMoreElements()) return false;
      else return true;
    } else return false;
  }
Esempio n. 22
0
 public Vector getAssociatedLevelLists() {
   Vector levelLists = new Vector();
   Vector endPts = CollectionHelper.makeVector("Keyword");
   Hashtable keywordParents =
       oncotcap.Oncotcap.getDataSource()
           .getParentTree(
               "Keyword", endPts, CollectionHelper.makeVector(this), TreeDisplayModePanel.ROOT);
   // Take each of the parents and get the associated level lists
   if (keywordParents.size() <= 0) return levelLists;
   Hashtable levelListsHashtable =
       oncotcap.Oncotcap.getDataSource()
           .getInstanceTree(
               "EnumLevelList",
               new Vector(),
               makeLevelListFilter(keywordParents),
               TreeDisplayModePanel.ROOT);
   for (Enumeration e = keywordParents.keys(); e.hasMoreElements(); ) {
     System.out.println("Keyword.getAssociatedLevelLists: " + e.nextElement());
   }
   // Collect all the level lists from the hashtable
   Vector selectedItems = CollectionHelper.makeVector(keyword);
   for (Enumeration e = levelListsHashtable.keys(); e.hasMoreElements(); ) {
     Object obj = e.nextElement();
     if (obj instanceof EnumLevelList) {
       levelLists.addElement(obj);
     }
   }
   return levelLists;
 }
Esempio n. 23
0
  public String verify(JarFile jar, String... algorithms) throws IOException {
    if (algorithms == null || algorithms.length == 0) algorithms = new String[] {"MD5", "SHA"};
    else if (algorithms.length == 1 && algorithms[0].equals("-")) return null;

    try {
      Manifest m = jar.getManifest();
      if (m.getEntries().isEmpty()) return "No name sections";

      for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements(); ) {
        JarEntry je = e.nextElement();
        if (MANIFEST_ENTRY.matcher(je.getName()).matches()) continue;

        Attributes nameSection = m.getAttributes(je.getName());
        if (nameSection == null) return "No name section for " + je.getName();

        for (String algorithm : algorithms) {
          try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            String expected = nameSection.getValue(algorithm + "-Digest");
            if (expected != null) {
              byte digest[] = Base64.decodeBase64(expected);
              copy(jar.getInputStream(je), md);
              if (!Arrays.equals(digest, md.digest()))
                return "Invalid digest for "
                    + je.getName()
                    + ", "
                    + expected
                    + " != "
                    + Base64.encodeBase64(md.digest());
            } else reporter.error("could not find digest for " + algorithm + "-Digest");
          } catch (NoSuchAlgorithmException nsae) {
            return "Missing digest algorithm " + algorithm;
          }
        }
      }
    } catch (Exception e) {
      return "Failed to verify due to exception: " + e.getMessage();
    }
    return null;
  }
Esempio n. 24
0
  /**
   * Check the helpers currently stored in the helper cache to see if any of them can handle the
   * sequence we've just been given. This avoids pinging the belief network context to get a helper
   * list.
   */
  public static Class find_helper_class1(
      Vector seq, String helper_type, int[] max_class_score, int[] max_count_score)
      throws ClassNotFoundException {
    int[] class_score1 = new int[1], count_score1 = new int[1];
    max_class_score[0] = -1;
    max_count_score[0] = -1;
    Class cmax_score = null;

    for (Enumeration e = helper_cache.keys(); e.hasMoreElements(); ) {
      try {
        HelperCacheKey key = (HelperCacheKey) e.nextElement();
        if (!key.helper_type.equals(helper_type)) continue;
        Class c = (Class) helper_cache.get(key);
        SeqTriple[] sm = (SeqTriple[]) invoke_description(c);
        if (sm == null) continue; // apparently not a helper class
        if (MatchClassPattern.matches(sm, seq, class_score1, count_score1)) {
          if (class_score1[0] > max_class_score[0]
              || (class_score1[0] == max_class_score[0] && count_score1[0] > max_count_score[0])) {
            cmax_score = c;
            max_class_score[0] = class_score1[0];
            max_count_score[0] = count_score1[0];
          }
        }
      } catch (Exception e2) {
      } // eat it; stagger forward
    }

    if (Global.debug > 1)
      System.err.println(
          "PiHelperLoader.find_helper_class1: helper "
              + (cmax_score == null ? "is NOT" : "is")
              + " in cache.");
    if (cmax_score == null) // no luck; try to get a helper list from the bnc & plunge ahead
    return find_helper_class0(seq, helper_type, max_class_score, max_count_score);
    else // success!
    return cmax_score;
  }
Esempio n. 25
0
  /**
   * Location where you can add commandline properties to the connection The Super class will call
   * this function before creating the connection
   *
   * @param cmdLine command line operations
   * @see CommandLine
   */
  public void addMoreProps(CommandLine cmdLine) {
    Enumeration extras = cmdLine._extraArgs.elements();
    Enumeration options = cmdLine._extraOptions.elements();
    while (extras.hasMoreElements()) {

      String option = (String) extras.nextElement();
      String value = (String) options.nextElement();
      String loaderURL = null;
      error("Extra options= " + option + " " + value + "\n");

      if (option.equals(_extraCmdOption) && loaderURL == null) {
        loaderURL = value;
        Properties props = (Properties) _cmdline._props.clone();
        _loader = _sybDriver.getClassLoader(loaderURL, props);
        if (_loader == null) {
          error("Could not get a CLASS_LOADER");
          break;
        }
        _cmdline._props.put("CLASS_LOADER", _loader);
        _gotClassLoader = true;
        break;
      }
    }
  }
Esempio n. 26
0
    public org.omg.CORBA.Contained[] contents(org.omg.CORBA.DefinitionKind limit_type, 
                                              boolean exclude_inherited)
    {
        Hashtable limited = new Hashtable();

        // analog constants, exceptions etc.

        for( Enumeration e = contained.elements(); e.hasMoreElements();  )
        {
            org.omg.CORBA.Contained c = (org.omg.CORBA.Contained)e.nextElement();
            if( limit_type == org.omg.CORBA.DefinitionKind.dk_all || 
                limit_type == c.def_kind() )
            {
                limited.put( c, "" );
            }
        }

        org.omg.CORBA.Contained[] c = new org.omg.CORBA.Contained[limited.size()];
        int i;
        Enumeration e;
        for( e = limited.keys(), i=0 ; e.hasMoreElements(); i++ )
            c[i] = (org.omg.CORBA.Contained)e.nextElement();
        return c;			
    }
  /**
   * Clear out all the old editors, and get new editors corresponding to the new object classes.
   *
   * @param entry the entry to be displayed by all the editors
   * @param ds the datasource the editors may use for more info
   * @param ocs the object classes (in order) to find editors for.
   */
  protected void setEditors(DXEntry entry, DataBrokerQueryInterface ds, Vector ocs) {

    try {
      clearPluggableEditors(); // clear all extra editors

      // search for unique structural editors...

      if ("false".equalsIgnoreCase(JXConfig.getProperty("plugins.ignoreUniqueness"))) {
        if (ocs == null) // TE: may happen if virtual entry.
        return;

        int size = ocs.size();

        for (int i = 0; i < size; i++) {
          Object objectClass = ocs.get(i);
          if (objectClass != null) {
            PluggableEditor ed = getEditor(objectClass.toString());
            if (ed != null && ed.isUnique() == true) // found a unique editor
            { // so clear old ones,
              addUniqueEditor(ed); // and use the unique one
              refreshEditors(entry, ds); // to display the data
              setCurrentEditor(ed);
              return; // ... and exit.
            }
          }
        }
      } else log.warning("skipping uniqueness test for pluggable editors");

      boolean newEdSet = false;

      // search for non-unique structural editors
      for (int i = 0; i < ocs.size(); i++) {
        Object objectClass = ocs.get(i);
        if (objectClass != null) {
          PluggableEditor ed = getEditor(objectClass.toString());
          if (ed != null) {
            addEditor(ed);

            // Force the displayed editor to be the first pluggable one...
            if (newEdSet == false) {
              setCurrentEditor(ed);
              newEdSet = true;
            }
          }
        }
      }

      // search for non-structural editors
      try {
        Attribute allOCs = entry.getAllObjectClasses();
        if (allOCs != null) {
          Enumeration vals = allOCs.getAll();
          while (vals.hasMoreElements()) {
            Object oc = vals.nextElement();
            if (oc != null) {
              String ocName = oc.toString();
              if (ocs.contains(ocName)
                  == false) // don't bother with struct objectclasses dealt with above
              {
                PluggableEditor ed = getEditor(ocName);

                if (ed != null) {
                  addEditor(ed);

                  if (ed.isUnique()) // a special service to users...
                  log.warning(
                        "WARNING: Illegal unique editor defined for oc: "
                            + ocName
                            + " not allowed - (oc not in primary structural inheritance chain)");
                }
              }
            }
          }
        }
      } catch (NamingException e) {
        log.log(
            Level.WARNING,
            "WARNING: non-fatal exception getting object classes for plugin editors. ",
            e);
      }

      addEditor(templateDisplay); // and always add old faithfulls...
      // XXX
      if (entry.getStatus() != DXEntry.NEW) // well, almost always...
      addEditor(tableDisplay);
    } catch (Exception e) {
      log.warning("Unexpected Exception in AttributeDisplay\n" + e);
      e.printStackTrace();
    }
  }
Esempio n. 28
0
  /* PROTECTED METHODS */
  protected void getBeanElements(
      Element parentElement, String objectName, String objectType, Object bean)
      throws IntrospectionException, IllegalAccessException {
    if (objectName == null) {
      // Get just the class name by lopping off the package name
      StringBuffer sb = new StringBuffer(bean.getClass().getName());
      sb.delete(0, sb.lastIndexOf(".") + 1);
      objectName = sb.toString();
    }

    // Check if the bean is a standard Java object type or a byte[] (encoded as a base 64 array)
    Element element = getStandardObjectElement(document, bean, objectName);
    // If the body element object is null then the bean is not a standard Java object type
    if (element != null) {
      if (includeNullValues
          || !element
              .getAttribute(
                  NamespaceConstants.NSPREFIX_SCHEMA_XSI
                      + ":"
                      + org.apache.axis.Constants.ATTR_TYPE)
              .equals("anyType")) {
        if (!includeTypeInfo) {
          element.removeAttribute(
              NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + org.apache.axis.Constants.ATTR_TYPE);
          element.removeAttribute(NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null");
        }
        parentElement.appendChild(element);
      }
    } else {
      // Analyze the bean
      Class classOfBean = null;
      if (bean != null) classOfBean = bean.getClass();
      // If the object is an array, then serialize each of the beans in the array.
      if ((classOfBean != null) && (classOfBean.isArray())) {
        String[] arrayInfo = getXsdSoapArrayInfo(classOfBean.getCanonicalName(), nsPrefix);
        int arrayLen = Array.getLength(bean);
        StringBuffer arrayType = new StringBuffer(arrayInfo[1]);
        arrayType.insert(arrayType.indexOf("[]") + 1, arrayLen);
        if (objectName.charAt(objectName.length() - 1) == ';')
          objectName =
              new StringBuffer(objectName).deleteCharAt(objectName.length() - 1).toString();
        element = document.createElement(objectName);
        parentElement.appendChild(element);
        // Get the bean objects from the array and serialize each
        for (int i = 0; i < arrayLen; i++) {
          Object b = Array.get(bean, i);
          if (b != null) {
            String name = null;
            if (objectName.charAt(objectName.length() - 1) == 's') {
              name = formatName(objectName.substring(0, objectName.length() - 1));
            }
            getBeanElements(element, name, b.getClass().getName(), b);
          } else {
            // Array element is null, so don't include it and decrement the # elements in the array
            int index = arrayType.indexOf("[");
            arrayType.replace(index + 1, index + 2, String.valueOf(--arrayLen));
          }
          if (includeTypeInfo) {
            element.setAttributeNS(
                NamespaceConstants.NSURI_SCHEMA_XSI,
                NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE,
                NamespaceConstants.NSPREFIX_SOAP_ENCODING + ":Array");
            element.setAttributeNS(
                NamespaceConstants.NSURI_SOAP_ENCODING,
                NamespaceConstants.NSPREFIX_SOAP_ENCODING + ":" + Constants.ATTR_ARRAY_TYPE,
                arrayInfo[0] + ":" + arrayType.toString());
          }
        }
      } else {
        int beanType = 0;
        String beanName = null;
        if (classOfBean != null) {
          if (classOfBean == Vector.class) {
            beanType = 1;
            beanName = "Vector";
          } else if (classOfBean == ArrayList.class) {
            beanType = 2;
            beanName = "ArrayList";
          } else if (classOfBean == LinkedList.class) {
            beanType = 3;
            beanName = "LinkedList";
          } else if (classOfBean == Hashtable.class) {
            beanType = 4;
            beanName = "Hashtable";
          } else if (classOfBean == Properties.class) {
            beanType = 5;
            beanName = "Properties";
          } else if ((classOfBean == HashMap.class) || (classOfBean == SortedMap.class)) {
            beanType = 6;
            beanName = "Map";
          }
        }
        if (beanType > 0) {
          String prefix = null;
          if ((beanType == 1) || (beanType == 5))
            prefix = NamespaceConstants.NSPREFIX_SOAP_ENCODING;
          if (beanType == 6) prefix = Constants.NS_PREFIX_XMLSOAP;
          else prefix = DEFAULT_NS_PREFIX;
          element = document.createElement(objectName);
          if (includeTypeInfo) {
            element.setAttributeNS(
                NamespaceConstants.NSURI_SCHEMA_XSI,
                NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE,
                prefix + ":" + beanName);
            if (bean == null)
              element.setAttributeNS(
                  NamespaceConstants.NSURI_SCHEMA_XSI,
                  NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null",
                  "true");
          }
          parentElement.appendChild(element);
          if ((beanType >= 1) && (beanType <= 3)) {
            AbstractCollection collection = (AbstractCollection) bean;
            // Get the bean objects from the vector and serialize each
            Iterator it = collection.iterator();
            while (it.hasNext()) {
              Object b = it.next();
              String name = null;
              if (b != null) {
                if (objectName.charAt(objectName.length() - 1) == 's') {
                  name = formatName(objectName.substring(0, objectName.length() - 1));
                } else name = "item";
              }
              getBeanElements(element, name, b.getClass().getName(), b);
            }
          } else if ((beanType == 4) || (beanType == 5)) {
            Hashtable hashtable = (Hashtable) bean;
            // Get the bean objects from the hashtable or properties and serialize each
            Enumeration en = hashtable.keys();
            while (en.hasMoreElements()) {
              Object key = en.nextElement();
              String keyClassName = key.getClass().getName();
              Object value = hashtable.get(key);
              String beanClassName = null;
              if (value != null) beanClassName = value.getClass().getName();
              Element itemElement = document.createElement("item");
              element.appendChild(itemElement);
              getBeanElements(itemElement, "key", keyClassName, key);
              getBeanElements(itemElement, "value", beanClassName, value);
            }
          } else if (beanType == 6) {
            Map map = null;
            if (classOfBean == HashMap.class) map = (HashMap) bean;
            else if (classOfBean == SortedMap.class) map = (SortedMap) bean;
            // Get the bean objects from the hashmap and serialize each
            Set set = map.keySet();
            Iterator it = set.iterator();
            while (it.hasNext()) {
              Object key = it.next();
              String keyClassName = key.getClass().getName();
              Object value = map.get(key);
              String beanClassName = null;
              if (value != null) beanClassName = value.getClass().getName();
              Element itemElement = document.createElement("item");
              element.appendChild(itemElement);
              getBeanElements(itemElement, "key", keyClassName, key);
              getBeanElements(itemElement, "value", beanClassName, value);
            }
          }
        } else {
          // Create a parent element for this bean's properties
          if (objectName.charAt(objectName.length() - 1) == ';')
            objectName =
                new StringBuffer(objectName).deleteCharAt(objectName.length() - 1).toString();
          objectName = formatName(objectName);
          element = document.createElement(objectName);
          parentElement.appendChild(element);
          if (includeTypeInfo) {
            StringBuffer className = new StringBuffer(objectType);
            element.setAttributeNS(
                NamespaceConstants.NSURI_SCHEMA_XSI,
                NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE,
                nsPrefix + ":" + className.delete(0, className.lastIndexOf(".") + 1).toString());
          }
          if (classOfBean != null) {
            // Get an array of property descriptors
            BeanInfo bi = Introspector.getBeanInfo(classOfBean);
            PropertyDescriptor[] pds = bi.getPropertyDescriptors();
            // For each property of the bean, get a SOAPBodyElement that
            // represents the individual property. Append that SOAPBodyElement
            // to the class name element of the SOAP body.
            for (int i = 0; i < pds.length; i++) {
              PropertyDescriptor pd = pds[i];
              getBeanElementProperties(element, bean, pd);
            }
          } else {
            if (includeTypeInfo)
              element.setAttributeNS(
                  NamespaceConstants.NSURI_SCHEMA_XSI,
                  NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null",
                  "true");
          }
        }
      }
    }
  }
Esempio n. 29
0
  /**
   * Contact a belief network context, get the helper list, and search the list to see if there's a
   * helper which matches the type sequence specified. If there's more than one helper which
   * matches, find the ``best fit.''
   *
   * <p>The class and count scores of the best-fitting helper class are written into
   * <tt>max_class_score[0]</tt> and <tt>max_count_score[0]</tt>, respectively.
   */
  public static Class find_helper_class0(
      Vector seq, String helper_type, int[] max_class_score, int[] max_count_score)
      throws ClassNotFoundException {
    long t0 = System.currentTimeMillis();
    if (bnc != null) // make sure the reference is still alive
    try {
        bnc.get_name();
      } catch (RemoteException e) {
        bnc = null;
      }

    if (bnc == null) // need to locate a context
    {
      String cb = System.getProperty("java.rmi.server.codebase", "http://localhost");
      long tt0 = System.currentTimeMillis();
      try {
        bnc = BeliefNetworkContext.locate_context(new URL(cb).getHost());
      } catch (Exception e) {
        throw new ClassNotFoundException("nested: " + e);
      }
    }

    String[] helperlist;
    try {
      helperlist = bnc.get_helper_names(helper_type);
    } catch (RemoteException e) {
      throw new ClassNotFoundException("bnc.get_helper_names failed");
    }

    int[] class_score1 = new int[1], count_score1 = new int[1];
    max_class_score[0] = -1;
    max_count_score[0] = -1;
    Class cmax_score = null;

    for (int i = 0; i < helperlist.length; i++) {
      try {
        Class c = RMIClassLoader.loadClass(helperlist[i]);
        SeqTriple[] sm = (SeqTriple[]) invoke_description(c);
        if (sm == null) continue; // apparently not a helper class
        if (MatchClassPattern.matches(sm, seq, class_score1, count_score1)) {
          if (class_score1[0] > max_class_score[0]
              || (class_score1[0] == max_class_score[0] && count_score1[0] > max_count_score[0])) {
            cmax_score = c;
            max_class_score[0] = class_score1[0];
            max_count_score[0] = count_score1[0];
          }
        }
      } catch (Exception e2) {
        System.err.println("PiHelperLoader: attempt to load " + helperlist[i] + " failed; " + e2);
      }
    }

    if (cmax_score == null) {
      System.err.println("find_helper_class0: failed; helper list:");
      for (int i = 0; i < helperlist.length; i++) System.err.println("\t" + helperlist[i]);

      String s = "";
      for (Enumeration e = seq.elements(); e.hasMoreElements(); ) {
        try {
          Class c = (Class) e.nextElement();
          s += c.getName() + ",";
        } catch (NoSuchElementException ee) {
          s += "???" + ",";
        }
      }

      throw new ClassNotFoundException("no " + helper_type + " helper for sequence [" + s + "]");
    }

    // FOR NOW IGNORE THE POSSIBILITY OF TWO OR MORE MATCHES !!!
    return cmax_score;
  }
Esempio n. 30
0
 private void dump() throws IOException {
   lookupMethod = null;
   try {
     lookupMethod = catalog.getClass().getMethod("lookup", new Class[] {java.lang.String.class});
   } catch (NoSuchMethodException e) {
   } catch (SecurityException e) {
   }
   Method pluralMethod = null;
   try {
     pluralMethod = catalog.getClass().getMethod("get_msgid_plural_table", new Class[0]);
   } catch (NoSuchMethodException e) {
   } catch (SecurityException e) {
   }
   Field pluralField = null;
   try {
     pluralField = catalog.getClass().getField("plural");
   } catch (NoSuchFieldException e) {
   } catch (SecurityException e) {
   }
   // Search for the header entry.
   {
     Object header_entry = null;
     Enumeration keys = catalog.getKeys();
     while (keys.hasMoreElements())
       if ("".equals(keys.nextElement())) {
         header_entry = lookup("");
         break;
       }
     // If there is no header entry, fake one.
     // FIXME: This is not needed; right after po_lex_charset_init set
     // the PO charset to UTF-8.
     if (header_entry == null) header_entry = "Content-Type: text/plain; charset=UTF-8\n";
     dumpMessage("", null, header_entry);
   }
   // Now the other messages.
   {
     Enumeration keys = catalog.getKeys();
     Object plural = null;
     if (pluralMethod != null) {
       // msgfmt versions > 0.13.1 create a static get_msgid_plural_table()
       // method.
       try {
         plural = pluralMethod.invoke(catalog, new Object[0]);
       } catch (IllegalAccessException e) {
         e.printStackTrace();
       } catch (InvocationTargetException e) {
         e.getTargetException().printStackTrace();
       }
     } else if (pluralField != null) {
       // msgfmt versions <= 0.13.1 create a static plural field.
       try {
         plural = pluralField.get(catalog);
       } catch (IllegalAccessException e) {
         e.printStackTrace();
       }
     }
     if (plural instanceof String[]) {
       // A GNU gettext created class with plural handling, Java2 format.
       int i = 0;
       while (keys.hasMoreElements()) {
         String key = (String) keys.nextElement();
         Object value = lookup(key);
         String key_plural = (value instanceof String[] ? ((String[]) plural)[i++] : null);
         if (!"".equals(key)) dumpMessage(key, key_plural, value);
       }
       if (i != ((String[]) plural).length)
         throw new RuntimeException("wrong plural field length");
     } else if (plural instanceof Hashtable) {
       // A GNU gettext created class with plural handling, Java format.
       while (keys.hasMoreElements()) {
         String key = (String) keys.nextElement();
         if (!"".equals(key)) {
           Object value = lookup(key);
           String key_plural =
               (value instanceof String[] ? (String) ((Hashtable) plural).get(key) : null);
           dumpMessage(key, key_plural, value);
         }
       }
     } else if (plural == null) {
       // No plural handling.
       while (keys.hasMoreElements()) {
         String key = (String) keys.nextElement();
         if (!"".equals(key)) dumpMessage(key, null, lookup(key));
       }
     } else throw new RuntimeException("wrong plural field value");
   }
 }