Пример #1
0
  public static void initContainerForRobocodeEngine(File robocodeHome, IBattleListener listener) {
    try {
      if (robocodeHome == null) {
        robocodeHome = FileUtil.getCwd();
      }
      FileUtil.setCwd(robocodeHome);

      File robotsDir = FileUtil.getRobotsDir();

      if (robotsDir == null) {
        throw new RuntimeException("No valid robot directory is specified");
      } else if (!(robotsDir.exists() && robotsDir.isDirectory())) {
        throw new RuntimeException(
            '\'' + robotsDir.getAbsolutePath() + "' is not a valid robot directory");
      }

    } catch (IOException e) {
      System.err.println(e);
      return;
    }

    // here we cross transition to EngineClassLoader classes using interface which is defined in
    // system classLoader
    RobocodeMainBase main = Container.getComponent(RobocodeMainBase.class);

    main.initForRobocodeEngine(listener);
  }
Пример #2
0
 private void changeDirectory(String robocodeDir) {
   try {
     FileUtil.setCwd(new File(robocodeDir));
   } catch (IOException e) {
     System.err.println(robocodeDir + " is not a valid directory to start Robocode in.");
     System.exit(8);
   }
 }
Пример #3
0
  private void printResultsData(BattleCompletedEvent event) {
    // Do not print out if no result file has been specified and the GUI is enabled
    if ((setup.resultsFilename == null
        && (!setup.exitOnComplete || windowManager.isGUIEnabled()))) {
      return;
    }

    PrintStream out = null;
    FileOutputStream fos = null;

    try {
      if (setup.resultsFilename == null) {
        out = Logger.realOut;
      } else {
        File f = new File(setup.resultsFilename);

        try {
          fos = new FileOutputStream(f);
          out = new PrintStream(fos);
        } catch (IOException e) {
          Logger.logError(e);
        }
      }
      if (out != null) {
        BattleResultsTableModel resultsTable =
            new BattleResultsTableModel(
                event.getSortedResults(), event.getBattleRules().getNumRounds());

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        resultsTable.print(new PrintStream(baos));
        out.append(StringUtil.toBasicLatin(baos.toString()));
      }
    } finally {
      FileUtil.cleanupStream(out);
      FileUtil.cleanupStream(fos);
    }
  }
Пример #4
0
  public void cleanupStreams() {
    FileUtil.cleanupStream(objectWriteStream);
    objectWriteStream = null;
    FileUtil.cleanupStream(bufferedWriteStream);
    bufferedWriteStream = null;
    FileUtil.cleanupStream(fileWriteStream);
    fileWriteStream = null;

    FileUtil.cleanupStream(objectReadStream);
    objectReadStream = null;
    FileUtil.cleanupStream(bufferedReadStream);
    bufferedReadStream = null;
    FileUtil.cleanupStream(fileReadStream);
    fileReadStream = null;
  }
Пример #5
0
  public static void openURL(String url) throws IOException {

    // Check if the JVM is version 1.6.0 or higher
    if (System.getProperty("java.version").charAt(2) >= '6') {
      // Try calling java.awt.Desktop.getDesktop().browse(new URI(url)) that is available from Java
      // 6
      try {
        Class<?> desktopClass = Class.forName("java.awt.Desktop");
        Object desktop =
            desktopClass
                .getDeclaredMethod("getDesktop", (Class<?>[]) null)
                .invoke((Object) null, (Object[]) null);

        desktopClass.getDeclaredMethod("browse", URI.class).invoke(desktop, new URI(url));
        return; // leave

      } catch (ClassNotFoundException e) {
      } catch (SecurityException e) {
      } catch (NoSuchMethodException e) {
      } catch (IllegalArgumentException e) {
      } catch (IllegalAccessException e) {
      } catch (InvocationTargetException e) {
      } catch (URISyntaxException e) {
      }
      // If calling java.awt.Desktop.getDesktop().browse(new URI(url)) fails, we fall down to the
      // code below
    }

    url = FileUtil.quoteFileName(url);

    Runtime rt = Runtime.getRuntime();
    String os = System.getProperty("os.name").toLowerCase();

    if (os.startsWith("windows")) {
      rt.exec("rundll32 url.dll, FileProtocolHandler " + url);

    } else if (os.startsWith("mac")) {
      rt.exec("open " + url);

    } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0) {
      // Do a best guess on Unix until we get a platform independent way.
      // Build a list of browsers to try, in this order.
      final String[] browsers = {
        "epiphany",
        "firefox",
        "mozilla",
        "konqueror",
        "galeon",
        "netscape",
        "opera",
        "links",
        "lynx"
      };

      // Build a command string which looks like
      // "browser1 "url" || browser2 "url" || ..."
      StringBuffer cmd = new StringBuffer();

      for (int i = 0; i < browsers.length; i++) {
        cmd.append((i == 0 ? "" : " || ") + browsers[i] + " \"" + url + "\" ");
      }

      rt.exec(new String[] {"sh", "-c", cmd.toString()});
    }
  }
Пример #6
0
  public void saveRecord(
      String recordFilename, BattleRecordFormat format, SerializableOptions options) {
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    ZipOutputStream zos = null;
    ObjectOutputStream oos = null;
    OutputStreamWriter osw = null;
    XmlWriter xwr = null;

    FileInputStream fis = null;
    BufferedInputStream bis = null;
    ObjectInputStream ois = null;

    final boolean isbin =
        format == BattleRecordFormat.BINARY || format == BattleRecordFormat.BINARY_ZIP;
    final boolean isxml = format == BattleRecordFormat.XML || format == BattleRecordFormat.XML_ZIP;
    Calendar calendar = Calendar.getInstance();

    try {
      fos = new FileOutputStream(recordFilename);
      bos = new BufferedOutputStream(fos, 1024 * 1024);

      if (format == BattleRecordFormat.BINARY) {
        oos = new ObjectOutputStream(bos);
      } else if (format == BattleRecordFormat.BINARY_ZIP) {
        zos = new ZipOutputStream(bos);
        zos.putNextEntry(new ZipEntry(dateFormat.format(calendar.getTime()) + "-robocode.br"));
        oos = new ObjectOutputStream(zos);
      } else if (format == BattleRecordFormat.XML) {
        final Charset utf8 = Charset.forName("UTF-8");

        osw = new OutputStreamWriter(bos, utf8);
        xwr = new XmlWriter(osw, true);
      } else if (format == BattleRecordFormat.XML_ZIP) {
        final Charset utf8 = Charset.forName("UTF-8");

        zos = new ZipOutputStream(bos);
        zos.putNextEntry(new ZipEntry(dateFormat.format(calendar.getTime()) + "-robocode.xml"));

        osw = new OutputStreamWriter(zos, utf8);
        xwr = new XmlWriter(osw, false);
      }

      if (isbin) {
        oos.writeObject(recordInfo);
      } else if (isxml) {
        xwr.startDocument();
        xwr.startElement("record");
        xwr.writeAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        if (options.shortAttributes) {
          xwr.writeAttribute("xsi:noNamespaceSchemaLocation", "battleRecordS.xsd");
        } else {
          xwr.writeAttribute("xsi:noNamespaceSchemaLocation", "battleRecord.xsd");
        }
        recordInfo.writeXml(xwr, options);
        xwr.startElement("turns");
      }

      if (recordInfo.turnsInRounds != null) {
        fis = new FileInputStream(tempFile);
        bis = new BufferedInputStream(fis, 1024 * 1024);
        ois = new ObjectInputStream(bis);

        for (int i = 0; i < recordInfo.turnsInRounds.length; i++) {
          if (recordInfo.turnsInRounds[i] > 0) {
            for (int j = 0; j <= recordInfo.turnsInRounds[i] - 1; j++) {
              try {
                TurnSnapshot turn = (TurnSnapshot) ois.readObject();

                if (j != turn.getTurn()) {
                  throw new Error("Something rotten");
                }

                if (isbin) {
                  turn.stripDetails(options);
                  oos.writeObject(turn);
                } else if (isxml) {
                  turn.writeXml(xwr, options);
                }
              } catch (ClassNotFoundException e) {
                logError(e);
              }
            }
            if (isbin) {
              oos.flush();
            } else if (isxml) {
              osw.flush();
            }
            bos.flush();
            fos.flush();
          }
        }
        if (isxml) {
          xwr.endElement(); // turns
          xwr.endElement(); // record
          osw.flush();
        }
      }

    } catch (IOException e) {
      logError(e);
      recorder = new BattleRecorder(this, properties);
      createTempFile();
    } finally {
      FileUtil.cleanupStream(ois);
      FileUtil.cleanupStream(bis);
      FileUtil.cleanupStream(fis);
      FileUtil.cleanupStream(oos);
      FileUtil.cleanupStream(zos);
      FileUtil.cleanupStream(bos);
      FileUtil.cleanupStream(fos);
      FileUtil.cleanupStream(osw);
    }
  }
Пример #7
0
  public void loadRecord(String recordFilename, BattleRecordFormat format) {
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    ZipInputStream zis = null;
    ObjectInputStream ois = null;
    InputStream xis = null;

    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    ObjectOutputStream oos = null;

    try {
      createTempFile();
      fis = new FileInputStream(recordFilename);
      bis = new BufferedInputStream(fis, 1024 * 1024);

      if (format == BattleRecordFormat.BINARY) {
        ois = new ObjectInputStream(bis);
      } else if (format == BattleRecordFormat.BINARY_ZIP) {
        zis = new ZipInputStream(bis);
        zis.getNextEntry();
        ois = new ObjectInputStream(zis);
      } else if (format == BattleRecordFormat.XML_ZIP) {
        zis = new ZipInputStream(bis);
        zis.getNextEntry();
        xis = zis;
      } else if (format == BattleRecordFormat.XML) {
        xis = bis;
      }
      if (format == BattleRecordFormat.BINARY || format == BattleRecordFormat.BINARY_ZIP) {
        recordInfo = (BattleRecordInfo) ois.readObject();
        if (recordInfo.turnsInRounds != null) {
          fos = new FileOutputStream(tempFile);
          bos = new BufferedOutputStream(fos, 1024 * 1024);
          oos = new ObjectOutputStream(bos);

          for (int i = 0; i < recordInfo.turnsInRounds.length; i++) {
            for (int j = recordInfo.turnsInRounds[i] - 1; j >= 0; j--) {
              try {
                ITurnSnapshot turn = (ITurnSnapshot) ois.readObject();

                oos.writeObject(turn);
              } catch (ClassNotFoundException e) {
                logError(e);
              }
            }
          }
        }
      } else {
        final RecordRoot root = new RecordRoot();

        fos = new FileOutputStream(tempFile);
        bos = new BufferedOutputStream(fos, 1024 * 1024);
        root.oos = new ObjectOutputStream(bos);
        XmlReader.deserialize(xis, root);
        if (root.lastException != null) {
          logError(root.lastException);
        }
        recordInfo = root.recordInfo;
      }
    } catch (IOException e) {
      logError(e);
      createTempFile();
      recordInfo = null;
    } catch (ClassNotFoundException e) {
      if (e.getMessage().contains("robocode.recording.BattleRecordInfo")) {
        Logger.logError(
            "Sorry, backward compatibility with record from version 1.6 is not provided.");
      } else {
        logError(e);
      }
      createTempFile();
      recordInfo = null;
    } finally {
      FileUtil.cleanupStream(oos);
      FileUtil.cleanupStream(bos);
      FileUtil.cleanupStream(fos);
      FileUtil.cleanupStream(ois);
      FileUtil.cleanupStream(zis);
      FileUtil.cleanupStream(bis);
      FileUtil.cleanupStream(fis);
    }
  }
Пример #8
0
  public void loadSetup(String[] args) {

    final String nosecMessage =
        "Robocode is running without a security manager.\n"
            + "Robots have full access to your system.\n"
            + "You should only run robots which you trust!";
    final String exMessage =
        "Robocode is running in experimental mode.\n"
            + "Robots have access to their IRobotPeer interfaces.\n"
            + "You should only run robots which you trust!";

    if (RobocodeProperties.isSecurityOff()) {
      Logger.logWarning(nosecMessage);
    }
    if (System.getProperty("EXPERIMENTAL", "false").equals("true")) {
      Logger.logWarning(exMessage);
    }

    setup.tps = properties.getOptionsBattleDesiredTPS();

    // Disable canonical file path cache under Windows as it causes trouble when returning
    // paths with differently-capitalized file names.
    if (System.getProperty("os.name").toLowerCase().startsWith("windows ")) {
      System.setProperty("sun.io.useCanonCaches", "false");
    }

    // Initialize the system property so the AWT does not use headless mode meaning that the
    // GUI (Awt and Swing) is enabled per default when running starting Robocode.
    // It might be set to true later, if the -nodisplay option is set (in the setEnableGUI method).
    // Read more about headless mode here:
    // http://java.sun.com/developer/technicalArticles/J2SE/Desktop/headless/
    System.setProperty("java.awt.headless", "false");

    for (int i = 0; i < args.length; i++) {
      String currentArg = args[i];
      if (currentArg.equalsIgnoreCase("-cwd") && (i < args.length + 1)) {
        changeDirectory(args[i + 1]);
        i++;
      } else if (currentArg.equalsIgnoreCase("-battle") && (i < args.length + 1)) {
        setup.battleFilename = args[i + 1];
        i++;
      } else if (currentArg.equalsIgnoreCase("-record") && (i < args.length + 1)) {
        setup.recordFilename = args[i + 1];
        i++;
      } else if (currentArg.equalsIgnoreCase("-recordXML") && (i < args.length + 1)) {
        setup.recordXmlFilename = args[i + 1];
        i++;
      } else if (currentArg.equalsIgnoreCase("-replay") && (i < args.length + 1)) {
        setup.replayFilename = args[i + 1];
        i++;
      } else if (currentArg.equalsIgnoreCase("-results") && (i < args.length + 1)) {
        setup.resultsFilename = args[i + 1];
        i++;
      } else if (currentArg.equalsIgnoreCase("-tps") && (i < args.length + 1)) {
        setup.tps = Integer.parseInt(args[i + 1]);
        if (setup.tps < 1) {
          Logger.logError("tps must be > 0");
          System.exit(8);
        }
        i++;
      } else if (currentArg.equalsIgnoreCase("-minimize")) {
        setup.minimize = true;
      } else if (currentArg.equalsIgnoreCase("-nodisplay")) {
        if (windowManager != null) {
          windowManager.setEnableGUI(false);
        }
        if (soundManager != null) {
          soundManager.setEnableSound(false);
        }
        setup.tps = 10000; // set TPS to maximum
      } else if (currentArg.equalsIgnoreCase("-nosound")) {
        if (soundManager != null) {
          soundManager.setEnableSound(false);
        }
      } else if (currentArg.equals("-?") || currentArg.equalsIgnoreCase("-help")) {
        printUsage();
        System.exit(0);
      } else {
        Logger.logError("Not understood: " + currentArg);
        printUsage();
        System.exit(8);
      }
    }
    File robotsDir = FileUtil.getRobotsDir();

    if (robotsDir == null) {
      System.err.println("No valid robot directory is specified");
      System.exit(8);
    } else if (!(robotsDir.exists() && robotsDir.isDirectory())) {
      System.err.println('\'' + robotsDir.getAbsolutePath() + "' is not a valid robot directory");
      System.exit(8);
    }

    // The Default Toolkit must be set as soon as we know if we are going to use headless mode or
    // not.
    // That is if the toolkit must be headless or not (GUI on/off). If we are running in headless
    // mode
    // from this point, a HeadlessException will be thrown if we access a AWT/Swing component.
    // Read more about headless mode here:
    // http://java.sun.com/developer/technicalArticles/J2SE/Desktop/headless/
    Toolkit.getDefaultToolkit();
  }
Пример #9
0
  public void compile(String directory, String fileName) {
    fileName = FileUtil.quoteFileName(fileName);

    ConsoleDialog console;

    if (editor != null) {
      console = new ConsoleDialog(editor, "Compiling", false);
    } else {
      console = new ConsoleDialog();
    }
    console.setSize(500, 400);
    console.setText("Compiling...\n");
    WindowUtil.centerShow(editor, console);

    try {
      StringBuffer command =
          new StringBuffer(compilerBinary)
              .append(' ')
              .append(compilerOptions)
              .append(' ')
              .append(compilerClassPath)
              .append(' ')
              .append(fileName);

      Logger.logMessage("Compile command: " + command);

      ProcessBuilder pb = new ProcessBuilder(command.toString().split(" "));

      pb.redirectErrorStream(true);
      pb.directory(FileUtil.getCwd());
      Process p = pb.start();

      // The waitFor() must done after reading the input and error stream of the process
      console.processStream(p.getInputStream());
      p.waitFor();

      if (p.exitValue() == 0) {
        console.append("Compiled successfully.\n");
        console.setTitle("Compiled successfully.");
      } else {
        console.append("Compile Failed (" + p.exitValue() + ")\n");
        console.setTitle("Compile failed.");
      }
    } catch (IOException e) {
      console.append("Unable to compile!\n");
      console.append("Exception was: " + e.toString() + "\n");
      console.append("Does " + compilerBinary + " exist?\n");
      console.setTitle("Exception while compiling");
    } catch (InterruptedException e) {
      // Immediately reasserts the exception by interrupting the caller thread itself
      Thread.currentThread().interrupt();

      console.append("Compile interrupted.\n");
      console.setTitle("Compile interrupted.");
    }

    int codesize = -1;

    try {
      File fileDir = new File(directory);

      // Call the Codesize utility using reflection
      Object item =
          Class.forName("codesize.Codesize")
              .getMethod("processDirectory", new Class[] {File.class})
              .invoke(null, fileDir);

      codesize =
          (Integer)
              item.getClass()
                  .getMethod("getCodeSize", (Class[]) null)
                  .invoke(item, (Object[]) null);
    } catch (Exception ignore) {
    }
    if (codesize >= 0) {
      String weightClass = null;

      if (codesize >= 1500) {
        weightClass = "MegaBot  (codesize >= 1500 bytes)";
      } else if (codesize > 750) {
        weightClass = "MiniBot  (codesize < 1500 bytes)";
      } else if (codesize > 250) {
        weightClass = "MicroBot (codesize < 750 bytes)";
      } else {
        weightClass = "NanoBot  (codesize < 250 bytes)";
      }
      StringBuilder sb = new StringBuilder();

      sb.append("\n\n---- Codesize ----\n");
      sb.append("Codesize: ").append(codesize).append(" bytes\n");
      sb.append("Robot weight class: ").append(weightClass).append('\n');

      console.append(sb.toString());
    }
  }