Example #1
0
 private static Type FilePathToClass(string cpEntry, string path)
 {
     if (path.Length <= cpEntry.Length)
     {
         throw new ArgumentException("Illegal path: cp=" + cpEntry + " path=" + path);
     }
     if (path[cpEntry.Length] != '/')
     {
         throw new ArgumentException("Illegal path: cp=" + cpEntry + " path=" + path);
     }
     path = Sharpen.Runtime.Substring(path, cpEntry.Length + 1);
     path = Sharpen.Runtime.Substring(path.ReplaceAll("/", "."), 0, path.Length - 6);
     try
     {
         return(Sharpen.Runtime.GetType(path, false, ClassLoader.GetSystemClassLoader()));
     }
     catch (TypeLoadException)
     {
         throw Redwood.Util.Fail("Could not load class at path: " + path);
     }
     catch (NoClassDefFoundError)
     {
         Redwood.Util.Warn("Class at path " + path + " is unloadable");
         return(null);
     }
 }
Example #2
0
        private static IDataset GetDatasetClass(Properties dsParams)
        {
            IDataset ds     = null;
            string   dsType = dsParams.GetProperty(ConfigParser.paramType);

            dsParams.Remove(ConfigParser.paramType);
            try
            {
                if (dsType == null)
                {
                    ds = new ATBArabicDataset();
                }
                else
                {
                    Type c = ClassLoader.GetSystemClassLoader().LoadClass(dsType);
                    ds = (IDataset)System.Activator.CreateInstance(c);
                }
            }
            catch (TypeLoadException)
            {
                System.Console.Error.Printf("Dataset type %s does not exist%n", dsType);
            }
            catch (InstantiationException)
            {
                System.Console.Error.Printf("Unable to instantiate dataset type %s%n", dsType);
            }
            catch (MemberAccessException)
            {
                System.Console.Error.Printf("Unable to access dataset type %s%n", dsType);
            }
            return(ds);
        }
Example #3
0
 private static ITreeVisitor LoadTreeVistor(string value)
 {
     try
     {
         Type c = ClassLoader.GetSystemClassLoader().LoadClass(value);
         return((ITreeVisitor)System.Activator.CreateInstance(c));
     }
     catch (ReflectiveOperationException e)
     {
         Sharpen.Runtime.PrintStackTrace(e);
     }
     return(null);
 }
Example #4
0
 private static Map<String, Class<?>> GetLoadedClasses(String ptrn) {
     ClassLoader appLoader = ClassLoader.GetSystemClassLoader();
     try {
         Vector<Class<?>> classes = (Vector<Class<?>>) _classes.Get(appLoader);
         Map<String, Class<?>> map = new HashMap<String, Class<?>>();
         for (Class<?> cls : classes) {
             String jar = cls.GetProtectionDomain().getCodeSource().getLocation().toString();
             if(jar.IndexOf(ptrn) != -1) map.Put(cls.GetName(), cls);
         }
         return map;
     } catch (IllegalAccessException e) {
         throw new RuntimeException(e);
     }
 }
Example #5
0
        private IMapper LoadMapper(string className)
        {
            IMapper m = null;

            try
            {
                Type c = ClassLoader.GetSystemClassLoader().LoadClass(className);
                m = (IMapper)System.Activator.CreateInstance(c);
            }
            catch (TypeLoadException)
            {
                System.Console.Error.Printf("%s: Mapper type %s does not exist\n", this.GetType().FullName, className);
            }
            catch (InstantiationException e)
            {
                System.Console.Error.Printf("%s: Unable to instantiate mapper type %s\n", this.GetType().FullName, className);
                Sharpen.Runtime.PrintStackTrace(e);
            }
            catch (MemberAccessException)
            {
                System.Console.Error.Printf("%s: Unable to access mapper type %s\n", this.GetType().FullName, className);
            }
            return(m);
        }
Example #6
0
        private static IDictionary <string, FieldInfo> FillOptionsImpl(object[] instances, Type[] classes, Properties options, bool ensureAllOptions, bool isBootstrap)
        {
            // Print usage, if applicable
            if (!isBootstrap)
            {
                if (Sharpen.Runtime.EqualsIgnoreCase("true", options.GetProperty("usage", "false")) || Sharpen.Runtime.EqualsIgnoreCase("true", options.GetProperty("help", "false")))
                {
                    ICollection <Type> allClasses = new HashSet <Type>();
                    Java.Util.Collections.AddAll(allClasses, classes);
                    if (instances != null)
                    {
                        foreach (object o in instances)
                        {
                            allClasses.Add(o.GetType());
                        }
                    }
                    System.Console.Error.WriteLine(Usage(Sharpen.Collections.ToArray(allClasses, new Type[0])));
                    System.Environment.Exit(0);
                }
            }
            //--Create Class->Object Mapping
            IDictionary <Type, object> class2object = new Dictionary <Type, object>();

            if (instances != null)
            {
                for (int i = 0; i < classes.Length; ++i)
                {
                    System.Diagnostics.Debug.Assert(instances[i].GetType() == classes[i]);
                    class2object[classes[i]] = instances[i];
                    Type mySuper = instances[i].GetType().BaseType;
                    while (mySuper != null && !mySuper.Equals(typeof(object)))
                    {
                        if (!class2object.Contains(mySuper))
                        {
                            class2object[mySuper] = instances[i];
                        }
                        mySuper = mySuper.BaseType;
                    }
                }
            }
            //--Get Fillable Options
            IDictionary <string, FieldInfo>          canFill  = new Dictionary <string, FieldInfo>();
            IDictionary <string, Pair <bool, bool> > required = new Dictionary <string, Pair <bool, bool> >();
            /* <exists, is_set> */
            IDictionary <string, string> interner = new Dictionary <string, string>();

            foreach (Type c in classes)
            {
                FieldInfo[] fields;
                try
                {
                    fields = ScrapeFields(c);
                }
                catch (Exception e)
                {
                    Redwood.Util.Debug("Could not check fields for class: " + c.FullName + "  (caused by " + e.GetType() + ": " + e.Message + ')');
                    continue;
                }
                bool someOptionFilled = false;
                bool someOptionFound  = false;
                foreach (FieldInfo f in fields)
                {
                    ArgumentParser.Option o = f.GetAnnotation <ArgumentParser.Option>();
                    if (o != null)
                    {
                        someOptionFound = true;
                        //(check if field is static)
                        if ((f.GetModifiers() & Modifier.Static) == 0 && instances == null)
                        {
                            continue;
                        }
                        someOptionFilled = true;
                        //(required marker)
                        Pair <bool, bool> mark = Pair.MakePair(false, false);
                        if (o.Required())
                        {
                            mark = Pair.MakePair(true, false);
                        }
                        //(add main name)
                        string name = o.Name().ToLower();
                        if (name.IsEmpty())
                        {
                            name = f.Name.ToLower();
                        }
                        if (canFill.Contains(name))
                        {
                            string name1 = canFill[name].DeclaringType.GetCanonicalName() + '.' + canFill[name].Name;
                            string name2 = f.DeclaringType.GetCanonicalName() + '.' + f.Name;
                            if (!name1.Equals(name2))
                            {
                                Redwood.Util.RuntimeException("Multiple declarations of option " + name + ": " + name1 + " and " + name2);
                            }
                            else
                            {
                                Redwood.Util.Err("Class is in classpath multiple times: " + canFill[name].DeclaringType.GetCanonicalName());
                            }
                        }
                        canFill[name]  = f;
                        required[name] = mark;
                        interner[name] = name;
                        //(add alternate names)
                        if (!o.Alt().IsEmpty())
                        {
                            foreach (string alt in o.Alt().Split(" *, *"))
                            {
                                alt = alt.ToLower();
                                if (canFill.Contains(alt) && !alt.Equals(name))
                                {
                                    throw new ArgumentException("Multiple declarations of option " + alt + ": " + canFill[alt] + " and " + f);
                                }
                                canFill[alt] = f;
                                if (mark.first)
                                {
                                    required[alt] = mark;
                                }
                                interner[alt] = name;
                            }
                        }
                    }
                }
                //(check to ensure that something got filled, if any @Option annotation was found)
                if (someOptionFound && !someOptionFilled)
                {
                    Redwood.Util.Warn("found @Option annotations in class " + c + ", but didn't set any of them (all options were instance variables and no instance given?)");
                }
            }
            //--Fill Options
            foreach (KeyValuePair <object, object> entry in options)
            {
                string rawKeyStr = entry.Key.ToString();
                string key       = rawKeyStr.ToLower();
                // (get values)
                string value = entry.Value.ToString();
                System.Diagnostics.Debug.Assert(value != null);
                FieldInfo target = canFill[key];
                // (mark required option as fulfilled)
                Pair <bool, bool> mark = required[key];
                if (mark != null && mark.first)
                {
                    required[key] = Pair.MakePair(true, true);
                }
                // (fill the field)
                if (target != null)
                {
                    // (case: declared option)
                    FillField(class2object[target.DeclaringType], target, value);
                }
                else
                {
                    if (ensureAllOptions)
                    {
                        // (case: undeclared option)
                        // split the key
                        int lastDotIndex = rawKeyStr.LastIndexOf('.');
                        if (lastDotIndex < 0)
                        {
                            Redwood.Util.Err("Unrecognized option: " + key);
                            continue;
                        }
                        if (!rawKeyStr.StartsWith("log."))
                        {
                            // ignore Redwood options
                            string className = Sharpen.Runtime.Substring(rawKeyStr, 0, lastDotIndex);
                            // get the class
                            Type clazz = null;
                            try
                            {
                                clazz = ClassLoader.GetSystemClassLoader().LoadClass(className);
                            }
                            catch (Exception)
                            {
                                Redwood.Util.Err("Could not set option: " + entry.Key + "; either the option is mistyped, not defined, or the class " + className + " does not exist.");
                            }
                            // get the field
                            if (clazz != null)
                            {
                                string fieldName = Sharpen.Runtime.Substring(rawKeyStr, lastDotIndex + 1);
                                try
                                {
                                    target = clazz.GetField(fieldName);
                                }
                                catch (Exception)
                                {
                                    Redwood.Util.Err("Could not set option: " + entry.Key + "; no such field: " + fieldName + " in class: " + className);
                                }
                                if (target != null)
                                {
                                    Redwood.Util.Log("option overrides " + target + " to '" + value + '\'');
                                    FillField(class2object[target.DeclaringType], target, value);
                                }
                                else
                                {
                                    Redwood.Util.Err("Could not set option: " + entry.Key + "; no such field: " + fieldName + " in class: " + className);
                                }
                            }
                        }
                    }
                }
            }
            //--Ensure Required
            bool good = true;

            foreach (KeyValuePair <string, Pair <bool, bool> > entry_1 in required)
            {
                string            key  = entry_1.Key;
                Pair <bool, bool> mark = entry_1.Value;
                if (mark.first && !mark.second)
                {
                    Redwood.Util.Err("Missing required option: " + interner[key] + "   <in class: " + canFill[key].DeclaringType + '>');
                    required[key] = Pair.MakePair(true, true);
                    //don't duplicate error messages
                    good = false;
                }
            }
            if (!good)
            {
                throw new Exception("Specified properties are not parsable or not valid!");
            }
            //System.exit(1);
            return(canFill);
        }
Example #7
0
        private static Type[] GetVisibleClasses()
        {
            //--Variables
            IList <Type> classes = new List <Type>();
            // (get classpath)
            string pathSep = Runtime.GetProperty("path.separator");

            string[] cp = Runtime.GetProperties().GetProperty("java.class.path", null).Split(pathSep);
            // --Fill Options
            // (get classes)
            foreach (string entry in cp)
            {
                Redwood.Util.Log("Checking cp " + entry);
                //(should skip?)
                if (entry.Equals(".") || entry.Trim().IsEmpty())
                {
                    continue;
                }
                //(no, don't skip)
                File f = new File(entry);
                if (f.IsDirectory())
                {
                    // --Case: Files
                    try
                    {
                        using (IDirectoryStream <IPath> stream = Files.NewDirectoryStream(f.ToPath(), "*.class"))
                        {
                            foreach (IPath p in stream)
                            {
                                //(get the associated class)
                                Type clazz = FilePathToClass(entry, p.ToString());
                                if (clazz != null)
                                {
                                    //(add the class if it's valid)
                                    classes.Add(clazz);
                                }
                            }
                        }
                    }
                    catch (IOException ioe)
                    {
                        Redwood.Util.Error(ioe);
                    }
                }
                else
                {
                    //noinspection StatementWithEmptyBody
                    if (!IsIgnored(entry))
                    {
                        // --Case: Jar
                        try
                        {
                            using (JarFile jar = new JarFile(f))
                            {
                                IEnumeration <JarEntry> e = ((IEnumeration <JarEntry>)jar.Entries());
                                while (e.MoveNext())
                                {
                                    //(for each jar file element)
                                    JarEntry jarEntry = e.Current;
                                    string   clazz    = jarEntry.GetName();
                                    if (clazz.Matches(".*class$"))
                                    {
                                        //(if it's a class)
                                        clazz = Sharpen.Runtime.Substring(clazz, 0, clazz.Length - 6).ReplaceAll("/", ".");
                                        //(add it)
                                        try
                                        {
                                            classes.Add(Sharpen.Runtime.GetType(clazz, false, ClassLoader.GetSystemClassLoader()));
                                        }
                                        catch (TypeLoadException)
                                        {
                                            Redwood.Util.Warn("Could not load class in jar: " + f + " at path: " + clazz);
                                        }
                                        catch (NoClassDefFoundError)
                                        {
                                            Redwood.Util.Debug("Could not scan class: " + clazz + " (in jar: " + f + ')');
                                        }
                                    }
                                }
                            }
                        }
                        catch (IOException)
                        {
                            Redwood.Util.Warn("Could not open jar file: " + f + "(are you sure the file exists?)");
                        }
                    }
                }
            }
            //case: ignored jar
            return(Sharpen.Collections.ToArray(classes, new Type[classes.Count]));
        }