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.
      }
    }
  }
Example #2
0
  public boolean isAvailable() {
    try {
      // Diagnostic was introduced in the Java 1.6 compiler
      Class<?> diagnostic = Class.forName("javax.tools.Diagnostic");
      diagnostic.getMethod("getKind");
      // javax.lang.model.SourceVersion.RELEASE_7 field introduced in Java 7
      Class<?> sourceVersion = Class.forName("javax.lang.model.SourceVersion");
      sourceVersion.getField("RELEASE_7"); // only exists in Java 7 and later releases
      // javax.tools.Diagnostic and javax.lang.model.SourceVersion are also found in rt.jar;
      // to test if tools.jar is available, we need to test for a class only found in tools.jar
      Class.forName("com.sun.tools.javac.main.JavaCompiler");

      // This is the class that javax.tools.ToolProvider.getSystemJavaCompiler() uses
      // We create an instance of that class directly, bypassing ToolProvider, because ToolProvider
      // returns null
      // if DrJava is started with just the JRE, instead of with the JDK, even if tools.jar is later
      // made available
      // to the class loader.
      JavaCompiler compiler =
          (JavaCompiler) (Class.forName("com.sun.tools.javac.api.JavacTool").newInstance());

      return (compiler != null);
    } catch (Exception e) {
      return false;
    } catch (LinkageError e) {
      return false;
    }
  }
  /* goodB2G2() - use badsource and goodsink by reversing statements in second if  */
  private void goodB2G2() throws Throwable {
    String data;
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (IO.static_t) {
      Logger log_bad = Logger.getLogger("local-logger");
      data = ""; /* init data */
      File f = new File("C:\\data.txt");
      BufferedReader buffread = null;
      FileReader fread = null;
      try {
        /* read string from file into data */
        fread = new FileReader(f);
        buffread = new BufferedReader(fread);
        data = buffread.readLine(); // This will be reading the first "line" of the file, which
        // could be very long if there are little or no newlines in the file\
      } catch (IOException ioe) {
        log_bad.warning("Error with stream reading");
      } catch (NumberFormatException nfe) {
        log_bad.warning("Error with number parsing");
      } finally {
        /* clean up stream reading objects */
        try {
          if (buffread != null) {
            buffread.close();
          }
        } catch (IOException ioe) {
          log_bad.warning("Error closing buffread");
        } finally {
          try {
            if (fread != null) {
              fread.close();
            }
          } catch (IOException ioe) {
            log_bad.warning("Error closing fread");
          }
        }
      }
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      data = "Testing.test";
    }
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (IO.static_t) {
      if (!data.equals("Testing.test")
          && /* FIX: classname must be one of 2 values */ !data.equals("Test.test")) {
        return;
      }
      Class<?> c = Class.forName(data);
      Object instance = c.newInstance();
      IO.writeLine(instance.toString());
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      Class<?> c = Class.forName(data); /* FLAW: loading arbitrary class */
      Object instance = c.newInstance();

      IO.writeLine(instance.toString());
    }
  }
  /**
   * Applies the fix for OpenSSL PRNG having low entropy. Does nothing if the fix is not needed.
   *
   * @throws SecurityException if the fix is needed but could not be applied.
   */
  private static void applyOpenSSLFix() throws SecurityException {
    if ((Build.VERSION.SDK_INT < VERSION_CODE_JELLY_BEAN)
        || (Build.VERSION.SDK_INT > VERSION_CODE_JELLY_BEAN_MR2)) {
      // No need to apply the fix
      return;
    }

    try {
      // Mix in the device- and invocation-specific seed.
      Class.forName("org.apache.harmony.xnet.provider.jsse.NativeCrypto")
          .getMethod("RAND_seed", byte[].class)
          .invoke(null, generateSeed());

      // Mix output of Linux PRNG into OpenSSL's PRNG
      int bytesRead =
          (Integer)
              Class.forName("org.apache.harmony.xnet.provider.jsse.NativeCrypto")
                  .getMethod("RAND_load_file", String.class, long.class)
                  .invoke(null, "/dev/urandom", 1024);
      if (bytesRead != 1024) {
        throw new IOException("Unexpected number of bytes read from Linux PRNG: " + bytesRead);
      }
    } catch (Exception e) {
      throw new SecurityException("Failed to seed OpenSSL PRNG", e);
    }
  }
Example #5
0
  void enableLionFS() {
    try {
      String version = System.getProperty("os.version");
      String[] tokens = version.split("\\.");
      int major = Integer.parseInt(tokens[0]), minor = 0;
      if (tokens.length > 1) minor = Integer.parseInt(tokens[1]);
      if (major < 10 || (major == 10 && minor < 7))
        throw new Exception("Operating system version is " + version);

      Class fsuClass = Class.forName("com.apple.eawt.FullScreenUtilities");
      Class argClasses[] = new Class[] {Window.class, Boolean.TYPE};
      Method setWindowCanFullScreen = fsuClass.getMethod("setWindowCanFullScreen", argClasses);
      setWindowCanFullScreen.invoke(fsuClass, this, true);

      Class fsListenerClass = Class.forName("com.apple.eawt.FullScreenListener");
      InvocationHandler fsHandler = new MyInvocationHandler(cc);
      Object proxy =
          Proxy.newProxyInstance(
              fsListenerClass.getClassLoader(), new Class[] {fsListenerClass}, fsHandler);
      argClasses = new Class[] {Window.class, fsListenerClass};
      Method addFullScreenListenerTo = fsuClass.getMethod("addFullScreenListenerTo", argClasses);
      addFullScreenListenerTo.invoke(fsuClass, this, proxy);

      canDoLionFS = true;
    } catch (Exception e) {
      vlog.debug("Could not enable OS X 10.7+ full-screen mode:");
      vlog.debug("  " + e.toString());
    }
  }
Example #6
0
  static {
    try {
      defineClass =
          ClassLoader.class.getDeclaredMethod(
              "defineClass", String.class, byte[].class, Integer.TYPE, Integer.TYPE);
      defineClass.setAccessible(true);
      resolveClass = ClassLoader.class.getDeclaredMethod("resolveClass", Class.class);
      resolveClass.setAccessible(true);

      classDir =
          new File(
              System.getProperty("lambda.weaving.debug.classes.dir", "target/generated-classes/"));
      debug("writing generated classes to " + classDir.getAbsolutePath());

    } catch (Exception e) {
      throw uncheck(e);
    }

    try {
      String[] realAsmPackageNotToBeChangedByJarJar = {"org.objectweb."};

      Class<?> checkClassAdapter =
          Class.forName(realAsmPackageNotToBeChangedByJarJar[0] + "asm.util.CheckClassAdapter");
      Class<?> classReader =
          Class.forName(realAsmPackageNotToBeChangedByJarJar[0] + "asm.ClassReader");

      verify = checkClassAdapter.getMethod("verify", classReader, Boolean.TYPE, PrintWriter.class);
      classReaderConstructor = classReader.getConstructor(InputStream.class);

      debug("asm-util is avaialbe, will pre-verify generated classes");

    } catch (Exception ignore) {
      debug("asm-util NOT avaialbe, will not be able to pre-verify generated classes");
    }
  }
  /**
   * Gets an InputStream that uses the snappy codec and wraps the supplied base input stream.
   *
   * @param the buffer size for the codec to use (in bytes)
   * @param in the base input stream to wrap around
   * @return an InputStream that uses the Snappy codec
   * @throws Exception if snappy is not available or an error occurs during reflection
   */
  public static InputStream getSnappyInputStream(int bufferSize, InputStream in) throws Exception {
    if (!isHadoopSnappyAvailable()) {
      throw new Exception("Hadoop-snappy does not seem to be available");
    }

    Object snappyCodec = Class.forName(SNAPPY_CODEC_CLASS).newInstance();
    Class confClass =
        Class.forName("org.apache.hadoop.conf.Configuration").newInstance().getClass();
    Class[] paramClass = new Class[1];
    paramClass[0] = confClass;

    Object newConf = Class.forName("org.apache.hadoop.conf.Configuration").newInstance();

    Object[] args = new Object[2];
    args[0] = IO_COMPRESSION_CODEC_SNAPPY_BUFFERSIZE_KEY;
    args[1] = "" + bufferSize;
    Method cm = confClass.getMethod("set", new Class[] {String.class, String.class});
    cm.invoke(newConf, args);

    Method m = snappyCodec.getClass().getMethod("setConf", paramClass);
    m.invoke(snappyCodec, newConf);

    paramClass[0] = Class.forName("java.io.InputStream");
    m = snappyCodec.getClass().getMethod("createInputStream", paramClass);
    Object result = m.invoke(snappyCodec, in);

    return (InputStream) result;
  }
  /* goodG2B2() - use goodsource and badsink by reversing statements in first if */
  private void goodG2B2() throws Throwable {
    String data;
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (5 == 5) {
      data = "Testing.test";
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      Logger log_bad = Logger.getLogger("local-logger");

      data = ""; /* init data */

      /* read user input from console with readLine*/
      BufferedReader buffread = null;
      InputStreamReader instrread = null;
      try {
        instrread = new InputStreamReader(System.in);
        buffread = new BufferedReader(instrread);
        data = buffread.readLine();
      } catch (IOException ioe) {
        log_bad.warning("Error with stream reading");
      } finally {
        /* clean up stream reading objects */
        try {
          if (buffread != null) {
            buffread.close();
          }
        } catch (IOException ioe) {
          log_bad.warning("Error closing buffread");
        } finally {
          try {
            if (instrread != null) {
              instrread.close();
            }
          } catch (IOException ioe) {
            log_bad.warning("Error closing instrread");
          }
        }
      }
    }
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (5 == 5) {
      Class<?> c = Class.forName(data); /* FLAW: loading arbitrary class */
      Object instance = c.newInstance();
      IO.writeLine(instance.toString());
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      if (!data.equals("Testing.test")
          && /* FIX: classname must be one of 2 values */ !data.equals("Test.test")) {
        return;
      }

      Class<?> c = Class.forName(data);
      Object instance = c.newInstance();

      IO.writeLine(instance.toString());
    }
  }
Example #9
0
  public PersistManager(URI iceRoot) {
    I = new Persist[MAX_BACKENDS];
    stats = new PersistStatsEntry[MAX_BACKENDS];
    for (int i = 0; i < stats.length; i++) {
      stats[i] = new PersistStatsEntry();
    }

    if (iceRoot == null) {
      Log.err("ice_root must be specified.  Exiting.");
      H2O.exit(1);
    }

    Persist ice = null;
    boolean windowsPath = iceRoot.toString().matches("^[a-zA-Z]:.*");

    if (windowsPath) {
      ice = new PersistFS(new File(iceRoot.toString()));
    } else if ((iceRoot.getScheme() == null) || Schemes.FILE.equals(iceRoot.getScheme())) {
      ice = new PersistFS(new File(iceRoot.getPath()));
    } else if (Schemes.HDFS.equals(iceRoot.getScheme())) {
      Log.err("HDFS ice_root not yet supported.  Exiting.");
      H2O.exit(1);

      // I am not sure anyone actually ever does this.
      // H2O on Hadoop launches use local disk for ice root.
      // This has a chance to work, but turn if off until it gets tested.
      //
      //      try {
      //        Class klass = Class.forName("water.persist.PersistHdfs");
      //        java.lang.reflect.Constructor constructor = klass.getConstructor(new
      // Class[]{URI.class});
      //        ice = (Persist) constructor.newInstance(iceRoot);
      //      } catch (Exception e) {
      //        Log.err("Could not initialize HDFS");
      //        throw new RuntimeException(e);
      //      }
    }

    I[Value.ICE] = ice;
    I[Value.NFS] = new PersistNFS();

    try {
      Class klass = Class.forName("water.persist.PersistHdfs");
      java.lang.reflect.Constructor constructor = klass.getConstructor();
      I[Value.HDFS] = (Persist) constructor.newInstance();
      Log.info("HDFS subsystem successfully initialized");
    } catch (Throwable ignore) {
      Log.info("HDFS subsystem not available");
    }

    try {
      Class klass = Class.forName("water.persist.PersistS3");
      java.lang.reflect.Constructor constructor = klass.getConstructor();
      I[Value.S3] = (Persist) constructor.newInstance();
      Log.info("S3 subsystem successfully initialized");
    } catch (Throwable ignore) {
      Log.info("S3 subsystem not available");
    }
  }
  public void bad() throws Throwable {
    String data;
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (private_final_five == 5) {
      Logger log_bad = Logger.getLogger("local-logger");
      data = ""; /* init data */
      URLConnection conn = (new URL("http://www.example.org/")).openConnection();
      BufferedReader buffread = null;
      InputStreamReader instrread = null;
      try {
        /* read input from URLConnection */
        instrread = new InputStreamReader(conn.getInputStream());
        buffread = new BufferedReader(instrread);
        data = buffread.readLine(); // This will be reading the first "line" of the response body,
        // which could be very long if there are no newlines in the HTML
      } catch (IOException ioe) {
        log_bad.warning("Error with stream reading");
      } finally {
        /* clean up stream reading objects */
        try {
          if (buffread != null) {
            buffread.close();
          }
        } catch (IOException ioe) {
          log_bad.warning("Error closing buffread");
        } finally {
          try {
            if (instrread != null) {
              instrread.close();
            }
          } catch (IOException ioe) {
            log_bad.warning("Error closing instrread");
          }
        }
      }
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      data = "Testing.test";
    }
    /* INCIDENTAL: CWE 571 Statement is Always True */
    if (private_final_five == 5) {
      Class<?> c = Class.forName(data); /* FLAW: loading arbitrary class */
      Object instance = c.newInstance();
      IO.writeLine(instance.toString());
    } else {
      /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */

      if (!data.equals("Testing.test")
          && /* FIX: classname must be one of 2 values */ !data.equals("Test.test")) {
        return;
      }

      Class<?> c = Class.forName(data);
      Object instance = c.newInstance();

      IO.writeLine(instance.toString());
    }
  }
  public static void main(String[] args) {
    try {
      String sp1 = "/home/caoc/alterAligner/SCORE_DROP/all_mtx/" + args[0] + ".mtx";
      String sp2 = "/home/caoc/alterAligner/SCORE_DROP/all_mtx/" + args[1] + ".mtx";
      System.out.println(args[0]);
      //                                String sp1 =
      // "/home/caoc/alterAligner/SCORE_DROP/all_fasta/" + args[0] ;
      //                               String sp2 =  "/home/caoc/alterAligner/SCORE_DROP/all_fasta/"
      // + args[1] ;

      Class parserClass = Class.forName("alterAligner.sequenceProfileParsers.PSSMParser");
      Class scoreFunctionClass =
          Class.forName("alterAligner.scoreFunctionStrategies.WeightedSumStrategy");
      SequenceProfileParser aParser = (SequenceProfileParser) parserClass.newInstance();
      ScoreFunctionStrategy aStrategy = (ScoreFunctionStrategy) scoreFunctionClass.newInstance();
      Aligner aligner = new Aligner(aStrategy, (float) 10, (float) 0.5);
      SequenceProfile seqPro1 = aParser.parse(new File(sp1));
      SequenceProfile seqPro2 = aParser.parse(new File(sp2));
      Alignment alignment = aligner.smithWatermanAlign(seqPro1, seqPro2);
      BufferedWriter writer =
          new BufferedWriter(
              new FileWriter(
                  "/home/caoc/alterAligner/SCORE_DROP/all_ws_alignment/"
                      + args[0]
                      + "__"
                      + args[1]
                      + ".ws.fasta"));
      writer.append(
          ">"
              + alignment.getName1()
              + "\t"
              + alignment.getStart1()
              + "\t"
              + alignment.getEnd1()
              + "\n");
      writer.append(alignment.getSequence1AsString() + "\n");
      writer.append(
          ">"
              + alignment.getName2()
              + "\t"
              + alignment.getStart2()
              + "\t"
              + alignment.getEnd2()
              + "\n");
      writer.append(alignment.getSequence2AsString() + "\n");
      writer.close();
    } catch (FileNotFoundException e) {
      System.out.println("Failed to open file! " + e.getMessage());
    } catch (IOException e) {
      System.out.println("Failed to read the file! " + e.getMessage());
    } catch (ClassNotFoundException e) {
      System.out.println("Failed to find the class! " + e.getMessage());
    } catch (Exception e) {
      System.out.println("Failed to due to do alignment! " + e.getMessage());
      e.printStackTrace();
    }
  }
 public void initStax(String infName, String outfName) {
   try {
     initStax(
         (XMLInputFactory) Class.forName(infName).newInstance(),
         (XMLOutputFactory) Class.forName(outfName).newInstance());
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
Example #13
0
  /**
   * Attempts to play this AudioClip, the method returns immediately and never throws exceptions. If
   * playing fails, it fails silently.
   */
  public synchronized void play() {
    if (successfulPlayer != null) {
      try {
        successfulPlayer.play(this);
        return;
      } catch (Exception e) {
      } // Ignore any exceptions
    }

    String cmdSpecifiedPlayer;
    try {
      cmdSpecifiedPlayer = System.getProperty("free.util.audio.player");
    } catch (SecurityException e) {
      cmdSpecifiedPlayer = null;
    }

    if (cmdSpecifiedPlayer != null) {
      try {
        Class playerClass = Class.forName(cmdSpecifiedPlayer);
        AudioPlayer player = (AudioPlayer) playerClass.newInstance();
        if (!player.isSupported()) {
          System.err.println(
              cmdSpecifiedPlayer + " is not supported on your system - audio disabled.");
          successfulPlayer = new NullAudioPlayer();
          return;
        }

        player.play(this);
        successfulPlayer = player;
      } catch (Throwable e) {
        if (e instanceof ThreadDeath) throw (ThreadDeath) e;
        System.err.println(cmdSpecifiedPlayer + " failed - audio disabled.");
        successfulPlayer = new NullAudioPlayer();
      }
    } else {
      for (int i = 0; i < PLAYER_CLASSNAMES.length; i++) {
        String classname = PLAYER_CLASSNAMES[i];
        try {
          Class playerClass = Class.forName(classname);
          AudioPlayer player = (AudioPlayer) playerClass.newInstance();
          if (!player.isSupported()) continue;
          player.play(this);
          System.err.println("Will now use " + classname + " to play audio clips.");
          successfulPlayer = player;
        } catch (Throwable e) {
          if (e instanceof ThreadDeath) throw (ThreadDeath) e;
          continue;
        }
        break;
      }

      if (successfulPlayer == null) {
        System.err.println("All supported players failed - audio disabled");
        successfulPlayer = new NullAudioPlayer();
      }
    }
  }
Example #14
0
 /**
  * Returns either Consumes.class or ConsumeMime.class (old version)
  *
  * @return
  */
 public static Class<?> getConsumesClass() {
   try {
     return Class.forName("javax.ws.rs.Consumes");
   } catch (ClassNotFoundException e) {
     try {
       return Class.forName("javax.ws.rs.ConsumeMime");
     } catch (ClassNotFoundException e1) {
       throw new RuntimeException(e1);
     }
   }
 }
Example #15
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.classes);

    setcc();

    Log.e("n", " CC Activity Started");
    try {
      Class<?> strictModeClass =
          Class.forName(
              "android.os.StrictMode", true, Thread.currentThread().getContextClassLoader());

      Class<?> threadPolicyClass =
          Class.forName(
              "android.os.StrictMode$ThreadPolicy",
              true,
              Thread.currentThread().getContextClassLoader());

      Class<?> threadPolicyBuilderClass =
          Class.forName(
              "android.os.StrictMode$ThreadPolicy$Builder",
              true,
              Thread.currentThread().getContextClassLoader());

      Method setThreadPolicyMethod =
          strictModeClass.getMethod("setThreadPolicy", threadPolicyClass);

      Method detectAllMethod = threadPolicyBuilderClass.getMethod("detectAll");
      Method penaltyMethod = threadPolicyBuilderClass.getMethod("penaltyLog");
      Method buildMethod = threadPolicyBuilderClass.getMethod("build");

      Constructor<?> threadPolicyBuilderConstructor = threadPolicyBuilderClass.getConstructor();
      Object threadPolicyBuilderObject = threadPolicyBuilderConstructor.newInstance();

      Object obj = detectAllMethod.invoke(threadPolicyBuilderObject);

      obj = penaltyMethod.invoke(obj);
      Object threadPolicyObject = buildMethod.invoke(obj);
      setThreadPolicyMethod.invoke(strictModeClass, threadPolicyObject);

    } catch (Exception ex) {
      Log.w("n", "Strict not enabled....");
    }

    final Button button = (Button) findViewById(R.id.ccbutton1);
    button.setOnClickListener(
        new View.OnClickListener() {
          public void onClick(View v) {
            setcc();
          }
        });
  }
Example #16
0
 /**
  * This method will be used to support different constructor signatures. The default is
  *
  * <pre>XXXOutputStream( OutputStream slave )</pre>
  *
  * if level is -1 or
  *
  * <pre>XXXOutputStream( OutputStream slave, int level )</pre>
  *
  * if level is other than -1.<br>
  * If the signature of the used output stream will be other, overload this method in the derived
  * pack compressor class.
  *
  * @param slave output stream to be used as slave
  * @return the constructor params as Object [] to be used as construction of the constructor via
  *     reflection
  * @throws Exception
  */
 protected Object[] resolveConstructorParams(OutputStream slave) throws Exception {
   if (level == -1) {
     paramsClasses = new Class[1];
     paramsClasses[0] = Class.forName("java.io.OutputStream");
     Object[] params = {slave};
     return (params);
   }
   paramsClasses = new Class[2];
   paramsClasses[0] = Class.forName("java.io.OutputStream");
   paramsClasses[1] = java.lang.Integer.TYPE;
   Object[] params = {slave, level};
   return (params);
 }
Example #17
0
 private static void initialize_evaluator() throws Exception {
   if (Config.bsp_mode)
     Evaluator.evaluator = (Evaluator) Class.forName("org.apache.mrql.BSPEvaluator").newInstance();
   else if (Config.spark_mode)
     Evaluator.evaluator =
         (Evaluator) Class.forName("org.apache.mrql.SparkEvaluator").newInstance();
   else if (Config.flink_mode)
     Evaluator.evaluator =
         (Evaluator) Class.forName("org.apache.mrql.FlinkEvaluator").newInstance();
   else // when Config.map_reduce_mode but also the default
   Evaluator.evaluator =
         (Evaluator) Class.forName("org.apache.mrql.MapReduceEvaluator").newInstance();
 }
Example #18
0
 /**
  * Override coverts old class names into new class names to preserve compatibility with
  * pre-Apache namespaces.
  */
 @Override
 protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException {
   ObjectStreamClass read = super.readClassDescriptor();
   if (read.getName().startsWith("com.fs.pxe.")) {
     return ObjectStreamClass.lookup(
         Class.forName(read.getName().replace("com.fs.pxe.", "org.apache.ode.")));
   }
   if (read.getName().startsWith("com.fs.utils.")) {
     return ObjectStreamClass.lookup(
         Class.forName(read.getName().replace("com.fs.utils.", "org.apache.ode.utils.")));
   }
   return read;
 }
  /** Performs tasks to resolve the lazy instantiation. */
  private synchronized void init() {
    if (!initialized) {
      // Mimic the behavior of XStream's JVM class
      String vendor = System.getProperty("java.vm.vendor");
      float version = 1.3f;
      try {
        version = Float.parseFloat(System.getProperty("java.version").substring(0, 3));
      } catch (NumberFormatException nfe) {
        // Keep the default
      }
      Class unsafe = null;
      try {
        unsafe = Class.forName("sun.misc.Unsafe", false, getClass().getClassLoader());
      } catch (ClassNotFoundException cnfe) {
        // Keep the default
      }
      ReflectionProvider reflectionProvider = null;
      if ((vendor.contains("Sun")
              || vendor.contains("Oracle")
              || vendor.contains("Apple")
              || vendor.contains("Hewlett-Packard")
              || vendor.contains("IBM")
              || vendor.contains("Blackdown"))
          && version >= 1.4f
          && unsafe != null) {
        try {
          reflectionProvider =
              (ReflectionProvider)
                  Class.forName(
                          "com.thoughtworks.xstream.converters.reflection.Sun14ReflectionProvider",
                          false,
                          getClass().getClassLoader())
                      .newInstance();
        } catch (InstantiationException ie) {
          reflectionProvider = new PureJavaReflectionProvider();
        } catch (IllegalAccessException iae) {
          reflectionProvider = new PureJavaReflectionProvider();
        } catch (ClassNotFoundException cnfe) {
          reflectionProvider = new PureJavaReflectionProvider();
        }
      } else {
        reflectionProvider = new PureJavaReflectionProvider();
      }
      HierarchicalStreamDriver driver = new DomDriver();

      xs = new XStream(reflectionProvider, driver);
      xs.setMarshallingStrategy(new LockssReferenceByXPathMarshallingStrategy(lockssContext));
      xs.registerConverter(new LockssDateConverter());
      initialized = true;
    }
  }
Example #20
0
 private static void netxsurgery() throws Exception {
   /* Force off NetX codebase classloading. */
   Class<?> nxc;
   try {
     nxc = Class.forName("net.sourceforge.jnlp.runtime.JNLPClassLoader");
   } catch (ClassNotFoundException e1) {
     try {
       nxc = Class.forName("netx.jnlp.runtime.JNLPClassLoader");
     } catch (ClassNotFoundException e2) {
       throw (new Exception("No known NetX on classpath"));
     }
   }
   ClassLoader cl = MainFrame.class.getClassLoader();
   if (!nxc.isInstance(cl)) {
     throw (new Exception("Not running from a NetX classloader"));
   }
   Field cblf, lf;
   try {
     cblf = nxc.getDeclaredField("codeBaseLoader");
     lf = nxc.getDeclaredField("loaders");
   } catch (NoSuchFieldException e) {
     throw (new Exception("JNLPClassLoader does not conform to its known structure"));
   }
   cblf.setAccessible(true);
   lf.setAccessible(true);
   Set<Object> loaders = new HashSet<Object>();
   Stack<Object> open = new Stack<Object>();
   open.push(cl);
   while (!open.empty()) {
     Object cur = open.pop();
     if (loaders.contains(cur)) continue;
     loaders.add(cur);
     Object curl;
     try {
       curl = lf.get(cur);
     } catch (IllegalAccessException e) {
       throw (new Exception("Reflection accessibility not available even though set"));
     }
     for (int i = 0; i < Array.getLength(curl); i++) {
       Object other = Array.get(curl, i);
       if (nxc.isInstance(other)) open.push(other);
     }
   }
   for (Object cur : loaders) {
     try {
       cblf.set(cur, null);
     } catch (IllegalAccessException e) {
       throw (new Exception("Reflection accessibility not available even though set"));
     }
   }
 }
Example #21
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);
  }
  private static Future<Void> startDeletionThread(@NotNull final File... tempFiles) {
    final RunnableFuture<Void> deleteFilesTask =
        new FutureTask<Void>(
            new Runnable() {
              @Override
              public void run() {
                final Thread currentThread = Thread.currentThread();
                final int priority = currentThread.getPriority();
                currentThread.setPriority(Thread.MIN_PRIORITY);
                try {
                  for (File tempFile : tempFiles) {
                    delete(tempFile);
                  }
                } finally {
                  currentThread.setPriority(priority);
                }
              }
            },
            null);

    try {
      // attempt to execute on pooled thread
      final Class<?> aClass = Class.forName("com.intellij.openapi.application.ApplicationManager");
      final Method getApplicationMethod = aClass.getMethod("getApplication");
      final Object application = getApplicationMethod.invoke(null);
      final Method executeOnPooledThreadMethod =
          application.getClass().getMethod("executeOnPooledThread", Runnable.class);
      executeOnPooledThreadMethod.invoke(application, deleteFilesTask);
    } catch (Exception ignored) {
      new Thread(deleteFilesTask, "File deletion thread").start();
    }
    return deleteFilesTask;
  }
 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();
     }
   }
 }
 /**
  * Force initialization of the static members. As of Java 5, referencing a class doesn't force it
  * to initialize. Since this class requires that the classes be initialized to declare their
  * comparators, we force that initialization to happen.
  *
  * @param cls the class to initialize
  */
 private static void forceInit(Class<?> cls) {
   try {
     Class.forName(cls.getName(), true, cls.getClassLoader());
   } catch (ClassNotFoundException e) {
     throw new IllegalArgumentException("Can't initialize class " + cls, e);
   }
 }
  /**
   * If createNode cannot locate the correct class to instantiate the node this method is called and
   * will instantiate the node using it's Java3D Core superclass
   */
  private SceneGraphObject createNodeFromSuper(
      String className, Class[] parameterTypes, Object[] parameters) {
    SceneGraphObject ret;

    String tmp = this.getClass().getName();
    String superClass = tmp.substring(tmp.indexOf("state") + 6, tmp.length() - 5);
    Constructor constructor;

    try {
      Class state = Class.forName(superClass);
      constructor = state.getConstructor(parameterTypes);
      ret = (SceneGraphObject) constructor.newInstance(parameters);
    } catch (ClassNotFoundException e1) {
      throw new SGIORuntimeException("No State class for " + superClass);
    } catch (IllegalAccessException e2) {
      throw new SGIORuntimeException("Broken State class for " + className + " - IllegalAccess");
    } catch (InstantiationException e3) {
      throw new SGIORuntimeException("Broken State class for " + className);
    } catch (java.lang.reflect.InvocationTargetException e4) {
      throw new SGIORuntimeException("InvocationTargetException for " + className);
    } catch (NoSuchMethodException e5) {
      for (int i = 0; i < parameterTypes.length; i++)
        System.err.println(parameterTypes[i].getName());
      System.err.println("------");
      throw new SGIORuntimeException("Invalid constructor for " + className);
    }

    return ret;
  }
  /**
   * Create a Java3D node which does not have a default constructor
   *
   * <p>parameterTypes must contain the classes required by the constructor, use Integer.TYPE,
   * Float.TYPE etc to specifiy primitive types
   *
   * <p>paramters should contain the list of parameters for the constructor, primitive types should
   * be wrapped in the appropriate class (ie Integer, Float )
   */
  private SceneGraphObject createNode(
      String className, Class[] parameterTypes, Object[] parameters) {
    SceneGraphObject ret;
    Constructor constructor;

    try {
      Class state = Class.forName(className);
      constructor = state.getConstructor(parameterTypes);
      ret = (SceneGraphObject) constructor.newInstance(parameters);
    } catch (ClassNotFoundException e1) {
      if (control.useSuperClassIfNoChildClass())
        ret = createNodeFromSuper(className, parameterTypes, parameters);
      else throw new SGIORuntimeException("No State class for " + className);
    } catch (IllegalAccessException e2) {
      throw new SGIORuntimeException("Broken State class for " + className + " - IllegalAccess");
    } catch (InstantiationException e3) {
      throw new SGIORuntimeException("Broken State class for " + className);
    } catch (java.lang.reflect.InvocationTargetException e4) {
      throw new SGIORuntimeException("InvocationTargetException for " + className);
    } catch (NoSuchMethodException e5) {
      for (int i = 0; i < parameterTypes.length; i++)
        System.err.println(parameterTypes[i].getName());
      System.err.println("------");
      throw new SGIORuntimeException("Invalid constructor for " + className);
    }

    return ret;
  }
Example #27
0
 public ClassifierSet() {
   try {
     classifierClass = Class.forName("weka.classifiers." + classifierType);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  /** JNDI object factory so the proxy can be used as a resource. */
  public Object getObjectInstance(
      Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
    Reference ref = (Reference) obj;

    String api = null;
    String url = null;
    String user = null;
    String password = null;

    for (int i = 0; i < ref.size(); i++) {
      RefAddr addr = ref.get(i);

      String type = addr.getType();
      String value = (String) addr.getContent();

      if (type.equals("type")) api = value;
      else if (type.equals("url")) url = value;
      else if (type.equals("user")) setUser(value);
      else if (type.equals("password")) setPassword(value);
    }

    if (url == null) throw new NamingException("`url' must be configured for HessianProxyFactory.");
    // XXX: could use meta protocol to grab this
    if (api == null)
      throw new NamingException("`type' must be configured for HessianProxyFactory.");

    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    Class apiClass = Class.forName(api, false, loader);

    return create(apiClass, url);
  }
Example #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"));
      }
    }
  }
Example #30
-1
  public List<Empleado> getAllEmpleados() {
    List ll = new LinkedList();
    Statement st;
    ResultSet rs;
    String url = "jdbc:mysql://localhost:3306/food";
    String user = "******";
    String pass = "******";
    String driver = "com.mysql.jdbc.Driver";

    try (Connection connection = DriverManager.getConnection(url, user, pass)) {
      Class.forName(driver);
      st = connection.createStatement();
      String recordQuery = ("Select * from empleados");
      rs = st.executeQuery(recordQuery);
      while (rs.next()) {
        Integer id = rs.getInt("idEmpleados");
        String name = rs.getString("Nombre");
        String telf = rs.getString("Telefono");
        ll.add(new Empleado(id, name, telf));
        /// System.out.println(id +","+ name +","+ apellido +","+ cedula +","+ telf +"
        // "+direccion+"");
      }

    } catch (ClassNotFoundException | SQLException ex) {
      Logger.getLogger(MenuEmpleados.class.getName()).log(Level.SEVERE, null, ex);
    }
    return ll;
  }