/**
   * Creates a new entity enumeration icon chooser.
   *
   * @param enumeration the enumeration to display in this combo box
   */
  public EnumerationIconChooser(Class<E> enumeration) {
    super();

    this.enumeration = enumeration;

    try {
      this.icons = (ImageIcon[]) enumeration.getMethod("getIcons").invoke(null);
      for (int i = 0; i < icons.length; i++) {
        addItem(icons[i]);
      }
    } catch (NoSuchMethodException ex) {
      System.err.println(
          "The method 'getIcons()' is missing in enumeration " + enumeration.getName());
      ex.printStackTrace();
      System.exit(1);
    } catch (IllegalAccessException ex) {
      System.err.println(
          "Cannot access method 'getIcons()' in enumeration "
              + enumeration.getName()
              + ": ex.getMessage()");
      ex.printStackTrace();
      System.exit(1);
    } catch (InvocationTargetException ex) {
      ex.getCause().printStackTrace();
      System.exit(1);
    }
  }
示例#2
0
  /** Sets up configuration based on params */
  private static boolean setup(Hashtable<String, String> curConf, Configuration argConf) {

    if (argConf.get("file") == null) {
      logger.fatal("Missing file parameter");
      System.exit(1);
    }

    if (argConf.get("hdfs_base_path") == null) {
      logger.fatal("Missing HDFS base path, check gestore-conf.xml");
      System.exit(1);
    }

    if (argConf.get("hdfs_temp_path") == null) {
      logger.fatal("Missing HDFS temp path, check gestore-conf.xml");
      System.exit(1);
    }

    if (argConf.get("local_temp_path") == null) {
      logger.fatal("Missing local temp path, check gestore-conf.xml");
      System.exit(1);
    }

    // Input paramaters
    curConf.put("run_id", argConf.get("run", ""));
    curConf.put("task_id", argConf.get("task", ""));
    curConf.put("file_id", argConf.get("file"));
    curConf.put("local_path", argConf.get("path", ""));
    curConf.put("type", argConf.get("type", "l2r"));
    curConf.put("timestamp_start", argConf.get("timestamp_start", "1"));
    curConf.put(
        "timestamp_stop", argConf.get("timestamp_stop", Integer.toString(Integer.MAX_VALUE)));
    curConf.put("delimiter", argConf.get("regex", "ID=.*"));
    curConf.put("taxon", argConf.get("taxon", "all"));
    curConf.put("intermediate", argConf.get("full_run", "false"));
    curConf.put("quick_add", argConf.get("quick_add", "false"));
    Boolean full_run = curConf.get("intermediate").matches("(?i).*true.*");
    curConf.put("format", argConf.get("format", "unknown"));
    curConf.put("split", argConf.get("split", "1"));
    curConf.put("copy", argConf.get("copy", "true"));

    // Constants
    curConf.put("base_path", argConf.get("hdfs_base_path"));
    curConf.put("temp_path", argConf.get("hdfs_temp_path"));
    curConf.put("local_temp_path", argConf.get("local_temp_path"));
    curConf.put("db_name_files", argConf.get("hbase_file_table"));
    curConf.put("db_name_runs", argConf.get("hbase_run_table"));
    curConf.put("db_name_updates", argConf.get("hbase_db_update_table"));

    // Timestamps
    Date currentTime = new Date();
    Date endDate = new Date(new Long(curConf.get("timestamp_stop")));
    curConf.put("timestamp_real", Long.toString(currentTime.getTime()));

    return true;
  }
示例#3
0
 public static void main(String[] args) {
   try {
     Class cls = new Object() {}.getClass().getEnclosingClass();
     Method m = cls.getMethod(args[0], String[].class);
     m.invoke(null, (Object) Arrays.copyOfRange(args, 1, args.length));
   } catch (Exception e) {
     e.printStackTrace();
     System.exit(1);
   }
   System.exit(0);
 }
 public static void main(String[] args) {
   if (args.length < 1) {
     print(usage);
     System.exit(0);
   }
   int lines = 0;
   try {
     Class<?> c = Class.forName(args[0]);
     Method[] methods = c.getMethods();
     Constructor[] ctors = c.getConstructors();
     if (args.length == 1) {
       for (Method method : methods) print(p.matcher(method.toString()).replaceAll(""));
       for (Constructor ctor : ctors) print(p.matcher(ctor.toString()).replaceAll(""));
       lines = methods.length + ctors.length;
     } else {
       for (Method method : methods)
         if (method.toString().indexOf(args[1]) != -1) {
           print(p.matcher(method.toString()).replaceAll(""));
           lines++;
         }
       for (Constructor ctor : ctors)
         if (ctor.toString().indexOf(args[1]) != -1) {
           print(p.matcher(ctor.toString()).replaceAll(""));
           lines++;
         }
     }
   } catch (ClassNotFoundException e) {
     print("No such class: " + e);
   }
 }
示例#5
0
  /**
   * Write the XML representation of the API to a file.
   *
   * @param root the RootDoc object passed by Javadoc
   * @return true if no problems encountered
   */
  public static boolean writeXML(RootDoc root) {
    String tempFileName = outputFileName;
    if (outputDirectory != null) {
      tempFileName = outputDirectory;
      if (!tempFileName.endsWith(JDiff.DIR_SEP)) tempFileName += JDiff.DIR_SEP;
      tempFileName += outputFileName;
    }

    try {
      FileOutputStream fos = new FileOutputStream(tempFileName);
      outputFile = new PrintWriter(fos);
      System.out.println("JDiff: writing the API to file '" + tempFileName + "'...");
      if (root.specifiedPackages().length != 0 || root.specifiedClasses().length != 0) {
        RootDocToXML apiWriter = new RootDocToXML();
        apiWriter.emitXMLHeader();
        apiWriter.logOptions();
        apiWriter.processPackages(root);
        apiWriter.emitXMLFooter();
      }
      outputFile.close();
    } catch (IOException e) {
      System.out.println("IO Error while attempting to create " + tempFileName);
      System.out.println("Error: " + e.getMessage());
      System.exit(1);
    }
    // If validation is desired, write out the appropriate api.xsd file
    // in the same directory as the XML file.
    if (XMLToAPI.validateXML) {
      writeXSD();
    }
    return true;
  }
  public static void main(String[] args) {
    // read class name from command line args or user input
    String name;
    if (args.length > 0) name = args[0];
    else {
      Scanner in = new Scanner(System.in);
      System.out.println("Enter class name (e.g. java.util.Date): ");
      name = in.next();
    }

    try {
      // print class name and superclass name (if != Object)
      Class cl = Class.forName(name);
      Class supercl = cl.getSuperclass();
      String modifiers = Modifier.toString(cl.getModifiers());
      if (modifiers.length() > 0) System.out.print(modifiers + " ");
      System.out.print("class " + name);
      if (supercl != null && supercl != Object.class)
        System.out.print(" extends " + supercl.getName());

      System.out.print("\n{\n");
      printConstructors(cl);
      System.out.println();
      printMethods(cl);
      System.out.println();
      printFields(cl);
      System.out.println("}");
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
    System.exit(0);
  }
 public static void main(String[] args) {
   int errorCount = 0;
   for (int i = 0; i < NTESTS; i++) {
     try {
       System.out.println("Test " + i + ":");
       test(i);
     } catch (Throwable e) {
       errorCount++;
       boolean first = true;
       do {
         System.err.println(first ? "Exception:" : "Caused by:");
         first = false;
         e.printStackTrace();
         Throwable nexte;
         nexte = e.getCause();
         if (nexte == null) { // old JMX
           if (e instanceof MBeanException) nexte = ((MBeanException) e).getTargetException();
         }
         e = nexte;
       } while (e != null);
     }
   }
   if (errorCount == 0) {
     System.out.println("All ModelMBean tests successfuly passed");
     System.out.println("Bye! Bye!");
     // JTReg doesn't like System.exit(0);
     return;
   } else {
     System.err.println("ERROR: " + errorCount + " tests failed");
     System.exit(errorCount);
   }
 }
示例#8
0
 private static void main2(String[] args) {
   Config.cmdline(args);
   try {
     javabughack();
   } catch (InterruptedException e) {
     return;
   }
   setupres();
   MainFrame f = new MainFrame(null);
   if (Utils.getprefb("fullscreen", false)) f.setfs();
   f.mt.start();
   try {
     f.mt.join();
   } catch (InterruptedException e) {
     f.g.interrupt();
     return;
   }
   dumplist(Resource.remote().loadwaited(), Config.loadwaited);
   dumplist(Resource.remote().cached(), Config.allused);
   if (ResCache.global != null) {
     try {
       Writer w = new OutputStreamWriter(ResCache.global.store("tmp/allused"), "UTF-8");
       try {
         Resource.dumplist(Resource.remote().used(), w);
       } finally {
         w.close();
       }
     } catch (IOException e) {
     }
   }
   System.exit(0);
 }
示例#9
0
  public static void main(String[] args) throws Exception {
    System.out.println(
        "Test that target MBean class loader is used " + "before JMX Remote API class loader");

    ClassLoader jmxRemoteClassLoader = JMXServiceURL.class.getClassLoader();
    if (jmxRemoteClassLoader == null) {
      System.out.println(
          "JMX Remote API loaded by bootstrap " + "class loader, this test is irrelevant");
      return;
    }
    if (!(jmxRemoteClassLoader instanceof URLClassLoader)) {
      System.out.println("TEST INVALID: JMX Remote API not loaded by " + "URLClassLoader");
      System.exit(1);
    }

    URLClassLoader jrcl = (URLClassLoader) jmxRemoteClassLoader;
    URL[] urls = jrcl.getURLs();
    PrivateMLet mlet = new PrivateMLet(urls, null, false);
    Class shadowClass = mlet.loadClass(JMXServiceURL.class.getName());
    if (shadowClass == JMXServiceURL.class) {
      System.out.println("TEST INVALID: MLet got original " + "JMXServiceURL not shadow");
      System.exit(1);
    }

    MBeanServer mbs = MBeanServerFactory.newMBeanServer();
    mbs.registerMBean(mlet, mletName);

    final String[] protos = {"rmi", "iiop", "jmxmp"};
    boolean ok = true;
    for (int i = 0; i < protos.length; i++) {
      try {
        ok &= test(protos[i], mbs);
      } 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);
    }
  }
示例#10
0
  /**
   * Given the name of an interface <engineInterface> that a user wants to use for an engine, as
   * well as the name of a class <vmClass> that represents the vm, this does the following:
   *
   * <p>1. Checks that the given vm supports the interface. 2. Builds an engine and returns it.
   */
  public static FluidEngine buildEngine(String engineInterface, String vmClass) {
    // get class for <engineInterface>
    Class cEngine = null;
    try {
      cEngine = Class.forName(engineInterface);
    } catch (Exception e) {
      System.err.println("Could not find engine interface " + cEngine);
      e.printStackTrace();
      System.exit(1);
    }

    // get class for <vmClass>
    Class cVM = null;
    try {
      cVM = Class.forName(vmClass);
    } catch (Exception e) {
      System.err.println("Could not find VM " + cEngine);
      e.printStackTrace();
      System.exit(1);
    }

    // make a VM
    VM vm = null;
    try {
      vm = (VM) cVM.newInstance();
    } catch (Exception e) {
      System.err.println("Could not instantiate VM " + cEngine);
      e.printStackTrace();
      System.exit(1);
    }

    // check that the VM implements the interface
    VMUtils.checkInterface(cVM, cEngine);

    // build a version of the engine interface that calls back to
    // this basic engine for all its native methods
    BasicEngine result = buildCallbackEngine(engineInterface, cEngine);

    // do the setup for the resulting engine
    result.setup(vm);

    return result;
  }
示例#11
0
 public void process(File cFile) {
   try {
     String cName = ClassNameFinder.thisClass(BinaryFile.read(cFile));
     if (!cName.contains("")) return; // Ignore unpackaged classes
     testClass = Class.forName(cName);
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
   TestMethods testMethods = new TestMethods();
   Method creator = null;
   Method cleanup = null;
   for (Method m : testClass.getDeclaredMethods()) {
     testMethods.addIfTestMethod(m);
     if (creator == null) creator = checkForCreatorMethod(m);
     if (cleanup == null) cleanup = checkForCleanupMethod(m);
   }
   if (testMethods.size() > 0) {
     if (creator == null)
       try {
         if (!Modifier.isPublic(testClass.getDeclaredConstructor().getModifiers())) {
           Print.print("Error: " + testClass + " default constructor must be public");
           System.exit(1);
         }
       } catch (NoSuchMethodException e) {
         // Synthesized default constructor; OK
       }
     Print.print(testClass.getName());
   }
   for (Method m : testMethods) {
     Print.printnb("  . " + m.getName() + " ");
     try {
       Object testObject = createTestObject(creator);
       boolean success = false;
       try {
         if (m.getReturnType().equals(boolean.class)) success = (Boolean) m.invoke(testObject);
         else {
           m.invoke(testObject);
           success = true; // If no assert fails
         }
       } catch (InvocationTargetException e) {
         // Actual exception is inside e:
         Print.print(e.getCause());
       }
       Print.print(success ? "" : "(failed)");
       testsRun++;
       if (!success) {
         failures++;
         failedTests.add(testClass.getName() + ": " + m.getName());
       }
       if (cleanup != null) cleanup.invoke(testObject, testObject);
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
   }
 }
示例#12
0
 static void CatchSignal(int signum) {
   // System.out.println("caught signal " + signum);
   if (signum >= 0 && signum < signalHandlers.length) {
     try {
       signalHandlers[signum].invoke(null, new Object[] {new Integer(signum)});
     } catch (Exception e) {
       System.err.println("*** Jtux: can't invoke sa_handler method: " + e);
       System.exit(1);
     }
   }
 }
示例#13
0
    public void run() {
      CdhrString cret;

      System.out.println("JopSpiderCmd start");

      while (true) {
        cret = qcom.getString(qcom_qix, qcom_nid);
        //      System.out.println("awake : " + cret.getSts());
        if (cret.oddSts()) {
          int idx;
          System.out.println("Command received :" + cret.str);

          Cli cli = new Cli(cliTable);
          String command = cli.parse(cret.str);
          if (cli.oddSts()) {

            if (command.equals("OPEN")) {

              if (cli.qualifierFound("cli_arg1")) {

                String jgraph = "JGRAPH";
                String cli_arg1 = cli.getQualValue("cli_arg1").toUpperCase();
                if (jgraph.length() >= cli_arg1.length()
                    && jgraph.substring(0, cli_arg1.length()).equals(cli_arg1)) {
                  // Command is "OPEN JGRAPH"

                  boolean newFrame = cli.qualifierFound("/NEW");
                  boolean scrollbar = cli.qualifierFound("/SCROLLBAR");

                  if (!cli.qualifierFound("cli_arg2")) {
                    System.out.println("Syntax error");
                    return;
                  }
                  String frameName = cli.getQualValue("cli_arg2");

                  System.out.println("Loading frame \"" + frameName + "\"");
                  try {
                    loadFrame(session, frameName, null, scrollbar);
                  } catch (ClassNotFoundException e) {
                  }
                }
              }
            } else if (command.equals("EXIT")) {
              System.out.println("Jop exiting");
              System.exit(0);
            }
          }
        }
        try {
          sleep(1000);
        } catch (InterruptedException e) {
        }
      }
    }
示例#14
0
  private void checkAndLaunchUpdate() {
    Log.i(LOG_FILE_NAME, "Checking for an update");

    int statusCode = 8; // UNEXPECTED_ERROR
    File baseUpdateDir = null;
    if (Build.VERSION.SDK_INT >= 8)
      baseUpdateDir = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
    else baseUpdateDir = new File(Environment.getExternalStorageDirectory().getPath(), "download");

    File updateDir = new File(new File(baseUpdateDir, "updates"), "0");

    File updateFile = new File(updateDir, "update.apk");
    File statusFile = new File(updateDir, "update.status");

    if (!statusFile.exists() || !readUpdateStatus(statusFile).equals("pending")) return;

    if (!updateFile.exists()) return;

    Log.i(LOG_FILE_NAME, "Update is available!");

    // Launch APK
    File updateFileToRun = new File(updateDir, getPackageName() + "-update.apk");
    try {
      if (updateFile.renameTo(updateFileToRun)) {
        String amCmd =
            "/system/bin/am start -a android.intent.action.VIEW "
                + "-n com.android.packageinstaller/.PackageInstallerActivity -d file://"
                + updateFileToRun.getPath();
        Log.i(LOG_FILE_NAME, amCmd);
        Runtime.getRuntime().exec(amCmd);
        statusCode = 0; // OK
      } else {
        Log.i(LOG_FILE_NAME, "Cannot rename the update file!");
        statusCode = 7; // WRITE_ERROR
      }
    } catch (Exception e) {
      Log.i(LOG_FILE_NAME, "error launching installer to update", e);
    }

    // Update the status file
    String status = statusCode == 0 ? "succeeded\n" : "failed: " + statusCode + "\n";

    OutputStream outStream;
    try {
      byte[] buf = status.getBytes("UTF-8");
      outStream = new FileOutputStream(statusFile);
      outStream.write(buf, 0, buf.length);
      outStream.close();
    } catch (Exception e) {
      Log.i(LOG_FILE_NAME, "error writing status file", e);
    }

    if (statusCode == 0) System.exit(0);
  }
示例#15
0
文件: Main.java 项目: rde1024/mcgt
 public void addAction(String action) {
   try {
     Class<?> c = Class.forName(action);
     Constructor init = c.getConstructor(new Class[] {MinecraftProcess.class});
     Action a = (Action) init.newInstance(new Object[] {mcp});
     mcp.addAction(a);
   } catch (Exception e) {
     e.printStackTrace(System.err);
     System.exit(1);
   }
 }
示例#16
0
 static void CatchSignal(int signum, siginfo_t info, long context) {
   System.out.println("caught signal " + signum);
   if (signum >= 0 && signum < signalHandlers.length) {
     try {
       signalHandlers[signum].invoke(
           null, new Object[] {new Integer(signum), info, new Long(context)});
     } catch (Exception e) {
       System.err.println("*** Jtux: can't invoke sa_sigaction method: " + e);
       System.exit(1);
     }
   }
 }
示例#17
0
 public void writeIdToVertexMap(String filePath) {
   try {
     BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filePath)));
     for (Entry<Integer, String> entry : nodes.entrySet()) {
       bw.write(entry.getKey() + " " + entry.getValue() + "\n");
     }
     bw.close();
   } catch (Exception ex) {
     ex.printStackTrace();
     System.exit(-1);
   }
 }
示例#18
0
 /**
  * Unsupported command line interface.
  *
  * @param args The command line parameters.
  */
 public static void main(String[] args) throws Exception {
   if (args.length > 0 && args[0].equals("-Xjdb")) {
     String[] newargs = new String[args.length + 2];
     Class<?> c = Class.forName("com.redhat.ceylon.langtools.tools.example.debug.tty.TTY");
     Method method = c.getDeclaredMethod("main", new Class<?>[] {args.getClass()});
     method.setAccessible(true);
     System.arraycopy(args, 1, newargs, 3, args.length - 1);
     newargs[0] = "-connect";
     newargs[1] =
         "com.redhat.ceylon.langtools.jdi.CommandLineLaunch:options=-esa -ea:com.redhat.ceylon.langtools.tools...";
     newargs[2] = "com.redhat.ceylon.langtools.tools.javac.Main";
     method.invoke(null, new Object[] {newargs});
   } else {
     System.exit(compile(args));
   }
 }
示例#19
0
  @Override
  protected void onNewIntent(Intent intent) {
    if (checkLaunchState(LaunchState.GeckoExiting)) {
      // We're exiting and shouldn't try to do anything else just incase
      // we're hung for some reason we'll force the process to exit
      System.exit(0);
      return;
    }
    final String action = intent.getAction();
    if (ACTION_DEBUG.equals(action)
        && checkAndSetLaunchState(LaunchState.Launching, LaunchState.WaitForDebugger)) {

      mMainHandler.postDelayed(
          new Runnable() {
            public void run() {
              Log.i(LOG_FILE_NAME, "Launching from debug intent after 5s wait");
              setLaunchState(LaunchState.Launching);
              launch(null);
            }
          },
          1000 * 5 /* 5 seconds */);
      Log.i(LOG_FILE_NAME, "Intent : ACTION_DEBUG - waiting 5s before launching");
      return;
    }
    if (checkLaunchState(LaunchState.WaitForDebugger) || launch(intent)) return;

    if (Intent.ACTION_MAIN.equals(action)) {
      Log.i(LOG_FILE_NAME, "Intent : ACTION_MAIN");
      GeckoAppShell.sendEventToGecko(new GeckoEvent(""));
    } else if (Intent.ACTION_VIEW.equals(action)) {
      String uri = intent.getDataString();
      GeckoAppShell.sendEventToGecko(new GeckoEvent(uri));
      Log.i(LOG_FILE_NAME, "onNewIntent: " + uri);
    } else if (ACTION_WEBAPP.equals(action)) {
      String uri = intent.getStringExtra("args");
      GeckoAppShell.sendEventToGecko(new GeckoEvent(uri));
      Log.i(LOG_FILE_NAME, "Intent : WEBAPP - " + uri);
    } else if (ACTION_BOOKMARK.equals(action)) {
      String args = intent.getStringExtra("args");
      GeckoAppShell.sendEventToGecko(new GeckoEvent(args));
      Log.i(LOG_FILE_NAME, "Intent : BOOKMARK - " + args);
    }
  }
示例#20
0
 public DumpResource(String resource_name, String locale_name) {
   // Split locale_name into language_country_variant.
   String language;
   String country;
   String variant;
   language = locale_name;
   {
     int i = language.indexOf('_');
     if (i >= 0) {
       country = language.substring(i + 1);
       language = language.substring(0, i);
     } else country = "";
   }
   {
     int j = country.indexOf('_');
     if (j >= 0) {
       variant = country.substring(j + 1);
       country = country.substring(0, j);
     } else variant = "";
   }
   Locale locale = new Locale(language, country, variant);
   // Get the resource.
   ResourceBundle catalog = ResourceBundle.getBundle(resource_name, locale);
   // We are only interested in the messsages belonging to the locale
   // itself, not in the inherited messages. But catalog.getLocale() exists
   // only in Java2 and sometimes differs from the given locale.
   try {
     Writer w1 = new OutputStreamWriter(System.out, "UTF8");
     Writer w2 = new BufferedWriter(w1);
     this.out = w2;
     this.catalog = catalog;
     dump();
     w2.close();
     w1.close();
     System.out.flush();
   } catch (IOException e) {
     e.printStackTrace();
     System.exit(1);
   }
 }
 public static void main(String[] args) {
   new Thread() {
     @Override
     public void run() {
       try {
         System.out.println(
             Class.forName("reflection.field.staticf.booleanf.Main")
                 .getField("b")
                 .getBoolean(null));
       } catch (Exception e) {
         e.printStackTrace();
         System.exit(1);
       }
     }
   }.start();
   try {
     Class.forName("reflection.field.staticf.booleanf.Main").getField("b").setBoolean(null, true);
   } catch (Exception e) {
     e.printStackTrace();
     System.exit(1);
   }
 }
 public static void quit(
     int
         exitCode) { // redirect to System.exit() as to reduce warnings by static code analysis
                     // tools
   System.exit(exitCode);
 }
示例#23
0
 public void exit(ActionEvent e) {
   System.exit(0);
 }
 public static void main(String args[]) {
   try {
     SeleniumHtmlClient client = new SeleniumHtmlClient();
     String testFile = null;
     String testSuite = null;
     String resultsFilename = null;
     for (int i = 0; i < args.length; i++) {
       if (args[i].equals("--host")) {
         i++;
         if (i < args.length) {
           client.setHost(args[i]);
         } else {
           throw new BadUsageException("--host must be followed by a hostname");
         }
       } else if (args[i].equals("--port")) {
         i++;
         if (i < args.length) {
           client.setPort(Integer.parseInt(args[i]));
         } else {
           throw new BadUsageException("--port must be followed by a port number");
         }
       } else if (args[i].equals("--browser")) {
         i++;
         if (i < args.length) {
           client.setBrowser(args[i]);
         } else {
           throw new BadUsageException("--browser must be followed by a browser spec");
         }
       } else if (args[i].equals("--out")) {
         i++;
         if (i < args.length) {
           resultsFilename = args[i];
         } else {
           throw new BadUsageException("--out must be followed by a filename");
         }
         /*
         } else if (args[i].equals("--outdir")) {
         	i++;
         	if (i < args.length) {
         		client.setResultsDir(new File(args[i]));
         	} else {
         		throw new BadUsageException("--outdir must be followed by a path");
         	}
         	*/
       } else if (args[i].equals("--baseurl")) {
         i++;
         if (i < args.length) {
           client.setBaseUrl(args[i]);
         } else {
           throw new BadUsageException("--baseurl must be followed by a URL");
         }
       } else if (args[i].equals("--test")) {
         i++;
         if (i < args.length) {
           if (testFile == null) {
             testFile = args[i];
           } else {
             throw new BadUsageException("only one test file permitted");
           }
         } else {
           throw new BadUsageException("--test must be followed by a test filepath");
         }
       } else if (args[i].equals("--testsuite")) {
         i++;
         if (i < args.length) {
           testSuite = args[i];
         } else {
           throw new BadUsageException("--testsuite must be followed by a testsuite filepath");
         }
       } else if (args[i].equals("--verbose") || args[i].equals("-v")) {
         client.setVerbose(true);
       } else if (args[i].equals("--help") || args[i].equals("-h")) {
         printUsage();
         System.exit(0);
       } else {
         throw new BadUsageException("Unknown parameter " + args[i]);
       }
     }
     if (testFile == null && testSuite == null) {
       throw new BadUsageException("No test or testsuite file specified");
     } else if (testFile != null && testSuite != null) {
       throw new BadUsageException("A test and testsuite file cannot both be specified");
     }
     Writer resultsWriter = null;
     if (resultsFilename != null) {
       resultsWriter = new FileWriter(resultsFilename);
     } else /* if (client.resultsDir == null) */ {
       resultsWriter = new OutputStreamWriter(System.out);
     }
     client.setResultsWriter(resultsWriter);
     if (testFile != null) {
       client.runTest(testFile);
     } else {
       client.runSuite(testSuite);
     }
     if (resultsWriter != null) resultsWriter.close();
   } catch (BadUsageException e) {
     System.err.println("Error: " + e.getMessage());
     System.err.println();
     printUsage();
     System.exit(1);
   } catch (Exception e) {
     e.printStackTrace();
     System.exit(1);
   }
 }
示例#25
0
 public void run(String arg) {
   if (arg.equals("menus")) {
     updateMenus();
     return;
   }
   if (IJ.getApplet() != null) return;
   URL url = getClass().getResource("/ij/IJ.class");
   String ij_jar = url == null ? null : url.toString().replaceAll("%20", " ");
   if (ij_jar == null || !ij_jar.startsWith("jar:file:")) {
     error("Could not determine location of ij.jar");
     return;
   }
   int exclamation = ij_jar.indexOf('!');
   ij_jar = ij_jar.substring(9, exclamation);
   if (IJ.debugMode) IJ.log("Updater (jar loc): " + ij_jar);
   File file = new File(ij_jar);
   if (!file.exists()) {
     error("File not found: " + file.getPath());
     return;
   }
   if (!file.canWrite()) {
     String msg = "No write access: " + file.getPath();
     error(msg);
     return;
   }
   String[] list = openUrlAsList(IJ.URL + "/download/jars/list.txt");
   int count = list.length + 3;
   String[] versions = new String[count];
   String[] urls = new String[count];
   String uv = getUpgradeVersion();
   if (uv == null) return;
   versions[0] = "v" + uv;
   urls[0] = IJ.URL + "/upgrade/ij.jar";
   if (versions[0] == null) return;
   for (int i = 1; i < count - 2; i++) {
     String version = list[i - 1];
     versions[i] = version.substring(0, version.length() - 1); // remove letter
     urls[i] =
         IJ.URL + "/download/jars/ij" + version.substring(1, 2) + version.substring(3, 6) + ".jar";
   }
   versions[count - 2] = "daily build";
   urls[count - 2] = IJ.URL + "/ij.jar";
   versions[count - 1] = "previous";
   urls[count - 1] = IJ.URL + "/upgrade/ij2.jar";
   int choice = showDialog(versions);
   if (choice == -1 || !Commands.closeAll()) return;
   // System.out.println("choice: "+choice);
   // for (int i=0; i<urls.length; i++) System.out.println("  "+i+" "+urls[i]);
   byte[] jar = null;
   if ("daily build".equals(versions[choice]) && notes != null && notes.contains(" </title>"))
     jar = getJar("http://wsr.imagej.net/download/daily-build/ij.jar");
   if (jar == null) jar = getJar(urls[choice]);
   if (jar == null) {
     error("Unable to download ij.jar from " + urls[choice]);
     return;
   }
   Prefs.savePreferences();
   // System.out.println("saveJar: "+file);
   saveJar(file, jar);
   if (choice < count - 2) // force macro Function Finder to download fresh list
   new File(IJ.getDirectory("macros") + "functions.html").delete();
   System.exit(0);
 }
示例#26
0
 public void run(String arg) {
   if (arg.equals("menus")) {
     updateMenus();
     return;
   }
   if (IJ.getApplet() != null) return;
   // File file = new File(Prefs.getHomeDir() + File.separator + "ij.jar");
   // if (isMac() && !file.exists())
   //	file = new File(Prefs.getHomeDir() + File.separator +
   // "ImageJ.app/Contents/Resources/Java/ij.jar");
   URL url = getClass().getResource("/ij/IJ.class");
   String ij_jar = url == null ? null : url.toString().replaceAll("%20", " ");
   if (ij_jar == null || !ij_jar.startsWith("jar:file:")) {
     error("Could not determine location of ij.jar");
     return;
   }
   int exclamation = ij_jar.indexOf('!');
   ij_jar = ij_jar.substring(9, exclamation);
   if (IJ.debugMode) IJ.log("Updater: " + ij_jar);
   File file = new File(ij_jar);
   if (!file.exists()) {
     error("File not found: " + file.getPath());
     return;
   }
   if (!file.canWrite()) {
     String msg = "No write access: " + file.getPath();
     if (IJ.isVista()) msg += Prefs.vistaHint;
     error(msg);
     return;
   }
   String[] list = openUrlAsList(IJ.URL + "/download/jars/list.txt");
   int count = list.length + 2;
   String[] versions = new String[count];
   String[] urls = new String[count];
   String uv = getUpgradeVersion();
   if (uv == null) return;
   versions[0] = "v" + uv;
   urls[0] = IJ.URL + "/upgrade/ij.jar";
   if (versions[0] == null) return;
   for (int i = 1; i < count - 1; i++) {
     String version = list[i - 1];
     versions[i] = version.substring(0, version.length() - 1); // remove letter
     urls[i] =
         IJ.URL + "/download/jars/ij" + version.substring(1, 2) + version.substring(3, 6) + ".jar";
   }
   versions[count - 1] = "daily build";
   urls[count - 1] = IJ.URL + "/ij.jar";
   int choice = showDialog(versions);
   if (choice == -1) return;
   if (!versions[choice].startsWith("daily")
       && versions[choice].compareTo("v1.39") < 0
       && Menus.getCommands().get("ImageJ Updater") == null) {
     String msg =
         "This command is not available in versions of ImageJ prior\n"
             + "to 1.39 so you will need to install the plugin version at\n"
             + "<"
             + IJ.URL
             + "/plugins/imagej-updater.html>.";
     if (!IJ.showMessageWithCancel("Update ImageJ", msg)) return;
   }
   byte[] jar = getJar(urls[choice]);
   // file.renameTo(new File(file.getParent()+File.separator+"ij.bak"));
   if (version().compareTo("1.37v") >= 0) Prefs.savePreferences();
   // if (!renameJar(file)) return; // doesn't work on Vista
   saveJar(file, jar);
   if (choice < count - 1) // force macro Function Finder to download fresh list
   new File(IJ.getDirectory("macros") + "functions.html").delete();
   System.exit(0);
 }
  public static void main(String[] args) {
    boolean pass = true;

    printHeader(args);

    // Architecture tests...
    //
    pass &= testCircleArch();
    pass &= testRectangleArch();
    pass &= testTriangleArch();
    pass &= testConvexPolygonArch();
    pass &= testCanvasArch();

    // Unit Tests...
    //
    try {
      pass &= testCircle();
    } catch (Exception e) {
      pass &= false;
      System.out.println("FAILED, runtime exception testing Circle");
      e.printStackTrace();
    }

    try {
      pass &= testRectangle();
    } catch (Exception e) {
      pass &= false;
      System.out.println("FAILED, runtime exception testing Rectangle");
      e.printStackTrace();
    }

    try {
      pass &= testTriangle();
    } catch (Exception e) {
      pass &= false;
      System.out.println("FAILED, runtime exception testing Triangle");
      e.printStackTrace();
    }

    try {
      pass &= testConvexPolygon();
    } catch (Exception e) {
      pass &= false;
      System.out.println("FAILED, runtime exception testing ConvexPolygon");
      e.printStackTrace();
    }

    try {
      pass &= testCanvas();
    } catch (Exception e) {
      pass &= false;
      System.out.println("FAILED, runtime error testing Canvas");
      e.printStackTrace();
    }

    printResults(pass);

    // Added for to support robust script checking
    if (!pass) {
      System.exit(-1);
    }
  }
  public static void main(String[] args) throws Exception {
    System.out.println(
        "Checking that all known MBeans that are "
            + "NotificationBroadcasters have sane "
            + "MBeanInfo.getNotifications()");

    System.out.println("Checking platform MBeans...");
    checkPlatformMBeans();

    URL codeBase = ClassLoader.getSystemResource("javax/management/MBeanServer.class");
    if (codeBase == null) {
      throw new Exception("Could not determine codeBase for " + MBeanServer.class);
    }

    System.out.println();
    System.out.println("Looking for standard MBeans...");
    String[] classes = findStandardMBeans(codeBase);

    System.out.println("Testing standard MBeans...");
    for (int i = 0; i < classes.length; i++) {
      String name = classes[i];
      Class<?> c;
      try {
        c = Class.forName(name);
      } catch (Throwable e) {
        System.out.println(name + ": cannot load (not public?): " + e);
        continue;
      }
      if (!NotificationBroadcaster.class.isAssignableFrom(c)) {
        System.out.println(name + ": not a NotificationBroadcaster");
        continue;
      }
      if (Modifier.isAbstract(c.getModifiers())) {
        System.out.println(name + ": abstract class");
        continue;
      }

      NotificationBroadcaster mbean;
      Constructor<?> constr;
      try {
        constr = c.getConstructor();
      } catch (Exception e) {
        System.out.println(name + ": no public no-arg constructor: " + e);
        continue;
      }
      try {
        mbean = (NotificationBroadcaster) constr.newInstance();
      } catch (Exception e) {
        System.out.println(name + ": no-arg constructor failed: " + e);
        continue;
      }

      check(mbean);
    }

    System.out.println();
    System.out.println("Testing some explicit cases...");

    check(new RelationService(false));
    /*
      We can't do this:
        check(new RequiredModelMBean());
      because the Model MBean spec more or less forces us to use the
      names GENERIC and ATTRIBUTE_CHANGE for its standard notifs.
    */
    checkRMIConnectorServer();

    System.out.println();
    if (!suspicious.isEmpty()) System.out.println("SUSPICIOUS CLASSES: " + suspicious);

    if (failed.isEmpty()) System.out.println("TEST PASSED");
    else {
      System.out.println("TEST FAILED: " + failed);
      System.exit(1);
    }
  }
示例#29
0
  /**
   * Given class of the interface for a fluid engine, build a concrete instance of that interface
   * that calls back into a Basic Engine for all methods in the interface.
   */
  private static BasicEngine buildCallbackEngine(String engineInterface, Class cEngine) {
    // build up list of callbacks for <engineInterface>
    StringBuffer decls = new StringBuffer();
    Method[] engineMethods = cEngine.getMethods();
    for (int i = 0; i < engineMethods.length; i++) {
      Method meth = engineMethods[i];
      // skip methods that aren't declared in the interface
      if (meth.getDeclaringClass() != cEngine) {
        continue;
      }
      decls.append(
          "    public " + Utils.asTypeDecl(meth.getReturnType()) + " " + meth.getName() + "(");
      Class[] params = meth.getParameterTypes();
      for (int j = 0; j < params.length; j++) {
        decls.append(Utils.asTypeDecl(params[j]) + " p" + j);
        if (j != params.length - 1) {
          decls.append(", ");
        }
      }
      decls.append(") {\n");
      decls.append(
          "        return ("
              + Utils.asTypeDecl(meth.getReturnType())
              + ")super.callNative(\""
              + meth.getName()
              + "\", new Object[] {");
      for (int j = 0; j < params.length; j++) {
        decls.append("p" + j);
        if (j != params.length - 1) {
          decls.append(", ");
        }
      }
      decls.append("} );\n");
      decls.append("    }\n\n");
    }

    // write template file
    String engineName = "BasicEngine_" + engineInterface;
    String fileName = engineName + ".java";
    try {
      String contents = Utils.readFile("lava/engine/basic/BasicEngineTemplate.java").toString();
      // remove package name
      contents = Utils.replaceAll(contents, "package lava.engine.basic;", "");
      // for class decl
      contents =
          Utils.replaceAll(
              contents, "extends BasicEngine", "extends BasicEngine implements " + engineInterface);
      // for constructor
      contents = Utils.replaceAll(contents, "BasicEngineTemplate", engineName);
      // for methods
      contents = Utils.replaceAll(contents, "// INSERT METHODS HERE", decls.toString());
      Utils.writeFile(fileName, contents);
    } catch (IOException e) {
      e.printStackTrace();
      System.exit(1);
    }

    // compile the file
    try {
      Process jProcess = Runtime.getRuntime().exec("jikes " + fileName, null, null);
      jProcess.waitFor();
    } catch (Exception e) {
      System.err.println("Error compiling auto-generated file " + fileName);
      e.printStackTrace();
      System.exit(1);
    }

    // instantiate the class
    BasicEngine result = null;
    try {
      result = (BasicEngine) Class.forName(engineName).newInstance();
      // cleanup the files we made
      new File(engineName + ".java").delete();
      new File(engineName + ".class").delete();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }

    return result;
  }
 public static void main(String[] args) throws Exception {
   System.exit((new annotation13p()).test(args));
 }