Exemplo n.º 1
0
  /** Determine whether the current user has Windows administrator privileges. */
  public static boolean isWinAdmin() {
    if (!isWinPlatform()) return false;
    //    for (String group : new com.sun.security.auth.module.NTSystem().getGroupIDs()) {
    //      if (group.equals("S-1-5-32-544")) return true; // "S-1-5-32-544" is a well-known
    // security identifier in Windows. If the current user has it then he/she/it is an
    // administrator.
    //    }
    //    return false;

    try {
      Class<?> ntsys = Class.forName("com.sun.security.auth.module.NTSystem");
      if (ntsys != null) {
        Object groupObj =
            SystemUtils.invoke(
                ntsys.newInstance(), ntsys.getDeclaredMethod("getGroupIDs"), (Object[]) null);
        if (groupObj instanceof String[]) {
          for (String group : (String[]) groupObj) {
            if (group.equals("S-1-5-32-544"))
              return true; // "S-1-5-32-544" is a well-known security identifier in Windows. If the
                           // current user has it then he/she/it is an administrator.
          }
        }
      }
    } catch (ReflectiveOperationException e) {
      System.err.println(e);
    }
    return false;
  }
Exemplo n.º 2
0
 static void javac(String... args) throws Exception {
   Class c = Class.forName("pl.wcislo.sbql4j.tools.javac.Main", true, cl);
   int status =
       (Integer)
           c.getMethod("compile", new Class[] {String[].class})
               .invoke(c.newInstance(), new Object[] {args});
   if (status != 0) throw new Exception("javac failed: status=" + status);
 }
 @SuppressWarnings("unchecked")
 public void addDefaultValue(String className, JSONObject oper) throws Exception {
   ObjectMapper defaultValueMapper = ObjectMapperFactory.getOperatorValueSerializer();
   Class<? extends Operator> clazz = (Class<? extends Operator>) classLoader.loadClass(className);
   if (clazz != null) {
     Operator operIns = clazz.newInstance();
     String s = defaultValueMapper.writeValueAsString(operIns);
     oper.put("defaultValue", new JSONObject(s).get(className));
   }
 }
 private static ITransportFactory getTransportFactory(String transportFactory) {
   try {
     Class<?> factory = Class.forName(transportFactory);
     if (!ITransportFactory.class.isAssignableFrom(factory))
       throw new IllegalArgumentException(
           String.format(
               "transport factory '%s' " + "not derived from ITransportFactory",
               transportFactory));
     return (ITransportFactory) factory.newInstance();
   } catch (Exception e) {
     throw new IllegalArgumentException(
         String.format("Cannot create a transport factory '%s'.", transportFactory), e);
   }
 }
  private void initDriverList() {
    try {
      Thread thread = Thread.currentThread();
      ClassLoader loader = thread.getContextClassLoader();

      Enumeration iter = loader.getResources("META-INF/services/java.sql.Driver");
      while (iter.hasMoreElements()) {
        URL url = (URL) iter.nextElement();

        ReadStream is = null;
        try {
          is = Vfs.lookup(url.toString()).openRead();

          String filename;

          while ((filename = is.readLine()) != null) {
            int p = filename.indexOf('#');

            if (p >= 0) filename = filename.substring(0, p);

            filename = filename.trim();
            if (filename.length() == 0) continue;

            try {
              Class cl = Class.forName(filename, false, loader);
              Driver driver = null;

              if (Driver.class.isAssignableFrom(cl)) driver = (Driver) cl.newInstance();

              if (driver != null) {
                log.fine(L.l("DatabaseManager adding driver '{0}'", driver.getClass().getName()));

                _driverList.add(driver);
              }
            } catch (Exception e) {
              log.log(Level.FINE, e.toString(), e);
            }
          }
        } catch (Exception e) {
          log.log(Level.FINE, e.toString(), e);
        } finally {
          if (is != null) is.close();
        }
      }
    } catch (Exception e) {
      log.log(Level.FINE, e.toString(), e);
    }
  }
Exemplo n.º 6
0
  public static PiHelper load_pi_helper(
      PiHelper pi_helper_cache, ConditionalDistribution pxu, Distribution[] pi_messages)
      throws Exception {
    if (pi_messages.length == 0) return new TrivialPiHelper();

    Vector seq = new Vector();
    seq.addElement(pxu.getClass());
    for (int i = 0; i < pi_messages.length; i++) seq.addElement(pi_messages[i].getClass());

    if (pi_helper_cache != null
        && MatchClassPattern.matches(pi_helper_cache.description(), seq, new int[1], new int[1]))
      return pi_helper_cache;

    Class c = find_helper_class(seq, "pi");
    return (PiHelper) c.newInstance();
  }
Exemplo n.º 7
0
  /**
   * If CS throws an exception it handled and transalated to a Openfire exception if possible. This
   * is done using <code>exceptionMap</code> that has a mapping from CS to OF. If no mapping is
   * found then it tries to instantiete the original exception. If this fails it throws a <code>
   * Exception</code> with the message of the CS exception.
   *
   * @param response the response from CS to check if it is an exception message.
   * @throws Exception if the response is an exception message.
   */
  private void checkFault(Element response) throws Exception {
    Node node = response.selectSingleNode("ns1:faultstring");
    if (node != null) {
      String exceptionText = node.getText();

      // Text accepted samples:
      // 'java.lang.Exception: Exception message'
      // 'java.lang.Exception'

      // Get the exception class and message if any
      int index = exceptionText.indexOf(":");
      String className;
      String message;
      // If there is no message, save the class only
      if (index == -1) {
        className = exceptionText;
        message = null;
      } else {
        // Else save both
        className = exceptionText.substring(0, index);
        message = exceptionText.substring(index + 2);
      }

      // Map the exception to a Openfire one, if possible
      if (exceptionMap.containsKey(className)) {
        className = exceptionMap.get(className);
      }

      // Tries to create an instance with the message
      Exception exception;
      try {
        Class exceptionClass = Class.forName(className);
        if (message == null) {
          exception = (Exception) exceptionClass.newInstance();
        } else {
          Constructor constructor = exceptionClass.getConstructor(String.class);
          exception = (Exception) constructor.newInstance(message);
        }
      } catch (Exception e) {
        // failed to create an specific exception, creating a standard one.
        exception = new Exception(exceptionText);
      }

      throw exception;
    }
  }
Exemplo n.º 8
0
 public void setProperty(String prop, String value) {
   if (PORT.equals(prop)) {
     setPort(value);
   } else if (HANDLER.equals(prop)) {
     try {
       Class chC = Class.forName(value);
       con = (TcpConnectionHandler) chC.newInstance();
     } catch (Exception ex) {
       ex.printStackTrace();
     }
   } else if (INET.equals(prop)) {
     try {
       address = InetAddress.getByName(value);
     } catch (Exception ex) {
     }
   }
 }
Exemplo n.º 9
0
  public JxpSource getJxpServlet(String name) {
    JxpSource source = _httpServlets.get(name);
    if (source != null) return source;

    try {
      Class c = Class.forName(name);
      Object n = c.newInstance();
      if (!(n instanceof HttpServlet))
        throw new RuntimeException("class [" + name + "] is not a HttpServlet");

      HttpServlet servlet = (HttpServlet) n;
      servlet.init(createServletConfig(name));
      source = new ServletSource(servlet);
      _httpServlets.put(name, source);
      return source;
    } catch (Exception e) {
      throw new RuntimeException("can't load [" + name + "]", e);
    }
  }
 /**
  * Method to create concrete instances of this abstract class. Instances are dynamically loaded.
  * Instances's names are obtained by concatenating a prefix, either "Light", "Regular", or
  * "Gourmet", with the suffix "PizzaFactory".
  *
  * @param style An integer representing the style of pizzas to create, e.g., 0 stands for
  *     "Light". @ @return a concrete pizza factory
  */
 static AbstractPizzaFactory getFactory(int style)
     throws ClassNotFoundException, InstantiationException, IllegalAccessException,
         IllegalArgumentException, MalformedURLException {
   if (0 <= style && style <= prefix.length - 1) {
     // Alternative #1 - load from current directory
     // AbstractPizzaFactory apf =
     //    (AbstractPizzaFactory) Class.forName
     //        (prefix [style] + suffix).newInstance ();
     // Alternative 2 - load from URL (including JAR file)
     // It looks like only the protocol "file:" is
     // required to load files from the execution directory
     URL[] classPath = {new URL("file:")};
     URLClassLoader classLoader = new URLClassLoader(classPath);
     String name = prefix[style] + suffix;
     Class someClass = classLoader.loadClass(name);
     AbstractPizzaFactory apf = (AbstractPizzaFactory) someClass.newInstance();
     // end of alternatives
     return apf;
   } else throw new IllegalArgumentException();
 }
  public void activateOptions() {
    InetAddress addr = null;

    try {
      Class c = Class.forName(decoder);
      Object o = c.newInstance();

      if (o instanceof Decoder) {
        this.decoderImpl = (Decoder) o;
      }
    } catch (ClassNotFoundException cnfe) {
      getLogger().warn("Unable to find decoder", cnfe);
    } catch (IllegalAccessException iae) {
      getLogger().warn("Could not construct decoder", iae);
    } catch (InstantiationException ie) {
      getLogger().warn("Could not construct decoder", ie);
    }

    try {
      addr = InetAddress.getByName(address);
    } catch (UnknownHostException uhe) {
      uhe.printStackTrace();
    }

    try {
      active = true;
      socket = new MulticastSocket(port);
      socket.joinGroup(addr);
      receiverThread = new MulticastReceiverThread();
      receiverThread.start();
      handlerThread = new MulticastHandlerThread();
      handlerThread.start();
      if (advertiseViaMulticastDNS) {
        zeroConf = new ZeroConfSupport(ZONE, port, getName());
        zeroConf.advertise();
      }

    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }
Exemplo n.º 12
0
 // Preprocess a FileObject.
 private boolean preprocess(FileObject fileObject) {
   if (TrialConfig.getPreprocessorEnabled().equals("yes")) {
     // Load the preprocessor class specified in the TrialConfig.
     // Reload each time in case the class changes behind our back.
     PreprocessorAdapter ppa = null;
     String className = TrialConfig.getPreprocessorClassName();
     try {
       Class theClass = Class.forName(className);
       ppa = (PreprocessorAdapter) theClass.newInstance();
       if (fileObject instanceof DicomObject) return ppa.process((DicomObject) fileObject);
       if (fileObject instanceof XmlObject) return ppa.process((XmlObject) fileObject);
       if (fileObject instanceof ZipObject) return ppa.process((ZipObject) fileObject);
       return ppa.process(fileObject);
     } catch (Exception ex) {
       Log.message("Exception while loading or running the preprocessor: " + className);
       logger.warn("Exception while loading or running the preprocessor: " + className);
       return false;
     }
   }
   return true;
 }
Exemplo n.º 13
0
 public static final ProtocolProvider<?> getProvider(int version, boolean x) {
   for (ProtocolProvider<?> provider : providers)
     if (version == provider.getSupportedVersion() && (x == provider instanceof ProtocolProviderX))
       return provider;
   try {
     String className =
         ProtocolProvider.class.getPackage().getName()
             + ".v"
             + version
             + (x ? "x" : "")
             + ".Protocol"
             + version
             + (x ? "X" : "")
             + "$Provider";
     @SuppressWarnings("rawtypes")
     Class<? extends ProtocolProvider> providerClass =
         Class.forName(className).asSubclass(ProtocolProvider.class);
     return providerClass.newInstance();
   } catch (Throwable exception) {
     return null;
   }
 }
Exemplo n.º 14
0
  private void initHttps() {
    // if(!setHttps) {
    String pkgs = SAAJUtil.getSystemProperty("java.protocol.handler.pkgs");
    log.log(Level.FINE, "SAAJ0053.p2p.providers", new String[] {pkgs});

    if (pkgs == null || pkgs.indexOf(SSL_PKG) < 0) {
      if (pkgs == null) pkgs = SSL_PKG;
      else pkgs = pkgs + "|" + SSL_PKG;
      System.setProperty("java.protocol.handler.pkgs", pkgs);
      log.log(Level.FINE, "SAAJ0054.p2p.set.providers", new String[] {pkgs});
      try {
        Class c = Class.forName(SSL_PROVIDER);
        Provider p = (Provider) c.newInstance();
        Security.addProvider(p);
        log.log(Level.FINE, "SAAJ0055.p2p.added.ssl.provider", new String[] {SSL_PROVIDER});
        // System.out.println("Added SSL_PROVIDER " + SSL_PROVIDER);
        // setHttps = true;
      } catch (Exception ex) {
      }
    }
    // }
  }
Exemplo n.º 15
0
  private static LaunchablePlugin[] findLaunchablePlugins(LoggerChannelListener listener) {
    // CAREFUL - this is called BEFORE any AZ initialisation has been performed and must
    // therefore NOT use anything that relies on this (such as logging, debug....)

    List res = new ArrayList();

    File app_dir = getApplicationFile("plugins");

    if (!(app_dir.exists()) && app_dir.isDirectory()) {

      listener.messageLogged(LoggerChannel.LT_ERROR, "Application dir '" + app_dir + "' not found");

      return (new LaunchablePlugin[0]);
    }

    File[] plugins = app_dir.listFiles();

    if (plugins == null || plugins.length == 0) {

      listener.messageLogged(LoggerChannel.LT_ERROR, "Application dir '" + app_dir + "' empty");

      return (new LaunchablePlugin[0]);
    }

    for (int i = 0; i < plugins.length; i++) {

      File plugin_dir = plugins[i];

      if (!plugin_dir.isDirectory()) {

        continue;
      }

      try {

        ClassLoader classLoader = PluginLauncherImpl.class.getClassLoader();

        ClassLoader root_cl = classLoader;

        File[] contents = plugin_dir.listFiles();

        if (contents == null || contents.length == 0) {

          continue;
        }

        // take only the highest version numbers of jars that look versioned

        String[] plugin_version = {null};
        String[] plugin_id = {null};

        contents = getHighestJarVersions(contents, plugin_version, plugin_id, true);

        for (int j = 0; j < contents.length; j++) {

          classLoader = addFileToClassPath(root_cl, classLoader, contents[j]);
        }

        Properties props = new Properties();

        File properties_file = new File(plugin_dir, "plugin.properties");

        // if properties file exists on its own then override any properties file
        // potentially held within a jar

        if (properties_file.exists()) {

          FileInputStream fis = null;

          try {
            fis = new FileInputStream(properties_file);

            props.load(fis);

          } finally {

            if (fis != null) {

              fis.close();
            }
          }
        } else {

          if (classLoader instanceof URLClassLoader) {

            URLClassLoader current = (URLClassLoader) classLoader;

            URL url = current.findResource("plugin.properties");

            if (url != null) {

              props.load(url.openStream());
            }
          }
        }

        String plugin_class = (String) props.get("plugin.class");

        // don't support multiple launchable plugins

        if (plugin_class == null || plugin_class.indexOf(';') != -1) {

          continue;
        }

        Class c = classLoader.loadClass(plugin_class);

        Plugin plugin = (Plugin) c.newInstance();

        if (plugin instanceof LaunchablePlugin) {

          preloaded_plugins.put(plugin_class, plugin);

          res.add(plugin);
        }
      } catch (Throwable e) {

        listener.messageLogged("Load of plugin in '" + plugin_dir + "' fails", e);
      }
    }

    LaunchablePlugin[] x = new LaunchablePlugin[res.size()];

    res.toArray(x);

    return (x);
  }