Exemplo n.º 1
1
  public ConsoleManager(GlowServer server) {
    this.server = server;

    // install Ansi code handler, which makes colors work on Windows
    AnsiConsole.systemInstall();

    for (Handler h : logger.getHandlers()) {
      logger.removeHandler(h);
    }

    // used until/unless gui is created
    consoleHandler = new FancyConsoleHandler();
    // consoleHandler.setFormatter(new DateOutputFormatter(CONSOLE_DATE));
    logger.addHandler(consoleHandler);

    // todo: why is this here?
    Runtime.getRuntime().addShutdownHook(new ServerShutdownThread());

    // reader must be initialized before standard streams are changed
    try {
      reader = new ConsoleReader();
    } catch (IOException ex) {
      logger.log(Level.SEVERE, "Exception initializing console reader", ex);
    }
    reader.addCompleter(new CommandCompleter());

    // set system output streams
    System.setOut(new PrintStream(new LoggerOutputStream(Level.INFO), true));
    System.setErr(new PrintStream(new LoggerOutputStream(Level.WARNING), true));
  }
Exemplo n.º 2
1
 public MapBuilder(String name, File toLoad, File toSave, String tileDir) {
   super(name);
   currTileImg = null;
   currTileLoc = "";
   try {
     System.out.println(tileDir);
     currTileImg = new ImageIcon(getTile(tileDir, 0, 0, DISPLAY_SCALE));
     currTileLoc = "0_0";
   } catch (IOException e) {
     System.out.println("Generating current tile failed.");
     System.out.println(e);
     System.exit(0);
   }
   currTileDisplay = new JLabel(new ImageIcon(scaleImage(currTileImg.getImage(), 2)));
   this.input = toLoad;
   output = toSave;
   this.tileDir = tileDir;
   if (toLoad != null) {
     try {
       backEnd = loadMap(toLoad);
     } catch (FileNotFoundException e) {
       System.err.println("Could not find input file.");
       System.exit(0);
     }
   } else {
     backEnd = emptyMap(DEFAULT_WIDTH, DEFAULT_HEIGHT);
   }
   mapWidth = backEnd.getWidth();
   mapHeight = backEnd.getHeight();
 }
Exemplo n.º 3
1
 static {
   if (Configuration.isMacOS()) {
     System.setProperty("apple.laf.useScreenMenuBar", "true");
     System.setProperty("com.apple.mrj.application.apple.menu.about.name", APP_NAME);
     System.setProperty("com.apple.mrj.application.growbox.intrudes", "false");
   }
 }
  /**
   * 批量删除指定名称的布局
   *
   * @param mapLayoutNames 布局名称
   */
  public static void deleteMapLayout(String[] mapLayoutNames) {
    try {
      String message = "";
      if (mapLayoutNames.length == 1) {
        message = CoreProperties.getString("String_LayoutDelete_Confirm");
        message =
            message
                + System.lineSeparator()
                + String.format(
                    CoreProperties.getString("String_LayoutDelete_Confirm_One"), mapLayoutNames[0]);
      } else {
        message = CoreProperties.getString("String_LayoutDelete_Confirm");
        message =
            message
                + System.lineSeparator()
                + String.format(
                    CoreProperties.getString("String_LayoutDelete_Confirm_Multi"),
                    mapLayoutNames.length);
      }
      if (!Objects.equals(message, "")
          && (JOptionPaneUtilties.showConfirmDialog(message) == JOptionPane.OK_OPTION)) {

        for (String mapLayoutName : mapLayoutNames) {
          Application.getActiveApplication().getWorkspace().getLayouts().remove(mapLayoutName);
        }
      }
    } catch (Exception ex) {
      Application.getActiveApplication().getOutput().output(ex);
    }
  }
Exemplo n.º 5
0
    // Creates a new thread, runs the program in that thread, and reports any errors as needed.
    private void run(String clazz) {
      try {
        // Makes sure the JVM resets if it's already running.
        if (JVMrunning) kill();

        // Some String constants for java path and OS-specific separators.
        String separator = System.getProperty("file.separator");
        String path = System.getProperty("java.home") + separator + "bin" + separator + "java";

        // Tries to run compiled code.
        ProcessBuilder builder = new ProcessBuilder(path, clazz);

        // Should be good now! Everything past this is on you. Don't mess it up.
        println(
            "Build succeeded on " + java.util.Calendar.getInstance().getTime().toString(), progErr);
        println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", progErr);

        JVM = builder.start();

        // Note that as of right now, there is no support for input. Only output.
        Reader errorReader = new InputStreamReader(JVM.getErrorStream());
        Reader outReader = new InputStreamReader(JVM.getInputStream());
        // Writer inReader = new OutputStreamWriter(JVM.getOutputStream());

        redirectErr = redirectIOStream(errorReader, err);
        redirectOut = redirectIOStream(outReader, out);
        // redirectIn = redirectIOStream(null, inReader);
      } catch (Exception e) {
        // This catches any other errors we might get.
        println("Some error thrown", progErr);
        logError(e.toString());
        displayLog();
        return;
      }
    }
 public TestType1CFont(InputStream is) throws IOException {
   super();
   setPreferredSize(new Dimension(800, 800));
   addKeyListener(this);
   BufferedInputStream bis = new BufferedInputStream(is);
   int count = 0;
   ArrayList<byte[]> al = new ArrayList<byte[]>();
   byte b[] = new byte[32000];
   int len;
   while ((len = bis.read(b, 0, b.length)) >= 0) {
     byte[] c = new byte[len];
     System.arraycopy(b, 0, c, 0, len);
     al.add(c);
     count += len;
     b = new byte[32000];
   }
   data = new byte[count];
   len = 0;
   for (int i = 0; i < al.size(); i++) {
     byte from[] = al.get(i);
     System.arraycopy(from, 0, data, len, from.length);
     len += from.length;
   }
   pos = 0;
   //	printData();
   parse();
   // TODO: free up (set to null) unused structures (data, subrs, stack)
 }
  public void displayAllClassesNames(List<String> classNames) {
    long start = System.currentTimeMillis();

    displayDataState = DisplayDataState.CLASSES_LIST;
    StyleConstants.setFontSize(style, 18);
    StyleConstants.setForeground(style, ColorScheme.FOREGROUND_CYAN);

    clearText();

    BatchDocument blank = new BatchDocument();
    jTextPane.setDocument(blank);

    for (String className : classNames) {
      blank.appendBatchStringNoLineFeed(className, style);
      blank.appendBatchLineFeed(style);
    }

    try {
      blank.processBatchUpdates(0);
    } catch (BadLocationException e) {
      e.printStackTrace();
    }

    jTextPane.setDocument(blank);

    System.out.println("UI update " + (System.currentTimeMillis() - start) + " ms");
  }
Exemplo n.º 8
0
  /**
   * 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);
    }
  }
Exemplo n.º 9
0
  public Notification(
      @NotNull String groupDisplayId,
      @NotNull Icon icon,
      @Nullable String title,
      @Nullable String subtitle,
      @Nullable String content,
      @NotNull NotificationType type,
      @Nullable NotificationListener listener) {
    myGroupId = groupDisplayId;
    myTitle = StringUtil.notNullize(title);
    myContent = StringUtil.notNullize(content);
    myType = type;
    myListener = listener;
    myTimestamp = System.currentTimeMillis();

    myIcon = icon;
    mySubtitle = subtitle;

    LOG.assertTrue(
        isTitle() || isContent(),
        "Notification should have title: "
            + title
            + " and/or subtitle and/or content groupId: "
            + myGroupId);

    id =
        String.valueOf(System.currentTimeMillis())
            + "."
            + String.valueOf(System.identityHashCode(this));
  }
Exemplo n.º 10
0
  public static void main(String[] args) {
    JFrame frame = new JFrame("Maze View");

    Random random = new Random();
    long startTime = System.nanoTime();
    MazeNode maze = MazeNode.generate(random, 100, 100);
    System.out.println("Gen : " + elapsedMs(startTime) + "ms");

    startTime = System.nanoTime();
    int sx = 0; // random.nextInt(maze.width);
    int sy = 0; // random.nextInt(maze.height);
    int dx = maze.width - 1; // random.nextInt(maze.width);
    int dy = maze.height - 1; // random.nextInt(maze.height);
    Path path = PathSolver.solve(maze, sx, sy, dx, dy);
    System.out.println("Solve : " + elapsedMs(startTime) + "ms");
    int pathSize = 0;
    PathCell pathIt = path.first;
    while (pathIt != null) {
      pathSize++;
      pathIt = pathIt.next;
    }
    System.out.println("Path Size: " + pathSize);

    frame.add(new JScrollPane(new MazeView(maze, sx, sy, dx, dy, path)));

    frame.setSize(500, 500);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    SwingUtilities.invokeLater(() -> frame.setVisible(true));
  }
Exemplo n.º 11
0
    public synchronized void paint(Graphics g) {
      if (needToStartThread) {
        totalDrawTime = 0;
        counter = 0;
        needToStartThread = false;
        startThread(beginAngle, endAngle);
        if (firstImage == null) {
          firstImage = createImageFromComponent(component1);
        }
        if (secondImage == null) {
          secondImage = createImageFromComponent(component2);
        }
      }
      if (firstImage == null || secondImage == null) return;
      Graphics2D g2d = (Graphics2D) g;
      int ww = firstImage.getWidth();
      int hh = firstImage.getHeight();
      {
        BufferedImage currImage = null;
        int[] currPixels = null;
        int w = firstImage.getWidth();
        int offset = (int) (w * angle / 180);
        if (offset < 0) offset = 0;
        if (offset > w) offset = w;

        long beforeDraw = System.currentTimeMillis();
        g2d.drawImage(firstImage, null, 0, 0);
        g2d.drawImage(secondImage, null, w - offset, 0);
        totalDrawTime += (System.currentTimeMillis() - beforeDraw);
        counter++;
      }
    }
  private JComponent createLabelsPanel() {
    JPanel panel = new JPanel();
    panel.setLayout(new GridLayout(0, 2, 10, 1));

    // Creates a StyledLabel to warn up so that we don't include class loading time into the
    // performance test.
    // This is the same for all three cases.
    new JLabel("Bold Italic Underlined");

    long start = System.currentTimeMillis();
    for (int i = 0; i < COUNT; i++) {
      JLabel label = new JLabel("Bold Italic Underlined");
      panel.add(label);
    }
    panel.setBorder(
        BorderFactory.createCompoundBorder(
            BorderFactory.createTitledBorder(
                new PartialLineBorder(Color.gray, 1, true),
                " JLabel (Plain) Examples - use " + (System.currentTimeMillis() - start) + " ms ",
                TitledBorder.CENTER,
                TitledBorder.CENTER,
                null,
                Color.RED),
            BorderFactory.createEmptyBorder(6, 4, 4, 4)));
    return panel;
  }
  // initialize data hash table servers
  // read server addresses from file and initialize the servers
  private void initServers() {

    try {
      java.net.URL path = ClassLoader.getSystemResource(clientSettingFile);
      FileReader fr = new FileReader(path.getFile());
      BufferedReader br = new BufferedReader(fr);
      try {
        String[] portMap = br.readLine().split(",");
        mServerCount = portMap.length;
        mPortMap = new int[mServerCount];
        for (int i = 0; i < mServerCount; i++) {
          mPortMap[i] = Integer.parseInt(portMap[i]);
        }
      } catch (IOException e) {
        e.printStackTrace();
        System.exit(-1);
      }
    } catch (FileNotFoundException e2) {
      e2.printStackTrace();
      System.exit(-1);
    }

    mDhtServerArray = new IDistributedHashTable[mServerCount];
    for (int i = 0; i < mServerCount; i++) {
      try {
        mDhtServerArray[i] =
            (IDistributedHashTable)
                Naming.lookup("rmi://localhost:" + mPortMap[i] + "/DistributedHashTable");
        appendOutput("server: " + (i + 1) + " is connected");
      } catch (Exception e) {
        appendOutput("initServers: " + (i + 1) + " " + e.getMessage());
      }
    }
  }
Exemplo n.º 14
0
  public final void runMovement() {
    if (!isShowing()) {
      return;
    }
    final int distance;
    final Rectangle bounds = getBounds();
    if (myAnchor == ToolWindowAnchor.LEFT || myAnchor == ToolWindowAnchor.RIGHT) {
      distance = bounds.width;
    } else {
      distance = bounds.height;
    }
    int count = 0;
    myOffset = 0;
    paintImmediately(
        0, 0, getWidth(), getHeight()); // first paint requires more time than next ones
    final long startTime = System.currentTimeMillis();

    while (true) {
      paintImmediately(0, 0, getWidth(), getHeight());
      final long timeSpent = System.currentTimeMillis() - startTime;
      count++;
      if (timeSpent >= myDesiredTimeToComplete) break;
      final double onePaintTime = (double) timeSpent / count;
      int iterations = (int) ((myDesiredTimeToComplete - timeSpent) / onePaintTime);
      iterations = Math.max(1, iterations);
      myOffset += (distance - myOffset) / iterations;
    }
  }
Exemplo n.º 15
0
  public void run() {

    long lastTime = System.nanoTime();
    long timer = System.currentTimeMillis();
    final double ns = 1000000000.0 / 60.0;
    double delta = 0;
    int frames = 0;
    int updates = 0;
    //		setFocusable(true);
    requestFocus();

    while (running) {
      long now = System.nanoTime();
      delta += (now - lastTime) / ns;
      lastTime = now;
      while (delta >= 1) {
        update();
        updates++;
        delta--;
      }
      // Renderiza tudo na tela
      render();
      // Calcula FPS
      frames++;

      if ((System.currentTimeMillis() - timer) > 1000) {
        timer += 1000;
        // T�tulo do jogo
        frame.setTitle(title + "  |  " + updates + " ups / " + frames + " fps ");
        updates = 0;
        frames = 0;
      }
    }
    stop();
  }
Exemplo n.º 16
0
  /** Checks if the program can run under the JDK it was started with. */
  private static boolean checkJdkVersion() {
    if (!"true".equals(System.getProperty("idea.no.jre.check"))) {
      try {
        // try to find a class from tools.jar
        Class.forName("com.sun.jdi.Field");
      } catch (ClassNotFoundException e) {
        showError(
            "Error",
            "'tools.jar' is not in "
                + ApplicationNamesInfo.getInstance().getProductName()
                + " classpath.\n"
                + "Please ensure JAVA_HOME points to JDK rather than JRE.");
        return false;
      }
    }

    if (!"true".equals(System.getProperty("idea.no.jdk.check"))) {
      final String version = System.getProperty("java.version");
      if (!SystemInfo.isJavaVersionAtLeast("1.6")) {
        showError(
            "Java Version Mismatch",
            "The JDK version is "
                + version
                + ".\n"
                + ApplicationNamesInfo.getInstance().getProductName()
                + " requires JDK 1.6 or higher.");
        return false;
      }
    }

    return true;
  }
Exemplo n.º 17
0
    /* (non-Javadoc)
     * @see org.jdesktop.swingworker.SwingWorker#doInBackground()
     */
    @Override
    protected Void doInBackground() throws Exception {

      if (errorInfo != null) {
        Throwable t = errorInfo.getErrorException();
        String osMessage =
            "An error occurred on "
                + System.getProperty("os.name")
                + " version "
                + System.getProperty("os.version");
        StringBuffer message = new StringBuffer();
        message.append("System Info : ").append(osMessage).append(NEW_LINE_CHAR);
        message.append("Message : ").append(t.toString()).append(NEW_LINE_CHAR);
        message.append("Level : ").append(errorInfo.getErrorLevel()).append(NEW_LINE_CHAR);
        message.append("Stack Trace : ").append(NEW_LINE_CHAR);
        message.append(stackTraceToString(t));

        // copy error message to system clipboard
        StringSelection stringSelection = new StringSelection(message.toString());
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(stringSelection, null);

        // open errorReportingURL
        OpenBrowserAction openBrowserAction = new OpenBrowserAction(errorReportingURL);
        openBrowserAction.actionPerformed(null);
      }

      return null;
    }
Exemplo n.º 18
0
 /**
  * This method runs the Runnable and measures how long it takes.
  *
  * @param r is the Runnable for the task that we want to measure
  * @return the time it took to execute this task
  */
 public static long time(Runnable r) {
   long time = -System.currentTimeMillis();
   r.run();
   time += System.currentTimeMillis();
   System.out.println("Took " + time + "ms");
   return time;
 }
Exemplo n.º 19
0
  private void tryToInitialize(int counter) {
    boolean existsCompatibleBrowser = getComponent() != null && isCompatible();
    synchronized (this) {
      initialized = existsCompatibleBrowser;
    }
    log.info(System.currentTimeMillis() + " initialized map: " + initialized);

    if (isInitialized()) {
      log.fine(System.currentTimeMillis() + " compatible, further initializing map");
      initializeAfterLoading();
      initializeBrowserInteraction();
      initializeCallbackListener();
      checkLocalhostResolution();
      checkCallback();
    } else {
      if (counter++ < 50) {
        log.info(System.currentTimeMillis() + " WAITING " + counter * 100 + " milliseconds");
        try {
          Thread.sleep(counter * 100);
        } catch (InterruptedException e) {
          // intentionally left empty
        }

        tryToInitialize(counter);
      }
    }
  }
Exemplo n.º 20
0
 public void paintComponent(Graphics g) {
   long start = System.currentTimeMillis();
   for (int r = 0; r < game.getRows(); r++) {
     for (int c = 0; c < game.getCols(); c++) {
       if (game.getTileAt(r, c).getResource() == Resource.FOOD) {
         g.setColor(new Color(186, 57, 57));
       } else if (game.getTileAt(r, c).getResource() == Resource.GOLD) {
         g.setColor(new Color(240, 188, 16));
       } else if (game.getTileAt(r, c).getResource() == Resource.STONE) {
         g.setColor(new Color(129, 133, 146));
       } else if (game.getTileAt(r, c).getResource() == Resource.WOOD) {
         g.setColor(new Color(55, 91, 67));
       } else // Resource is none or does not change color.
       {
         if (game.getTileAt(r, c).getTerrainType() == Terrain.SAND)
           g.setColor(new Color(255, 241, 212));
         else if (game.getTileAt(r, c).getTerrainType() == Terrain.WATER)
           g.setColor(new Color(51, 126, 255));
         else if (game.getTileAt(r, c).getTerrainType() == Terrain.FOREST)
           g.setColor(new Color(139, 131, 120));
         else if (game.getTileAt(r, c).getTerrainType() == Terrain.MOUNTAIN)
           g.setColor(new Color(238, 238, 224));
         else if (game.getTileAt(r, c).getTerrainType() == Terrain.SNOW)
           g.setColor(new Color(255, 255, 255));
         else g.setColor(new Color(118, 208, 108));
       }
       g.fillRect(r * 1, c * 1, 1, 1);
     }
   }
   long end = System.currentTimeMillis();
   System.out.println("JPanel Setup Time: " + (end - start));
 }
Exemplo n.º 21
0
 @Override
 public void load() {
   for (AnimationComboListener listener : comboListeners) {
     listener.load();
   }
   otherCombo.setSelectedIndex(
       MCPatcherUtils.getBoolean(MCPatcherUtils.HD_TEXTURES, "customOther", true) ? 1 : 0);
   boolean is64bit = false;
   try {
     String datamodel =
         System.getProperty("sun.arch.data.model"); // sun-specific, but gets the arch of the jvm
     String arch =
         System.getProperty(
             "os.arch"); // generic, but gets the arch of the os, not the jvm (may be a 32-bit jvm
                         // on a 64-bit os)
     if (datamodel != null) {
       is64bit = (Integer.parseInt(datamodel) >= 64);
     } else if (arch != null) {
       is64bit = arch.contains("64");
     } else {
       is64bit = false;
     }
   } catch (Throwable e) {
   }
   textureCacheCheckBox.setSelected(
       MCPatcherUtils.getBoolean(MCPatcherUtils.HD_TEXTURES, "useTextureCache", is64bit));
   shrinkGLMemoryCheckBox.setSelected(
       MCPatcherUtils.getBoolean(MCPatcherUtils.HD_TEXTURES, "reclaimGLMemory", false));
   autoRefreshTexturesCheckBox.setSelected(
       MCPatcherUtils.getBoolean(MCPatcherUtils.HD_TEXTURES, "autoRefreshTextures", false));
 }
Exemplo n.º 22
0
  /**
   * Returns JPicEdt's install directory w/o trailing "/", provided the command line looks like :
   *
   * <p><code>java -classpath other-class-paths:jpicedt-install-dir/lib/jpicedt.jar jpicedt.JPicEdt
   * </code> (where <code>/</code> may be replaced by the actual respective separator for files on
   * the underlying platform).
   *
   * <p>For Windows platform, the install directory is tried to be detected 1st with the MSWindows
   * file-separator (<code>\</code>), and if this does not work, a subsequent trial is made with
   * <code>/</code>.
   *
   * <p>That is, the old way (java -jar jpicedt.jar) won't work. However, classpath can contain
   * relative pathname (then user.dir get prepended).
   *
   * <p>Code snippet was adapted from jEdit/JEdit.java (http://www.jedit.org).
   *
   * @return the value of the "user.dir" Java property if "lib/jpicedt.jar" wasn't found in the
   *     command line.
   */
  public static String getJPicEdtHome() {

    String classpath = System.getProperty("java.class.path"); // e.g.
    // "/usr/lib/java/jre/lib/rt.jar:/home/me/jpicedt/1.3.2/lib/jpicedt.jar"
    // File.separator = "/" on Unix, "\\" on Windows,...
    String fileSeparator = File.separator;
    int index;
    // File.pathSeparator = ":" on Unix/MacOS-X platforms, ";" on Windows
    // search ":" backward starting from
    // "/usr/lib/java/jre/lib/rt.jar:/home/me/jpicedt/1.3.2/^lib/jpicedt.jar"

    String homeDir = null;
    int trials = 2;
    do {
      index = classpath.toLowerCase().indexOf("lib" + fileSeparator + "jpicedt.jar");
      int start = classpath.lastIndexOf(File.pathSeparator, index);
      if (start == -1)
        start =
            0; // File.pathSeparator not found => lib/jpicedt.jar probably at beginning of classpath
      else start += File.pathSeparator.length(); // e.g. ":^/home..."

      if (index >= start) {
        homeDir = classpath.substring(start, index);
        if (homeDir.endsWith(fileSeparator)) homeDir = homeDir.substring(0, homeDir.length() - 1);
      }
      switch (trials) {
        case 2:
          if (File.pathSeparator.equals(";") && homeDir == null) {
            // MS-Windows case, this must work both with / and \
            trials = 1;
            fileSeparator = "/";
          } else trials = 0;
          break;
        case 1:
          if (homeDir != null && !fileSeparator.equals(File.separator)) {
            homeDir.replace(fileSeparator, File.separator);
          }
          trials = 0;
          break;

        default:
          trials = 0;
          break;
      }
    } while (trials != 0);

    if (homeDir != null) {
      if (homeDir.equals("")) homeDir = System.getProperty("user.dir");
      else if (!new File(homeDir).isAbsolute())
        homeDir = System.getProperty("user.dir") + File.separator + homeDir;
    } else {
      homeDir = System.getProperty("user.dir");
      if (homeDir.endsWith(
          "lib")) // this is the case if jpicedt run as "java -jar jpicedt.jar" from inside lib/ dir
      homeDir = homeDir.substring(0, homeDir.lastIndexOf("lib"));
    }

    // System.out.println("JPicEdt's home = " + homeDir);
    return homeDir;
  }
Exemplo n.º 23
0
  public static void checkSanity() {
    long t = System.currentTimeMillis();

    try {
      r.lock();
      final int fileLength = (int) getRecords().length();
      assert fileLength % RECORD_SIZE == 0;
      int recordCount = fileLength / RECORD_SIZE;

      IntArrayList usedAttributeRecordIds = new IntArrayList();
      IntArrayList validAttributeIds = new IntArrayList();
      for (int id = 2; id < recordCount; id++) {
        int flags = getFlags(id);
        LOG.assertTrue(
            (flags & ~ALL_VALID_FLAGS) == 0,
            "Invalid flags: 0x" + Integer.toHexString(flags) + ", id: " + id);
        if ((flags & FREE_RECORD_FLAG) != 0) {
          LOG.assertTrue(
              DbConnection.myFreeRecords.contains(id),
              "Record, marked free, not in free list: " + id);
        } else {
          LOG.assertTrue(
              !DbConnection.myFreeRecords.contains(id),
              "Record, not marked free, in free list: " + id);
          checkRecordSanity(id, recordCount, usedAttributeRecordIds, validAttributeIds);
        }
      }
    } finally {
      r.unlock();
    }

    t = System.currentTimeMillis() - t;
    LOG.info("Sanity check took " + t + " ms");
  }
 private MouseOrTabletOperation(
     String name,
     String description,
     WorldPainterView view,
     int delay,
     boolean oneshot,
     String statisticsKey,
     String iconName) {
   super(
       name,
       description,
       (iconName != null) ? iconName : name.toLowerCase().replaceAll("\\s", ""));
   setView(view);
   this.delay = delay;
   this.oneShot = oneshot;
   this.statisticsKey = statisticsKey;
   statisticsKeyUndo = statisticsKey + ".undo";
   legacy =
       (SystemUtils.isMac() && System.getProperty("os.version").startsWith("10.4."))
           || "true"
               .equalsIgnoreCase(
                   System.getProperty("org.pepsoft.worldpainter.disableTabletSupport"));
   if (legacy) {
     logger.warn("Tablet support disabled for operation " + name);
   }
 }
    protected void preCache(List<Position> grid, Position centerPosition)
        throws InterruptedException {
      // Pre-cache the tiles that will be needed for the intersection calculations.
      double n = 0;
      final long start = System.currentTimeMillis();
      for (Position gridPos : grid) // for each grid point.
      {
        final double progress = 100 * (n++ / grid.size());
        terrain.cacheIntersectingTiles(centerPosition, gridPos);

        SwingUtilities.invokeLater(
            new Runnable() {
              public void run() {
                progressBar.setValue((int) progress);
                progressBar.setString(null);
              }
            });
      }

      SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              progressBar.setValue(100);
            }
          });

      long end = System.currentTimeMillis();
      System.out.printf(
          "Pre-caching time %d milliseconds, cache usage %f, tiles %d\n",
          end - start, terrain.getCacheUsage(), terrain.getNumCacheEntries());
    }
Exemplo n.º 26
0
 private static ArrayList<String> getArrayOfValues(String key) {
   ArrayList<String> stringArrayList = new ArrayList<>();
   try (BufferedReader br = new BufferedReader(new FileReader(CONFIG_FILE_LOCATION))) {
     for (String line; (line = br.readLine()) != null; ) {
       if (line.length() > 0) {
         if (line.charAt(0) != '#' && line.contains(key)) {
           String[] values = line.split("=");
           if (values.length == 2) {
             stringArrayList.add(values[1]);
           } else {
             infoBox("Value for ''" + key + "'' not defined\nProgram will exit!", "Error");
             System.exit(-2);
           }
         }
       }
     }
   } catch (IOException e) {
     infoBox(
         "Error reading config file. Save config file to C:\\config.conf and run program again.",
         "Error");
     e.printStackTrace();
     System.exit(1);
   }
   return stringArrayList;
 }
Exemplo n.º 27
0
  public static void main(String[] args) throws IOException {
    if (args.length != 1) {
      System.err.printf("Usage: DesignerApplication propertyFile\n");
      System.exit(-1);
    }

    Properties properties = parseProperties(args[0]);
    String repositoryFile = properties.getProperty("octopus.repository.file");
    if (repositoryFile == null || repositoryFile.length() == 0) {
      System.err.printf(
          "The property file %s is missing the octopus.repository.file property", args[0]);
      System.exit(-1);
    }

    OctopusRepository repository = new OctopusDb4oRepository(repositoryFile);
    LookAndFeelFactory.installDefaultLookAndFeelAndExtension();
    final DesignerFrame designerFrame = new DesignerFrame(repository);
    try {
      designerFrame.loadInitialDataFromRepository();

      SwingUtilities.invokeLater(
          new Runnable() {
            @Override
            public void run() {
              designerFrame.setVisible(true);
            }
          });
    } catch (RepositoryException e) {
      ErrorDialog.showErrorDialog(null, e, "Problem loading initial data from repository");
    }
  }
Exemplo n.º 28
0
 /** Trims all steps after endFrame. */
 protected void trimSteps() {
   // return if trimming not needed
   VideoClip clip = trackerPanel.getPlayer().getVideoClip();
   int n = clip.getFrameCount() - 1;
   int end = getEndFrame() == Integer.MAX_VALUE ? n : getEndFrame();
   while (end > getStartFrame() && !clip.includesFrame(end)) {
     end--;
   }
   if (end >= lastValidFrame) return;
   int trimCount = (tracePtsPerStep * (lastValidFrame - end)) / clip.getStepSize();
   ParticleModel[] models = getModels();
   for (ParticleModel next : models) {
     // create smaller trace arrays and copy existing points into them
     next.locked = false;
     int traceLength = next.traceX.length - trimCount;
     if (traceLength < 0) return; // trap for error during closing
     next.prevX = next.traceX;
     next.prevY = next.traceY;
     next.traceX = new double[traceLength];
     next.traceY = new double[traceLength];
     System.arraycopy(next.prevX, 0, next.traceX, 0, traceLength);
     System.arraycopy(next.prevY, 0, next.traceY, 0, traceLength);
     // reduce number of steps
     next.steps.setLength(end + 1);
     // refresh derivatives
     next.updateDerivatives(end - 2, lastValidFrame - end + 2);
     // restore state
     restoreState(end);
     next.support.firePropertyChange("steps", null, null); // $NON-NLS-1$
     next.locked = true;
   }
   lastValidFrame = end;
   repaint();
   //		trackerPanel.repaint();
 }
Exemplo n.º 29
0
 public void initGame() {
   String cfgname = null;
   if (isApplet()) {
     cfgname = getParameter("configfile");
   } else {
     JFileChooser chooser = new JFileChooser();
     chooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
     chooser.setDialogTitle("Choose a config file");
     int returnVal = chooser.showOpenDialog(this);
     if (returnVal == JFileChooser.APPROVE_OPTION) {
       cfgname = chooser.getSelectedFile().getAbsolutePath();
     } else {
       System.exit(0);
     }
     // XXX read this as resource!
     // cfgname = "mygeneratedgame.appconfig";
   }
   gamecfg = new AppConfig("Game parameters", this, cfgname);
   gamecfg.loadFromFile();
   gamecfg.defineFields("gp_", "", "", "");
   gamecfg.saveToObject();
   initMotionPars();
   // unpause and copy settingswhen config window is closed
   gamecfg.setListener(
       new ActionListener() {
         public void actionPerformed(ActionEvent e) {
           start();
           requestGameFocus();
           initMotionPars();
         }
       });
   defineMedia("simplegeneratedgame.tbl");
   setFrameRate(35, 1);
 }
  @Override
  public void actionPerformed(ActionEvent AE) {
    if (AE.getSource() == CheckAll) {
      boolean Selection = CheckAll.isSelected();
      if (Selection) CheckAll.setText("Uncheck all");
      else CheckAll.setText("Check all");
      for (int i = 0; i < NumberOfCourses; i++) My[i].CourseCheckBox.setSelected(Selection);
    }

    if (AE.getSource() == DocButton)
      if (TempControll.ConnectionManagerObject.createConnection()) {

        new File(System.getProperty("user.home") + "/TermResultCalculator/StudentDocs/").mkdirs();
        if (gatherDataForDocument()) {
          if (TempControll.StudentPdfObject.createPDF(
              this.Roll, this.Session, this.Selected, this.Taken, this.Completed, this.GPA))
            JOptionPane.showMessageDialog(
                RPS,
                "Report created successfully at "
                    + System.getProperty("user.home")
                    + "/TermResultCalculator/StudentDocs/",
                "Success",
                JOptionPane.INFORMATION_MESSAGE);
          else
            JOptionPane.showMessageDialog(
                RPS, "Error while creating report.", "Error", JOptionPane.ERROR_MESSAGE);
        } else
          JOptionPane.showMessageDialog(
              RPS,
              "At least one course has to be selected.",
              "Error : No Selection",
              JOptionPane.ERROR_MESSAGE);
      }
  }