public void changeLAF(int iLAFIndex) {
    try {
      // Change LAF
      if (iLAFIndex >= marrLaf.length) iLAFIndex = marrLaf.length - 1;
      UIManager.setLookAndFeel(
          (LookAndFeel) Class.forName(marrLaf[iLAFIndex].getClassName()).newInstance());

      // Update UI
      ((JMenuItem) mvtLAFItem.elementAt(iLAFIndex)).setSelected(true);
      SwingUtilities.updateComponentTreeUI(this);
      SwingUtilities.updateComponentTreeUI(mnuMain);
      WindowManager.updateLookAndField();

      // Store config
      try {
        Hashtable prt = Global.loadHashtable(Global.FILE_CONFIG);
        prt.put("LAF", String.valueOf(iLAFIndex));
        Global.storeHashtable(prt, Global.FILE_CONFIG);
      } catch (Exception e) {
      }
    } catch (Exception e) {
      e.printStackTrace();
      MessageBox.showMessageDialog(this, e, Global.APP_NAME, MessageBox.ERROR_MESSAGE);
    }
  }
  @SuppressWarnings({"fallthrough"})
  private static Permission getPermission(String type, String name, String actions)
      throws ClassNotFoundException, InstantiationException, IllegalAccessException,
          NoSuchMethodException, InvocationTargetException {
    Class<?> clazz = Class.forName(type);
    int nArgs = actions != null ? 2 : name != null ? 1 : 0;

    switch (nArgs) {
      case 0:
        try {
          return (Permission) clazz.getConstructor().newInstance();
        } catch (NoSuchMethodException e) {
        }

      case 1:
        try {
          return (Permission) clazz.getConstructor(ARGS_NAME).newInstance(name);
        } catch (NoSuchMethodException e) {
        }

      case 2:
        return (Permission) clazz.getConstructor(ARGS_NAME_ACTIONS).newInstance(name, actions);
    }

    assert false;
    return null;
  }
Esempio n. 3
0
  public static void invokeSetMethod(Object obj, String prop, String value)
      throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    Class cl = obj.getClass();
    // change first letter to uppercase
    String setMeth = "set" + prop.substring(0, 1).toUpperCase() + prop.substring(1);

    // try string method
    try {
      Class[] cldef = {String.class};
      Method meth = cl.getMethod(setMeth, cldef);
      Object[] params = {value};
      meth.invoke(obj, params);
      return;
    } catch (NoSuchMethodException ex) {
      try {
        // try int method
        Class[] cldef = {Integer.TYPE};
        Method meth = cl.getMethod(setMeth, cldef);
        Object[] params = {Integer.valueOf(value)};
        meth.invoke(obj, params);
        return;
      } catch (NoSuchMethodException nsmex) {
        // try boolean method
        Class[] cldef = {Boolean.TYPE};
        Method meth = cl.getMethod(setMeth, cldef);
        Object[] params = {Boolean.valueOf(value)};
        meth.invoke(obj, params);
        return;
      }
    }
  }
Esempio n. 4
0
 Object createGuiElement(Class cls, EntityPlayer player, World world, int x, int y, int z) {
   try {
     try {
       if (debugGui)
         System.out.printf(
             "BaseMod.createGuiElement: Invoking create method of %s for %s in %s\n",
             cls, player, world);
       return cls.getMethod(
               "create", EntityPlayer.class, World.class, int.class, int.class, int.class)
           .invoke(null, player, world, x, y, z);
     } catch (NoSuchMethodException e) {
       if (debugGui)
         System.out.printf("BaseMod.createGuiElement: Invoking constructor of %s\n", cls);
       return cls.getConstructor(EntityPlayer.class, World.class, int.class, int.class, int.class)
           .newInstance(player, world, x, y, z);
     }
   } catch (Exception e) {
     Throwable cause = e.getCause();
     System.out.printf("BaseMod.createGuiElement: %s: %s\n", e, cause);
     if (cause != null) cause.printStackTrace();
     else e.printStackTrace();
     // throw new RuntimeException(e);
     return null;
   }
 }
  /** 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;
  }
 public void loadMacros() {
   File f = new File(System.getProperty("user.dir"));
   String[] files = f.list();
   for (int i = 0; i < files.length; i++) {
     try {
       if (files[i].startsWith("macro_")
           && files[i].endsWith(".class")
           && files[i].indexOf('$') == -1) {
         System.out.println(files[i]);
         Class clazz = Class.forName(files[i].substring(0, files[i].length() - ".class".length()));
         Macro macro =
             (Macro)
                 clazz
                     .getConstructor(new Class[] {mudclient_Debug.class})
                     .newInstance(new Object[] {inner});
         String[] commands = macro.getCommands();
         for (int j = 0; j < commands.length; j++) {
           System.out.println("command registered:" + commands[j]);
           mudclient_Debug.macros.put(commands[j], macro);
         }
       }
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
Esempio n. 7
0
  private int findfd(Object fdObj) throws Exception {
    Class cl;
    Field f;
    Object val, implVal;

    if ((fdObj instanceof java.net.Socket) || (fdObj instanceof java.net.ServerSocket)) {
      cl = fdObj.getClass();
      f = cl.getDeclaredField("impl");
      f.setAccessible(true);
      val = f.get(fdObj);
      cl = f.getType();
      f = cl.getDeclaredField("fd");
      f.setAccessible(true);
      implVal = f.get(val);
      cl = f.getType();
      f = cl.getDeclaredField("fd");
      f.setAccessible(true);
      return ((Integer) f.get(implVal)).intValue();
    } else if (fdObj instanceof java.io.FileDescriptor) {
      cl = fdObj.getClass();
      f = cl.getDeclaredField("fd");
      f.setAccessible(true);
      return ((Integer) f.get(fdObj)).intValue();
    } else {
      throw new IllegalArgumentException("Illegal Object type.");
    }
  }
Esempio n. 8
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);
 }
Esempio n. 9
0
 private KeyStore createKeyStore(@Nullable String path)
     throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
   String keyStoreType = KeyStore.getDefaultType();
   char[] defaultPassword = "******".toCharArray();
   if (path != null) {
     // If the user provided path, only try to load the keystore at that path.
     KeyStore keyStore = KeyStore.getInstance(keyStoreType);
     FileInputStream is = new FileInputStream(path);
     keyStore.load(is, defaultPassword);
     return keyStore;
   }
   try {
     // Check if we are on Android.
     Class version = Class.forName("android.os.Build$VERSION");
     // Build.VERSION_CODES.ICE_CREAM_SANDWICH is 14.
     if (version.getDeclaredField("SDK_INT").getInt(version) >= 14) {
       // After ICS, Android provided this nice method for loading the keystore,
       // so we don't have to specify the location explicitly.
       KeyStore keystore = KeyStore.getInstance("AndroidCAStore");
       keystore.load(null, null);
       return keystore;
     } else {
       keyStoreType = "BKS";
       path =
           System.getProperty("java.home")
               + "/etc/security/cacerts.bks".replace('/', File.separatorChar);
     }
   } catch (ClassNotFoundException e) {
     // NOP. android.os.Build is not present, so we are not on Android. Fall through.
   } catch (NoSuchFieldException e) {
     throw new RuntimeException(e); // Should never happen.
   } catch (IllegalAccessException e) {
     throw new RuntimeException(e); // Should never happen.
   }
   if (path == null) {
     path = System.getProperty("javax.net.ssl.trustStore");
   }
   if (path == null) {
     // Try this default system location for Linux/Windows/OSX.
     path =
         System.getProperty("java.home")
             + "/lib/security/cacerts".replace('/', File.separatorChar);
   }
   try {
     KeyStore keyStore = KeyStore.getInstance(keyStoreType);
     FileInputStream is = new FileInputStream(path);
     keyStore.load(is, defaultPassword);
     return keyStore;
   } catch (FileNotFoundException e) {
     // If we failed to find a system trust store, load our own fallback trust store. This can fail
     // on Android
     // but we should never reach it there.
     KeyStore keyStore = KeyStore.getInstance("JKS");
     InputStream is = getClass().getResourceAsStream("cacerts");
     keyStore.load(is, defaultPassword);
     return keyStore;
   }
 }
Esempio n. 10
0
  /**
   * Given a map between a string and an object of unknown type, attempt to retrieve what value is
   * mapped to from the specified string and validate that the actual type matches the specified
   * class.
   *
   * @return Null if the types do not match, or the value
   */
  private static Object validateAndGet(Map<String, Object> m, String s, Class<?> c)
      throws MissingMappingException, UnexpectedTypeException {
    Object o = m.get(s);
    if (o == null) throw new MissingMappingException(s);

    if (!c.isAssignableFrom(o.getClass()))
      throw new UnexpectedTypeException(s, c.toString(), o.getClass().toString());
    else return o;
  }
Esempio n. 11
0
 @Override
 public <T> T narrow(Class<T> target) {
   if (target == Socket.class) {
     return target.cast(socket);
   } else if (target == TimeStampStream.class) {
     return target.cast(buffOut);
   }
   return super.narrow(target);
 }
Esempio n. 12
0
 static void jar(String... args) throws Exception {
   Class c = Class.forName("sun.tools.jar.Main", true, cl);
   Object instance =
       c.getConstructor(new Class[] {PrintStream.class, PrintStream.class, String.class})
           .newInstance(System.out, System.err, "jar");
   boolean result =
       (Boolean)
           c.getMethod("run", new Class[] {String[].class}).invoke(instance, new Object[] {args});
   if (!result) throw new Exception("jar failed");
 }
 @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));
   }
 }
Esempio n. 14
0
 // Use reflection to get version since early versions
 // of ImageJ do not have the IJ.getVersion() method.
 String version() {
   String version = "";
   try {
     Class ijClass = ImageJ.class;
     Field field = ijClass.getField("VERSION");
     version = (String) field.get(ijClass);
   } catch (Exception ex) {
   }
   return version;
 }
Esempio n. 15
0
  public static Object loadFrame(
      JopSession session, String className, String instance, boolean scrollbar)
      throws ClassNotFoundException {

    if (className.indexOf(".pwg") != -1) {
      GrowFrame frame =
          new GrowFrame(
              className, session.getGdh(), instance, new GrowFrameCb(session), session.getRoot());
      frame.validate();
      frame.setVisible(true);
    } else {
      Object frame;
      if (instance == null) instance = "";

      JopLog.log(
          "JopSpider.loadFrame: Loading frame \"" + className + "\" instance \"" + instance + "\"");
      try {
        Class clazz = Class.forName(className);
        try {
          Class argTypeList[] =
              new Class[] {session.getClass(), instance.getClass(), boolean.class};
          Object argList[] = new Object[] {session, instance, new Boolean(scrollbar)};
          System.out.println("JopSpider.loadFrame getConstructor");
          Constructor constructor = clazz.getConstructor(argTypeList);

          try {
            frame = constructor.newInstance(argList);
          } catch (Exception e) {
            System.out.println(
                "Class instanciation error: "
                    + className
                    + " "
                    + e.getMessage()
                    + " "
                    + constructor);
            return null;
          }
          // frame = clazz.newInstance();
          JopLog.log("JopSpider.loadFrame openFrame");
          openFrame(frame);
          return frame;
        } catch (NoSuchMethodException e) {
          System.out.println("NoSuchMethodException: Unable to get frame constructor " + className);
        } catch (Exception e) {
          System.out.println(
              "Exception: Unable to get frame class " + className + " " + e.getMessage());
        }
      } catch (ClassNotFoundException e) {
        System.out.println("Class not found: " + className);
        throw new ClassNotFoundException();
      }
      return null;
    }
    return null;
  }
  static {
    if (!Boolean.getBoolean(GridSystemProperties.GG_JETTY_LOG_NO_OVERRIDE)) {
      String ctgrJetty = "org.eclipse.jetty"; // WARN for this category.
      String ctgrJettyUtil = "org.eclipse.jetty.util.log"; // ERROR for this...
      String ctgrJettyUtilComp = "org.eclipse.jetty.util.component"; // ...and this.

      try {
        Class<?> logCls = Class.forName("org.apache.log4j.Logger");

        Object logJetty = logCls.getMethod("getLogger", String.class).invoke(logCls, ctgrJetty);
        Object logJettyUtil =
            logCls.getMethod("getLogger", String.class).invoke(logCls, ctgrJettyUtil);
        Object logJettyUtilComp =
            logCls.getMethod("getLogger", String.class).invoke(logCls, ctgrJettyUtilComp);

        Class<?> lvlCls = Class.forName("org.apache.log4j.Level");

        Object warnLvl = lvlCls.getField("WARN").get(null);
        Object errLvl = lvlCls.getField("ERROR").get(null);

        logJetty.getClass().getMethod("setLevel", lvlCls).invoke(logJetty, warnLvl);
        logJettyUtil.getClass().getMethod("setLevel", lvlCls).invoke(logJetty, errLvl);
        logJettyUtilComp.getClass().getMethod("setLevel", lvlCls).invoke(logJetty, errLvl);
      } catch (Exception ignored) {
        // No-op.
      }
    }
  }
Esempio n. 17
0
 /**
  * Uses reflection to load an implementation of the class. Returns false if it failed for some
  * reason. This allows us to remove implementation classes (for example, to get rid of the
  * dependency on Mozilla for GTK2 users/builds
  */
 private boolean loadEditor(String clazz) {
   try {
     // Don't replace an existing editor
     if (editorPaneImpl != null) return true;
     Class c = Class.forName(clazz);
     editorPaneImpl = (EditorPane) c.getConstructors()[0].newInstance(null);
     return true;
   } catch (Exception e) {
     return false;
   }
 }
Esempio n. 18
0
  /**
   * Returns compact class host.
   *
   * @param obj Object to compact.
   * @return String.
   */
  @Nullable
  public static Object compactObject(Object obj) {
    if (obj == null) return null;

    if (obj instanceof Enum) return obj.toString();

    if (obj instanceof String || obj instanceof Boolean || obj instanceof Number) return obj;

    if (obj instanceof Collection) {
      Collection col = (Collection) obj;

      Object[] res = new Object[col.size()];

      int i = 0;

      for (Object elm : col) res[i++] = compactObject(elm);

      return res;
    }

    if (obj.getClass().isArray()) {
      Class<?> arrType = obj.getClass().getComponentType();

      if (arrType.isPrimitive()) {
        if (obj instanceof boolean[]) return Arrays.toString((boolean[]) obj);
        if (obj instanceof byte[]) return Arrays.toString((byte[]) obj);
        if (obj instanceof short[]) return Arrays.toString((short[]) obj);
        if (obj instanceof int[]) return Arrays.toString((int[]) obj);
        if (obj instanceof long[]) return Arrays.toString((long[]) obj);
        if (obj instanceof float[]) return Arrays.toString((float[]) obj);
        if (obj instanceof double[]) return Arrays.toString((double[]) obj);
      }

      Object[] arr = (Object[]) obj;

      int iMax = arr.length - 1;

      StringBuilder sb = new StringBuilder("[");

      for (int i = 0; i <= iMax; i++) {
        sb.append(compactObject(arr[i]));

        if (i != iMax) sb.append(", ");
      }

      sb.append("]");

      return sb.toString();
    }

    return U.compact(obj.getClass().getName());
  }
  /**
   * Constructs new instance of the specified class.
   *
   * @param exp Expected class for the new instance.
   * @param clsName Class name to create new instance for.
   * @param <T> Expected class type for the new instance.
   * @return New instance of specified class.
   * @throws GridClientException If loading failed.
   */
  private static <T> T newInstance(Class<T> exp, String clsName) throws GridClientException {
    Object obj;

    try {
      obj = Class.forName(clsName).newInstance();
    }
    // Catch all for convenience.
    catch (Exception e) {
      throw new GridClientException("Failed to create class instance: " + clsName, e);
    }

    return exp.cast(obj);
  }
Esempio n. 20
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 + "]";
  }
Esempio n. 21
0
  public static void main(String[] args) throws Exception {
    Class thisClass = MethodResultTest.class;
    Class exoticClass = Exotic.class;
    String exoticClassName = Exotic.class.getName();
    ClassLoader testClassLoader = thisClass.getClassLoader();
    if (!(testClassLoader instanceof URLClassLoader)) {
      System.out.println("TEST INVALID: Not loaded by a " + "URLClassLoader: " + testClassLoader);
      System.exit(1);
    }

    URLClassLoader tcl = (URLClassLoader) testClassLoader;
    URL[] urls = tcl.getURLs();
    ClassLoader shadowLoader =
        new ShadowLoader(
            urls,
            testClassLoader,
            new String[] {
              exoticClassName, ExoticMBeanInfo.class.getName(), ExoticException.class.getName()
            });
    Class cl = shadowLoader.loadClass(exoticClassName);
    if (cl == exoticClass) {
      System.out.println(
          "TEST INVALID: Shadow class loader loaded " + "same class as test class loader");
      System.exit(1);
    }
    Thread.currentThread().setContextClassLoader(shadowLoader);

    ObjectName on = new ObjectName("a:b=c");
    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    mbs.createMBean(Thing.class.getName(), on);

    final String[] protos = {"rmi", "iiop", "jmxmp"};

    boolean ok = true;
    for (int i = 0; i < protos.length; i++) {
      try {
        ok &= test(protos[i], mbs, on);
        System.out.println();
      } catch (Exception e) {
        System.out.println("TEST FAILED WITH EXCEPTION:");
        e.printStackTrace(System.out);
        ok = false;
      }
    }

    if (ok) System.out.println("Test passed");
    else {
      System.out.println("TEST FAILED");
      System.exit(1);
    }
  }
Esempio n. 22
0
  public SOAPMessage get(Object endPoint) throws SOAPException {
    if (closed) {
      log.severe("SAAJ0011.p2p.get.already.closed.conn");
      throw new SOAPExceptionImpl("Connection is closed");
    }
    Class urlEndpointClass = null;

    try {
      urlEndpointClass = Class.forName("javax.xml.messaging.URLEndpoint");
    } catch (Exception ex) {
      // Do nothing. URLEndpoint is available only when JAXM is there.
    }

    if (urlEndpointClass != null) {
      if (urlEndpointClass.isInstance(endPoint)) {
        String url = null;

        try {
          Method m = urlEndpointClass.getMethod("getURL", (Class[]) null);
          url = (String) m.invoke(endPoint, (Object[]) null);
        } catch (Exception ex) {
          log.severe("SAAJ0004.p2p.internal.err");
          throw new SOAPExceptionImpl("Internal error: " + ex.getMessage());
        }
        try {
          endPoint = new URL(url);
        } catch (MalformedURLException mex) {
          log.severe("SAAJ0005.p2p.");
          throw new SOAPExceptionImpl("Bad URL: " + mex.getMessage());
        }
      }
    }

    if (endPoint instanceof java.lang.String) {
      try {
        endPoint = new URL((String) endPoint);
      } catch (MalformedURLException mex) {
        log.severe("SAAJ0006.p2p.bad.URL");
        throw new SOAPExceptionImpl("Bad URL: " + mex.getMessage());
      }
    }

    if (endPoint instanceof URL)
      try {
        SOAPMessage response = doGet((URL) endPoint);
        return response;
      } catch (Exception ex) {
        throw new SOAPExceptionImpl(ex);
      }
    else throw new SOAPExceptionImpl("Bad endPoint type " + endPoint);
  }
 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);
   }
 }
Esempio n. 24
0
  /**
   * Fired when a control is clicked. This is the equivalent of
   * ActionListener.actionPerformed(ActionEvent e).
   */
  protected void actionPerformed(GuiButton par1GuiButton) {
    if (par1GuiButton.enabled) {
      if (par1GuiButton.id == 5) {
        if (Minecraft.getOs() == EnumOS.MACOS) {
          try {
            this.mc.getLogAgent().logInfo(this.fileLocation);
            Runtime.getRuntime().exec(new String[] {"/usr/bin/open", this.fileLocation});
            return;
          } catch (IOException var7) {
            var7.printStackTrace();
          }
        } else if (Minecraft.getOs() == EnumOS.WINDOWS) {
          String var2 =
              String.format(
                  "cmd.exe /C start \"Open file\" \"%s\"", new Object[] {this.fileLocation});

          try {
            Runtime.getRuntime().exec(var2);
            return;
          } catch (IOException var6) {
            var6.printStackTrace();
          }
        }

        boolean var8 = false;

        try {
          Class var3 = Class.forName("java.awt.Desktop");
          Object var4 =
              var3.getMethod("getDesktop", new Class[0]).invoke((Object) null, new Object[0]);
          var3.getMethod("browse", new Class[] {URI.class})
              .invoke(
                  var4,
                  new Object[] {(new File(Minecraft.getMinecraftDir(), "texturepacks")).toURI()});
        } catch (Throwable var5) {
          var5.printStackTrace();
          var8 = true;
        }

        if (var8) {
          this.mc.getLogAgent().logInfo("Opening via system class!");
          Sys.openURL("file://" + this.fileLocation);
        }
      } else if (par1GuiButton.id == 6) {
        this.mc.displayGuiScreen(this.guiScreen);
      } else {
        this.guiTexturePackSlot.actionPerformed(par1GuiButton);
      }
    }
  }
 public void loadAndRun(String className) throws Throwable {
   // System.out.println("Loading " + className + "...");
   Class testClass = new VerifyClassLoader().loadClass(className);
   // System.out.println("Loaded " + className);
   try {
     Method main = testClass.getMethod("main", new Class[] {String[].class});
     // System.out.println("Running " + className);
     main.invoke(null, new Object[] {new String[] {}});
     // System.out.println("Finished running " + className);
   } catch (NoSuchMethodException e) {
     return;
   } catch (InvocationTargetException e) {
     throw e.getTargetException();
   }
 }
  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);
    }
  }
Esempio n. 27
0
  @Before
  public void dbInit() throws Exception {
    String configFileName = System.getProperty("user.home");
    if (System.getProperty("os.name").toLowerCase().indexOf("linux") > -1) {
      configFileName += "/.pokerth/config.xml";
    } else {
      configFileName += "/AppData/Roaming/pokerth/config.xml";
    }
    File file = new File(configFileName);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(file);
    doc.getDocumentElement().normalize();
    Element configNode = (Element) doc.getElementsByTagName("Configuration").item(0);

    Element dbAddressNode = (Element) configNode.getElementsByTagName("DBServerAddress").item(0);
    String dbAddress = dbAddressNode.getAttribute("value");

    Element dbUserNode = (Element) configNode.getElementsByTagName("DBServerUser").item(0);
    String dbUser = dbUserNode.getAttribute("value");

    Element dbPasswordNode = (Element) configNode.getElementsByTagName("DBServerPassword").item(0);
    String dbPassword = dbPasswordNode.getAttribute("value");

    Element dbNameNode = (Element) configNode.getElementsByTagName("DBServerDatabaseName").item(0);
    String dbName = dbNameNode.getAttribute("value");

    final String dbUrl = "jdbc:mysql://" + dbAddress + ":3306/" + dbName;
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    dbConn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
  }
Esempio n. 28
0
  public static void main(String[] args) throws IOException, ClassNotFoundException {
    ServerSocket serverSocket = null;
    boolean listening = true;
    Class.forName("org.sqlite.JDBC");

    try {
      if (args.length == 1) {
        serverSocket = new ServerSocket(Integer.parseInt(args[0]));
        System.out.println(
            "Server up and running with:\nhostname: " + getLocalIpAddress() + "\nport: " + args[0]);
        System.out.println("Waiting to accept client...");
        System.out.println("Remember to setup client hostname");
      } else {
        System.err.println("ERROR: Invalid arguments!");
        System.exit(-1);
      }
    } catch (IOException e) {
      System.err.println("ERROR: Could not listen on port!");
      System.exit(-1);
    }

    while (listening) {
      new ServerHandlerThread(serverSocket.accept()).start();
    }

    serverSocket.close();
  }
Esempio n. 29
0
  private /*synchronized*/ StructureType assignStructureType(String structType)
      throws VisualizerLoadException {

    if (debug) System.out.println("In assignStructureType with " + structType);

    // Handle objects whose constructors require args separately
    if ((structType.toUpperCase().compareTo("BAR") == 0)
        || (structType.toUpperCase().compareTo("SCAT") == 0))
      return (new BarScat(structType.toUpperCase()));
    else if ((structType.toUpperCase().compareTo("GRAPH") == 0)
        || (structType.toUpperCase().compareTo("NETWORK") == 0))
      return (new Graph_Network(structType.toUpperCase()));
    else { // Constructor for object does not require args

      try {
        return ((StructureType)
            ((Class.forName(insure_text_case_correct_for_legacy_scripts(structType)))
                .newInstance()));
      } catch (InstantiationException e) {
        System.out.println(e);
        throw (new VisualizerLoadException(structType + " is invalid structure type"));
      } catch (IllegalAccessException e) {
        System.out.println(e);
        throw (new VisualizerLoadException(structType + " is invalid structure type"));
      } catch (ClassNotFoundException e) {
        System.out.println(e);
        throw (new VisualizerLoadException(structType + " is invalid structure type"));
      }
    }
  }
Esempio n. 30
0
  /**
   * Create a splash screen (borderless graphic for display while other operations are taking
   * place).
   *
   * @param filename a class-relative path to the splash graphic
   * @param callingClass the class to which the graphic filename location is relative
   */
  public SplashScreen(String filename, Class callingClass) {
    super(new Frame());
    URL imageURL = callingClass.getResource(filename);
    image = Toolkit.getDefaultToolkit().createImage(imageURL);
    // Load the image
    MediaTracker mt = new MediaTracker(this);
    mt.addImage(image, 0);
    try {
      mt.waitForID(0);
    } catch (InterruptedException ie) {
    }

    // Center the window on the screen
    int imgWidth = image.getWidth(this);
    int imgHeight = image.getHeight(this);
    setSize(imgWidth, imgHeight);
    Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
    setLocation((screenDim.width - imgWidth) / 2, (screenDim.height - imgHeight) / 2);

    setVisible(true);
    repaint();
    // if on a single processor machine, wait for painting (see Fast Java Splash Screen.pdf)
    if (!EventQueue.isDispatchThread()) {
      synchronized (this) {
        while (!this.paintCalled) {
          try {
            this.wait();
          } catch (InterruptedException e) {
          }
        }
      }
    }
  }