Esempio n. 1
0
  private boolean findEntry() {
    Cursor waitCursor = shell.getDisplay().getSystemCursor(SWT.CURSOR_WAIT);
    shell.setCursor(waitCursor);

    boolean matchCase = searchDialog.getMatchCase();
    boolean matchWord = searchDialog.getMatchWord();
    String searchString = searchDialog.getSearchString();
    int column = searchDialog.getSelectedSearchArea();

    searchString = matchCase ? searchString : searchString.toLowerCase();

    boolean found = false;
    if (searchDialog.getSearchDown()) {
      for (int i = table.getSelectionIndex() + 1; i < table.getItemCount(); i++) {
        if (found = findMatch(searchString, table.getItem(i), column, matchWord, matchCase)) {
          table.setSelection(i);
          break;
        }
      }
    } else {
      for (int i = table.getSelectionIndex() - 1; i > -1; i--) {
        if (found = findMatch(searchString, table.getItem(i), column, matchWord, matchCase)) {
          table.setSelection(i);
          break;
        }
      }
    }

    shell.setCursor(null);

    return found;
  }
Esempio n. 2
0
 public static void main(String[] args) {
   Display display = new Display();
   AddressBook application = new AddressBook();
   Shell shell = application.open(display);
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) display.sleep();
   }
   display.dispose();
 }
Esempio n. 3
0
  public Shell open(Display display) {
    shell = new Shell(display);
    shell.setLayout(new FillLayout());
    shell.addShellListener(
        new ShellAdapter() {
          @Override
          public void shellClosed(ShellEvent e) {
            e.doit = closeAddressBook();
          }
        });

    createMenuBar();

    searchDialog = new SearchDialog(shell);
    searchDialog.setSearchAreaNames(columnNames);
    searchDialog.setSearchAreaLabel(resAddressBook.getString("Column"));
    searchDialog.addFindListener(
        new FindListener() {
          public boolean find() {
            return findEntry();
          }
        });

    table = new Table(shell, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION);
    table.setHeaderVisible(true);
    table.setMenu(createPopUpMenu());
    table.addSelectionListener(
        new SelectionAdapter() {
          @Override
          public void widgetDefaultSelected(SelectionEvent e) {
            TableItem[] items = table.getSelection();
            if (items.length > 0) editEntry(items[0]);
          }
        });
    for (int i = 0; i < columnNames.length; i++) {
      TableColumn column = new TableColumn(table, SWT.NONE);
      column.setText(columnNames[i]);
      column.setWidth(150);
      final int columnIndex = i;
      column.addSelectionListener(
          new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
              sort(columnIndex);
            }
          });
    }

    newAddressBook();

    shell.setSize(table.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, 300);
    shell.open();
    return shell;
  }
 public static void main(String[] args) {
   Display display = new Display();
   MessageWindow application = new MessageWindow();
   Shell shell = application.open(display);
   if (args.length != 0) {
     application.openAddressBook(args[0]);
   }
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) display.sleep();
   }
   display.dispose();
 }
 /** Invokes as a standalone program. */
 public static void main(String[] args) {
   Display display = new Display();
   Shell shell = new Shell(display, SWT.SHELL_TRIM);
   shell.setLayout(new FillLayout());
   ControlExample instance = new ControlExample(shell);
   shell.setText(getResourceString("window.title"));
   setShellSize(instance, shell);
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) display.sleep();
   }
   instance.dispose();
   display.dispose();
 }
  private boolean save() {
    if (file == null) return saveAs();

    Cursor waitCursor = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT);
    shell.setCursor(waitCursor);

    TableItem[] items = table.getItems();
    String[] lines = new String[items.length];
    for (int i = 0; i < items.length; i++) {
      String[] itemText = new String[table.getColumnCount()];
      for (int j = 0; j < itemText.length; j++) {
        itemText[j] = items[i].getText(j);
      }
      lines[i] = encodeLine(itemText);
    }

    FileWriter fileWriter = null;
    try {
      fileWriter = new FileWriter(file.getAbsolutePath(), false);
      for (int i = 0; i < lines.length; i++) {
        fileWriter.write(lines[i]);
      }
    } catch (FileNotFoundException e) {
      displayError(resMessages.getString("File_not_found") + "\n" + file.getName());
      return false;
    } catch (IOException e) {
      displayError(resMessages.getString("IO_error_write") + "\n" + file.getName());
      return false;
    } finally {
      shell.setCursor(null);
      waitCursor.dispose();

      if (fileWriter != null) {
        try {
          fileWriter.close();
        } catch (IOException e) {
          displayError(resMessages.getString("IO_error_close") + "\n" + file.getName());
          return false;
        }
      }
    }

    shell.setText(resMessages.getString("Title_bar") + file.getName());
    isModified = false;
    return true;
  }
Esempio n. 7
0
  /**
   * Creates the menu at the top of the shell where most of the programs functionality is accessed.
   *
   * @return The <code>Menu</code> widget that was created
   */
  private Menu createMenuBar() {
    Menu menuBar = new Menu(shell, SWT.BAR);
    shell.setMenuBar(menuBar);

    // create each header and subMenu for the menuBar
    createFileMenu(menuBar);
    createEditMenu(menuBar);
    createSearchMenu(menuBar);
    createHelpMenu(menuBar);

    return menuBar;
  }
Esempio n. 8
0
 public static void main(String[] args) {
   Display display = Display.getDefault();
   Shell shell = new Shell(display);
   @SuppressWarnings("unused")
   MainWindow inst = new MainWindow(shell, SWT.NULL);
   shell.setLayout(new FillLayout());
   shell.setImage(SWTResourceManager.getImage("images/16x16.png"));
   shell.setText("Change This Title");
   shell.setBackgroundImage(SWTResourceManager.getImage("images/ToolbarBackground.gif"));
   shell.layout();
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) display.sleep();
   }
 }
Esempio n. 9
0
  private boolean closeAddressBook() {
    if (isModified) {
      // ask user if they want to save current address book
      MessageBox box = new MessageBox(shell, SWT.ICON_WARNING | SWT.YES | SWT.NO | SWT.CANCEL);
      box.setText(shell.getText());
      box.setMessage(resAddressBook.getString("Close_save"));

      int choice = box.open();
      if (choice == SWT.CANCEL) {
        return false;
      } else if (choice == SWT.YES) {
        if (!save()) return false;
      }
    }

    TableItem[] items = table.getItems();
    for (int i = 0; i < items.length; i++) {
      items[i].dispose();
    }

    return true;
  }
Esempio n. 10
0
  private void openAddressBook() {
    FileDialog fileDialog = new FileDialog(shell, SWT.OPEN);

    fileDialog.setFilterExtensions(new String[] {"*.adr;", "*.*"});
    fileDialog.setFilterNames(
        new String[] {
          resAddressBook.getString("Book_filter_name") + " (*.adr)",
          resAddressBook.getString("All_filter_name") + " (*.*)"
        });
    String name = fileDialog.open();

    if (name == null) return;
    File file = new File(name);
    if (!file.exists()) {
      displayError(
          resAddressBook.getString("File")
              + file.getName()
              + " "
              + resAddressBook.getString("Does_not_exist"));
      return;
    }

    Cursor waitCursor = shell.getDisplay().getSystemCursor(SWT.CURSOR_WAIT);
    shell.setCursor(waitCursor);

    FileReader fileReader = null;
    BufferedReader bufferedReader = null;
    String[] data = new String[0];
    try {
      fileReader = new FileReader(file.getAbsolutePath());
      bufferedReader = new BufferedReader(fileReader);
      String nextLine = bufferedReader.readLine();
      while (nextLine != null) {
        String[] newData = new String[data.length + 1];
        System.arraycopy(data, 0, newData, 0, data.length);
        newData[data.length] = nextLine;
        data = newData;
        nextLine = bufferedReader.readLine();
      }
    } catch (FileNotFoundException e) {
      displayError(resAddressBook.getString("File_not_found") + "\n" + file.getName());
      return;
    } catch (IOException e) {
      displayError(resAddressBook.getString("IO_error_read") + "\n" + file.getName());
      return;
    } finally {

      shell.setCursor(null);

      if (fileReader != null) {
        try {
          fileReader.close();
        } catch (IOException e) {
          displayError(resAddressBook.getString("IO_error_close") + "\n" + file.getName());
          return;
        }
      }
    }

    String[][] tableInfo = new String[data.length][table.getColumnCount()];
    int writeIndex = 0;
    for (int i = 0; i < data.length; i++) {
      String[] line = decodeLine(data[i]);
      if (line != null) tableInfo[writeIndex++] = line;
    }
    if (writeIndex != data.length) {
      String[][] result = new String[writeIndex][table.getColumnCount()];
      System.arraycopy(tableInfo, 0, result, 0, writeIndex);
      tableInfo = result;
    }
    Arrays.sort(tableInfo, new RowComparator(0));

    for (int i = 0; i < tableInfo.length; i++) {
      TableItem item = new TableItem(table, SWT.NONE);
      item.setText(tableInfo[i]);
    }
    shell.setText(resAddressBook.getString("Title_bar") + fileDialog.getFileName());
    isModified = false;
    this.file = file;
  }
Esempio n. 11
0
 private void newAddressBook() {
   shell.setText(resAddressBook.getString("Title_bar") + resAddressBook.getString("New_title"));
   file = null;
   isModified = false;
 }
  public Shell open(Display display) {

    // Window dressing - the icon
    windowIcon =
        new Image(display, getClass().getClassLoader().getResourceAsStream("icons/joanju.gif"));

    shell = new Shell(display);
    shell.setLayout(new FillLayout());
    shell.addShellListener(
        new ShellAdapter() {
          public void shellClosed(ShellEvent e) {
            e.doit = closeAddressBook();
          }
        });

    shell.setImage(windowIcon);

    createMenuBar();

    searchDialog = new SearchDialog(shell);
    searchDialog.setSearchAreaNames(columnNames);
    searchDialog.setSearchAreaLabel(resMessages.getString("Column"));
    searchDialog.addFindListener(
        new FindListener() {
          public boolean find() {
            return findEntry();
          }
        });

    table = new Table(shell, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION);
    table.setHeaderVisible(true);
    table.setMenu(createPopUpMenu());
    table.addSelectionListener(
        new SelectionAdapter() {
          public void widgetDefaultSelected(SelectionEvent e) {
            TableItem[] items = table.getSelection();
            if (items.length > 0) launchEditor(items[0]);
          }
        });
    int[] widths = {150, 50, 200, 200};
    for (int i = 0; i < columnNames.length; i++) {
      TableColumn column = new TableColumn(table, SWT.NONE);
      column.setText(columnNames[i]);
      column.setWidth(widths[i]);
      final int columnIndex = i;
      column.addSelectionListener(
          new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
              sort(columnIndex);
            }
          });
    }

    newAddressBook();

    shell.addDisposeListener(
        new DisposeListener() {
          public void widgetDisposed(DisposeEvent e) {
            windowIcon.dispose();
          }
        });

    shell.setSize(table.computeSize(SWT.DEFAULT, SWT.DEFAULT).x, 300);
    shell.open();
    return shell;
  }
  private void openAddressBook(String name) {
    if (name == null) return;
    File file = new File(name);
    if (!file.exists()) {
      displayError(
          resMessages.getString("File")
              + file.getName()
              + " "
              + resMessages.getString("Does_not_exist"));
      return;
    }

    Cursor waitCursor = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT);
    shell.setCursor(waitCursor);

    FileReader fileReader = null;
    BufferedReader bufferedReader = null;
    String[] data = new String[0];
    try {
      fileReader = new FileReader(file.getAbsolutePath());
      bufferedReader = new BufferedReader(fileReader);
      String nextLine = bufferedReader.readLine();
      while (nextLine != null) {
        String[] newData = new String[data.length + 1];
        System.arraycopy(data, 0, newData, 0, data.length);
        newData[data.length] = nextLine;
        data = newData;
        nextLine = bufferedReader.readLine();
      }
    } catch (FileNotFoundException e) {
      displayError(resMessages.getString("File_not_found") + "\n" + file.getName());
      return;
    } catch (IOException e) {
      displayError(resMessages.getString("IO_error_read") + "\n" + file.getName());
      return;
    } finally {

      shell.setCursor(null);
      waitCursor.dispose();

      if (fileReader != null) {
        try {
          fileReader.close();
        } catch (IOException e) {
          displayError(resMessages.getString("IO_error_close") + "\n" + file.getName());
          return;
        }
      }
    }

    String[][] tableInfo = new String[data.length][table.getColumnCount()];
    for (int i = 0; i < data.length; i++) {
      tableInfo[i] = decodeLine(data[i]);
    }

    Arrays.sort(tableInfo, new RowComparator(0));

    for (int i = 0; i < tableInfo.length; i++) {
      TableItem item = new TableItem(table, SWT.NONE);
      item.setText(tableInfo[i]);
    }
    shell.setText(resMessages.getString("Title_bar") + file.getName());
    isModified = false;
    this.file = file;
  }
Esempio n. 14
0
  public void tick() {
    timeLeft--;

    if (widthArrow < 0) {
      widthArrow *= -1;
      tipWidthArrow *= -1;

      xPositionsArrow =
          new int[] {
            xArrow + -widthArrow / 2,
            xArrow + widthArrow / 2 - tipWidthArrow,
            xArrow + widthArrow / 2 - tipWidthArrow,
            xArrow + widthArrow / 2,
            xArrow + widthArrow / 2 - tipWidthArrow,
            xArrow + widthArrow / 2 - tipWidthArrow,
            xArrow + -widthArrow / 2
          };
      yPositionsArrow =
          new int[] {
            yArrow + -heightArrow / 4,
            yArrow + -heightArrow / 4,
            yArrow + -heightArrow / 2,
            yArrow + 0,
            yArrow + heightArrow / 2,
            yArrow + heightArrow / 4,
            yArrow + heightArrow / 4
          };
    }

    if (timeLeft == 0) {
      mario.dieTime();
    }

    xCamO = xCam;
    yCamO = yCam;

    if (startTime > 0) {
      startTime++;
    }

    float targetXCam = mario.x - 160;

    xCam = targetXCam;

    if (xCam < 0) xCam = 0;
    if (xCam > level.getWidth() * 16 - 320) xCam = level.getWidth() * 16 - 320;

    /*      if (recorder != null)
    {
    recorder.addTick(mario.getKeyMask());
    }

    if (replayer!=null)
    {
    mario.setKeys(replayer.nextTick());
    }*/

    fireballsOnScreen = 0;

    for (Sprite sprite : sprites) {
      if (sprite != mario) {
        float xd = sprite.x - xCam;
        float yd = sprite.y - yCam;
        if (xd < -64 || xd > 320 + 64 || yd < -64 || yd > 240 + 64) {
          removeSprite(sprite);
        } else {
          if (sprite instanceof Fireball) {
            fireballsOnScreen++;
          }
        }
      }
    }

    if (paused) {
      for (Sprite sprite : sprites) {
        if (sprite == mario) {
          sprite.tick();
        } else {
          sprite.tickNoMove();
        }
      }
    } else {

      tick++;
      level.tick();

      boolean hasShotCannon = false;
      int xCannon = 0;

      for (int x = (int) xCam / 16 - 1; x <= (int) (xCam + layer.width) / 16 + 1; x++)
        for (int y = (int) yCam / 16 - 1; y <= (int) (yCam + layer.height) / 16 + 1; y++) {
          int dir = 0;

          if (x * 16 + 8 > mario.x + 16) dir = -1;
          if (x * 16 + 8 < mario.x - 16) dir = 1;

          SpriteTemplate st = level.getSpriteTemplate(x, y);

          if (st != null) {
            if (st.lastVisibleTick != tick - 1) {
              if (st.sprite == null || !sprites.contains(st.sprite)) {
                st.spawn(this, x, y, dir);
              }
            }

            st.lastVisibleTick = tick;
          }

          if (dir != 0) {
            byte b = level.getBlock(x, y);
            if (((Level.TILE_BEHAVIORS[b & 0xff]) & Level.BIT_ANIMATED) > 0) {
              if ((b % 16) / 4 == 3 && b / 16 == 0) {
                if ((tick - x * 2) % 100 == 0) {
                  xCannon = x;
                  for (int i = 0; i < 8; i++) {
                    addSprite(
                        new Sparkle(
                            x * 16 + 8,
                            y * 16 + (int) (Math.random() * 16),
                            (float) Math.random() * dir,
                            0,
                            0,
                            1,
                            5));
                  }
                  addSprite(new BulletBill(this, x * 16 + 8 + dir * 8, y * 16 + 15, dir));
                  hasShotCannon = true;
                }
              }
            }
          }
        }

      if (hasShotCannon) {
        sound.play(
            Art.samples[Art.SAMPLE_CANNON_FIRE],
            new FixedSoundSource(xCannon * 16, yCam + 120),
            1,
            1,
            1);
      }

      for (Sprite sprite : sprites) {
        sprite.tick();
      }

      for (Sprite sprite : sprites) {
        sprite.collideCheck();
      }

      for (Shell shell : shellsToCheck) {
        for (Sprite sprite : sprites) {
          if (sprite != shell && !shell.dead) {
            if (sprite.shellCollideCheck(shell)) {
              if (mario.carried == shell && !shell.dead) {
                mario.carried = null;
                shell.die();
              }
            }
          }
        }
      }
      shellsToCheck.clear();

      for (Fireball fireball : fireballsToCheck) {
        for (Sprite sprite : sprites) {
          if (sprite != fireball && !fireball.dead) {
            if (sprite.fireballCollideCheck(fireball)) {
              fireball.die();
            }
          }
        }
      }
      fireballsToCheck.clear();
    }

    sprites.addAll(0, spritesToAdd);
    sprites.removeAll(spritesToRemove);
    spritesToAdd.clear();
    spritesToRemove.clear();

    // TODO: THIS IS TEST FLIP
    //        if(keys[Mario.KEY_UP] && tick%2 == 0)
    //        	level.startFlipping = true;

    //        if(level.canFlip)
    //        	flip();
  }
Esempio n. 15
0
  @Override
  public final void run() {
    try {

      // before preparing the job localize
      // all the archives
      TaskAttemptID taskid = t.getTaskID();
      LocalDirAllocator lDirAlloc = new LocalDirAllocator("mapred.local.dir");
      File jobCacheDir = null;
      if (conf.getJar() != null) {
        jobCacheDir = new File(new Path(conf.getJar()).getParent().toString());
      }
      File workDir =
          new File(
              lDirAlloc
                  .getLocalPathToRead(
                      TaskTracker.getJobCacheSubdir()
                          + Path.SEPARATOR
                          + t.getJobID()
                          + Path.SEPARATOR
                          + t.getTaskID()
                          + Path.SEPARATOR
                          + MRConstants.WORKDIR,
                      conf)
                  .toString());

      URI[] archives = DistributedCache.getCacheArchives(conf);
      URI[] files = DistributedCache.getCacheFiles(conf);
      FileStatus fileStatus;
      FileSystem fileSystem;
      Path localPath;
      String baseDir;

      if ((archives != null) || (files != null)) {
        if (archives != null) {
          String[] archivesTimestamps = DistributedCache.getArchiveTimestamps(conf);
          Path[] p = new Path[archives.length];
          for (int i = 0; i < archives.length; i++) {
            fileSystem = FileSystem.get(archives[i], conf);
            fileStatus = fileSystem.getFileStatus(new Path(archives[i].getPath()));
            String cacheId = DistributedCache.makeRelative(archives[i], conf);
            String cachePath = TaskTracker.getCacheSubdir() + Path.SEPARATOR + cacheId;
            if (lDirAlloc.ifExists(cachePath, conf)) {
              localPath = lDirAlloc.getLocalPathToRead(cachePath, conf);
            } else {
              localPath = lDirAlloc.getLocalPathForWrite(cachePath, fileStatus.getLen(), conf);
            }
            baseDir = localPath.toString().replace(cacheId, "");
            p[i] =
                DistributedCache.getLocalCache(
                    archives[i],
                    conf,
                    new Path(baseDir),
                    fileStatus,
                    true,
                    Long.parseLong(archivesTimestamps[i]),
                    new Path(workDir.getAbsolutePath()),
                    false);
          }
          DistributedCache.setLocalArchives(conf, stringifyPathArray(p));
        }
        if ((files != null)) {
          String[] fileTimestamps = DistributedCache.getFileTimestamps(conf);
          Path[] p = new Path[files.length];
          for (int i = 0; i < files.length; i++) {
            fileSystem = FileSystem.get(files[i], conf);
            fileStatus = fileSystem.getFileStatus(new Path(files[i].getPath()));
            String cacheId = DistributedCache.makeRelative(files[i], conf);
            String cachePath = TaskTracker.getCacheSubdir() + Path.SEPARATOR + cacheId;
            if (lDirAlloc.ifExists(cachePath, conf)) {
              localPath = lDirAlloc.getLocalPathToRead(cachePath, conf);
            } else {
              localPath = lDirAlloc.getLocalPathForWrite(cachePath, fileStatus.getLen(), conf);
            }
            baseDir = localPath.toString().replace(cacheId, "");
            p[i] =
                DistributedCache.getLocalCache(
                    files[i],
                    conf,
                    new Path(baseDir),
                    fileStatus,
                    false,
                    Long.parseLong(fileTimestamps[i]),
                    new Path(workDir.getAbsolutePath()),
                    false);
          }
          DistributedCache.setLocalFiles(conf, stringifyPathArray(p));
        }
        Path localTaskFile = new Path(t.getJobFile());
        FileSystem localFs = FileSystem.getLocal(conf);
        localFs.delete(localTaskFile, true);
        OutputStream out = localFs.create(localTaskFile);
        try {
          conf.writeXml(out);
        } finally {
          out.close();
        }
      }

      if (!prepare()) {
        return;
      }

      String sep = System.getProperty("path.separator");
      StringBuffer classPath = new StringBuffer();
      // start with same classpath as parent process
      classPath.append(System.getProperty("java.class.path"));
      classPath.append(sep);
      if (!workDir.mkdirs()) {
        if (!workDir.isDirectory()) {
          LOG.fatal("Mkdirs failed to create " + workDir.toString());
        }
      }

      String jar = conf.getJar();
      if (jar != null) {
        // if jar exists, it into workDir
        File[] libs = new File(jobCacheDir, "lib").listFiles();
        if (libs != null) {
          for (int i = 0; i < libs.length; i++) {
            classPath.append(sep); // add libs from jar to classpath
            classPath.append(libs[i]);
          }
        }
        classPath.append(sep);
        classPath.append(new File(jobCacheDir, "classes"));
        classPath.append(sep);
        classPath.append(jobCacheDir);
      }

      // include the user specified classpath

      // archive paths
      Path[] archiveClasspaths = DistributedCache.getArchiveClassPaths(conf);
      if (archiveClasspaths != null && archives != null) {
        Path[] localArchives = DistributedCache.getLocalCacheArchives(conf);
        if (localArchives != null) {
          for (int i = 0; i < archives.length; i++) {
            for (int j = 0; j < archiveClasspaths.length; j++) {
              if (archives[i].getPath().equals(archiveClasspaths[j].toString())) {
                classPath.append(sep);
                classPath.append(localArchives[i].toString());
              }
            }
          }
        }
      }
      // file paths
      Path[] fileClasspaths = DistributedCache.getFileClassPaths(conf);
      if (fileClasspaths != null && files != null) {
        Path[] localFiles = DistributedCache.getLocalCacheFiles(conf);
        if (localFiles != null) {
          for (int i = 0; i < files.length; i++) {
            for (int j = 0; j < fileClasspaths.length; j++) {
              if (files[i].getPath().equals(fileClasspaths[j].toString())) {
                classPath.append(sep);
                classPath.append(localFiles[i].toString());
              }
            }
          }
        }
      }

      classPath.append(sep);
      classPath.append(workDir);
      //  Build exec child jmv args.
      Vector<String> vargs = new Vector<String>(8);
      File jvm = // use same jvm as parent
          new File(new File(System.getProperty("java.home"), "bin"), "java");

      vargs.add(jvm.toString());

      // Add child (task) java-vm options.
      //
      // The following symbols if present in mapred.child.java.opts value are
      // replaced:
      // + @taskid@ is interpolated with value of TaskID.
      // Other occurrences of @ will not be altered.
      //
      // Example with multiple arguments and substitutions, showing
      // jvm GC logging, and start of a passwordless JVM JMX agent so can
      // connect with jconsole and the likes to watch child memory, threads
      // and get thread dumps.
      //
      //  <property>
      //    <name>mapred.child.java.opts</name>
      //    <value>-verbose:gc -Xloggc:/tmp/@[email protected] \
      //           -Dcom.sun.management.jmxremote.authenticate=false \
      //           -Dcom.sun.management.jmxremote.ssl=false \
      //    </value>
      //  </property>
      //
      String javaOpts = conf.get("mapred.child.java.opts", "-Xmx200m");
      javaOpts = javaOpts.replace("@taskid@", taskid.toString());
      String[] javaOptsSplit = javaOpts.split(" ");

      // Add java.library.path; necessary for loading native libraries.
      //
      // 1. To support native-hadoop library i.e. libhadoop.so, we add the
      //    parent processes' java.library.path to the child.
      // 2. We also add the 'cwd' of the task to it's java.library.path to help
      //    users distribute native libraries via the DistributedCache.
      // 3. The user can also specify extra paths to be added to the
      //    java.library.path via mapred.child.java.opts.
      //
      String libraryPath = System.getProperty("java.library.path");
      if (libraryPath == null) {
        libraryPath = workDir.getAbsolutePath();
      } else {
        libraryPath += sep + workDir;
      }
      boolean hasUserLDPath = false;
      for (int i = 0; i < javaOptsSplit.length; i++) {
        if (javaOptsSplit[i].startsWith("-Djava.library.path=")) {
          javaOptsSplit[i] += sep + libraryPath;
          hasUserLDPath = true;
          break;
        }
      }
      if (!hasUserLDPath) {
        vargs.add("-Djava.library.path=" + libraryPath);
      }
      for (int i = 0; i < javaOptsSplit.length; i++) {
        vargs.add(javaOptsSplit[i]);
      }

      // add java.io.tmpdir given by mapred.child.tmp
      String tmp = conf.get("mapred.child.tmp", "./tmp");
      Path tmpDir = new Path(tmp);

      // if temp directory path is not absolute
      // prepend it with workDir.
      if (!tmpDir.isAbsolute()) {
        tmpDir = new Path(workDir.toString(), tmp);
      }
      FileSystem localFs = FileSystem.getLocal(conf);
      if (!localFs.mkdirs(tmpDir) && !localFs.getFileStatus(tmpDir).isDir()) {
        throw new IOException("Mkdirs failed to create " + tmpDir.toString());
      }
      vargs.add("-Djava.io.tmpdir=" + tmpDir.toString());

      // Add classpath.
      vargs.add("-classpath");
      vargs.add(classPath.toString());

      // Setup the log4j prop
      long logSize = TaskLog.getTaskLogLength(conf);
      vargs.add(
          "-Dhadoop.log.dir=" + new File(System.getProperty("hadoop.log.dir")).getAbsolutePath());
      vargs.add("-Dhadoop.root.logger=INFO,TLA");
      vargs.add("-Dhadoop.tasklog.taskid=" + taskid);
      vargs.add("-Dhadoop.tasklog.totalLogFileSize=" + logSize);

      if (conf.getProfileEnabled()) {
        if (conf.getProfileTaskRange(t.isMapTask()).isIncluded(t.getPartition())) {
          File prof = TaskLog.getTaskLogFile(taskid, TaskLog.LogName.PROFILE);
          vargs.add(String.format(conf.getProfileParams(), prof.toString()));
        }
      }

      // Add main class and its arguments
      vargs.add(Child.class.getName()); // main of Child
      // pass umbilical address
      InetSocketAddress address = tracker.getTaskTrackerReportAddress();
      vargs.add(address.getAddress().getHostAddress());
      vargs.add(Integer.toString(address.getPort()));
      vargs.add(taskid.toString()); // pass task identifier

      String pidFile = null;
      if (tracker.isTaskMemoryManagerEnabled()) {
        pidFile =
            lDirAlloc
                .getLocalPathForWrite(
                    (TaskTracker.getPidFilesSubdir() + Path.SEPARATOR + taskid), this.conf)
                .toString();
      }

      // set memory limit using ulimit if feasible and necessary ...
      String[] ulimitCmd = Shell.getUlimitMemoryCommand(conf);
      List<String> setup = null;
      if (ulimitCmd != null) {
        setup = new ArrayList<String>();
        for (String arg : ulimitCmd) {
          setup.add(arg);
        }
      }

      // Set up the redirection of the task's stdout and stderr streams
      File stdout = TaskLog.getTaskLogFile(taskid, TaskLog.LogName.STDOUT);
      File stderr = TaskLog.getTaskLogFile(taskid, TaskLog.LogName.STDERR);
      stdout.getParentFile().mkdirs();
      tracker.getTaskTrackerInstrumentation().reportTaskLaunch(taskid, stdout, stderr);

      Map<String, String> env = new HashMap<String, String>();
      StringBuffer ldLibraryPath = new StringBuffer();
      ldLibraryPath.append(workDir.toString());
      String oldLdLibraryPath = null;
      oldLdLibraryPath = System.getenv("LD_LIBRARY_PATH");
      if (oldLdLibraryPath != null) {
        ldLibraryPath.append(sep);
        ldLibraryPath.append(oldLdLibraryPath);
      }
      env.put("LD_LIBRARY_PATH", ldLibraryPath.toString());
      jvmManager.launchJvm(
          this,
          jvmManager.constructJvmEnv(
              setup, vargs, stdout, stderr, logSize, workDir, env, pidFile, conf));
      synchronized (lock) {
        while (!done) {
          lock.wait();
        }
      }
      tracker.getTaskTrackerInstrumentation().reportTaskEnd(t.getTaskID());
      if (exitCodeSet) {
        if (!killed && exitCode != 0) {
          if (exitCode == 65) {
            tracker.getTaskTrackerInstrumentation().taskFailedPing(t.getTaskID());
          }
          throw new IOException("Task process exit with nonzero status of " + exitCode + ".");
        }
      }
    } catch (FSError e) {
      LOG.fatal("FSError", e);
      try {
        tracker.fsError(t.getTaskID(), e.getMessage());
      } catch (IOException ie) {
        LOG.fatal(t.getTaskID() + " reporting FSError", ie);
      }
    } catch (Throwable throwable) {
      LOG.warn(t.getTaskID() + " Child Error", throwable);
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      throwable.printStackTrace(new PrintStream(baos));
      try {
        tracker.reportDiagnosticInfo(t.getTaskID(), baos.toString());
      } catch (IOException e) {
        LOG.warn(t.getTaskID() + " Reporting Diagnostics", e);
      }
    } finally {
      try {
        URI[] archives = DistributedCache.getCacheArchives(conf);
        URI[] files = DistributedCache.getCacheFiles(conf);
        if (archives != null) {
          for (int i = 0; i < archives.length; i++) {
            DistributedCache.releaseCache(archives[i], conf);
          }
        }
        if (files != null) {
          for (int i = 0; i < files.length; i++) {
            DistributedCache.releaseCache(files[i], conf);
          }
        }
      } catch (IOException ie) {
        LOG.warn("Error releasing caches : Cache files might not have been cleaned up");
      }
      tracker.reportTaskFinished(t.getTaskID(), false);
      if (t.isMapTask()) {
        tracker.addFreeMapSlot();
      } else {
        tracker.addFreeReduceSlot();
      }
    }
  }
 /**
  * Sets the size of the shell to it's "packed" size, unless that makes it larger than the monitor
  * it is being displayed on, in which case just set the shell size to be slightly smaller than the
  * monitor.
  */
 static void setShellSize(ControlExample instance, Shell shell) {
   Point size = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT);
   Rectangle monitorArea = shell.getMonitor().getClientArea();
   shell.setSize(Math.min(size.x, monitorArea.width), Math.min(size.y, monitorArea.height));
 }