Example #1
0
    /**
     * Returns the minimum amount of space the layout needs.
     *
     * @param the Container for which this layout manager is being used
     * @return a Dimension object containing the layout's minimum size
     */
    public Dimension minimumLayoutSize(Container parent) {
      Dimension cpd;
      int cpWidth = 0;
      int cpHeight = 0;
      int mbWidth = 0;
      int mbHeight = 0;
      int tpWidth = 0;

      Insets i = parent.getInsets();
      JRootPane root = (JRootPane) parent;

      if (root.getContentPane() != null) {
        cpd = root.getContentPane().getMinimumSize();
      } else {
        cpd = root.getSize();
      }
      if (cpd != null) {
        cpWidth = cpd.width;
        cpHeight = cpd.height;
      }

      return new Dimension(
          Math.max(Math.max(cpWidth, mbWidth), tpWidth) + i.left + i.right,
          cpHeight + mbHeight + tpWidth + i.top + i.bottom);
    }
Example #2
0
    /**
     * Returns the amount of space the layout would like to have.
     *
     * @param the Container for which this layout manager is being used
     * @return a Dimension object containing the layout's preferred size
     */
    public Dimension preferredLayoutSize(Container parent) {
      Dimension cpd, tpd;
      int cpWidth = 0;
      int cpHeight = 0;
      int mbWidth = 0;
      int mbHeight = 0;
      int tpWidth = 0;
      Insets i = parent.getInsets();
      JRootPane root = (JRootPane) parent;

      if (root.getContentPane() != null) {
        cpd = root.getContentPane().getPreferredSize();
      } else {
        cpd = root.getSize();
      }
      if (cpd != null) {
        cpWidth = cpd.width;
        cpHeight = cpd.height;
      }

      if (root.getWindowDecorationStyle() != JRootPane.NONE
          && (root.getUI() instanceof RootPaneUI)) {
        JComponent titlePane = ((RootPaneUI) root.getUI()).getTitlePane();
        if (titlePane != null) {
          tpd = titlePane.getPreferredSize();
          if (tpd != null) {
            tpWidth = tpd.width;
          }
        }
      }

      return new Dimension(
          Math.max(Math.max(cpWidth, mbWidth), tpWidth) + i.left + i.right,
          cpHeight + mbHeight + tpWidth + i.top + i.bottom);
    }
Example #3
0
    /**
     * Returns the maximum amount of space the layout can use.
     *
     * @param the Container for which this layout manager is being used
     * @return a Dimension object containing the layout's maximum size
     */
    public Dimension maximumLayoutSize(Container target) {
      Dimension cpd;
      int cpWidth = Integer.MAX_VALUE;
      int cpHeight = Integer.MAX_VALUE;
      int mbWidth = Integer.MAX_VALUE;
      int mbHeight = Integer.MAX_VALUE;
      int tpWidth = Integer.MAX_VALUE;
      int tpHeight = Integer.MAX_VALUE;
      Insets i = target.getInsets();
      JRootPane root = (JRootPane) target;

      if (root.getContentPane() != null) {
        cpd = root.getContentPane().getMaximumSize();
        if (cpd != null) {
          cpWidth = cpd.width;
          cpHeight = cpd.height;
        }
      }

      int maxHeight = Math.max(Math.max(cpHeight, mbHeight), tpHeight);
      // Only overflows if 3 real non-MAX_VALUE heights, sum to > MAX_VALUE
      // Only will happen if sums to more than 2 billion units.  Not likely.
      if (maxHeight != Integer.MAX_VALUE) {
        maxHeight = cpHeight + mbHeight + tpHeight + i.top + i.bottom;
      }

      int maxWidth = Math.max(Math.max(cpWidth, mbWidth), tpWidth);
      // Similar overflow comment as above
      if (maxWidth != Integer.MAX_VALUE) {
        maxWidth += i.left + i.right;
      }

      return new Dimension(maxWidth, maxHeight);
    }
    /**
     * Returns the maximum amount of space the layout can use.
     *
     * @param the Container for which this layout manager is being used
     * @return a Dimension object containing the layout's maximum size
     */
    public Dimension maximumLayoutSize(Container target) {
      Dimension cpd, mbd, tpd;
      int cpWidth = Integer.MAX_VALUE;
      int cpHeight = Integer.MAX_VALUE;
      int mbWidth = Integer.MAX_VALUE;
      int mbHeight = Integer.MAX_VALUE;
      int tpWidth = Integer.MAX_VALUE;
      int tpHeight = Integer.MAX_VALUE;
      Insets i = target.getInsets();
      JRootPane root = (JRootPane) target;

      if (root.getContentPane() != null) {
        cpd = root.getContentPane().getMaximumSize();
        if (cpd != null) {
          cpWidth = cpd.width;
          cpHeight = cpd.height;
        }
      }

      if (root.getMenuBar() != null) {
        mbd = root.getMenuBar().getMaximumSize();
        if (mbd != null) {
          mbWidth = mbd.width;
          mbHeight = mbd.height;
        }
      }

      if (root.getWindowDecorationStyle() != JRootPane.NONE
          && (root.getUI() instanceof HokageRootPaneUI)) {
        JComponent titlePane = ((HokageRootPaneUI) root.getUI()).getTitlePane();
        if (titlePane != null) {
          tpd = titlePane.getMaximumSize();
          if (tpd != null) {
            tpWidth = tpd.width;
            tpHeight = tpd.height;
          }
        }
      }

      int maxHeight = Math.max(Math.max(cpHeight, mbHeight), tpHeight);
      // Only overflows if 3 real non-MAX_VALUE heights, sum to > MAX_VALUE
      // Only will happen if sums to more than 2 billion units.  Not likely.
      if (maxHeight != Integer.MAX_VALUE) {
        maxHeight = cpHeight + mbHeight + tpHeight + i.top + i.bottom;
      }

      int maxWidth = Math.max(Math.max(cpWidth, mbWidth), tpWidth);
      // Similar overflow comment as above
      if (maxWidth != Integer.MAX_VALUE) {
        maxWidth += i.left + i.right;
      }

      return new Dimension(maxWidth, maxHeight);
    }
Example #5
0
  /**
   * Returns a partial token.
   *
   * @param token input text
   * @param start start position
   * @param end end position
   * @return resulting text
   */
  public static byte[] subtoken(final byte[] token, final int start, final int end) {
    int s = Math.max(0, start);
    final int e = Math.min(end, token.length);
    if (s == 0 && e == token.length) return token;
    if (s >= e) return EMPTY;

    int t = Math.max(0, s - 4);
    for (; t != s && t < e; t += cl(token, t)) {
      if (t >= s) s = t;
    }
    for (; t < e; t += cl(token, t)) ;
    return Arrays.copyOfRange(token, s, t);
  }
Example #6
0
  /**
   * Check the length of an RSA key modulus/exponent to make sure it is not too short or long. Some
   * impls have their own min and max key sizes that may or may not match with a system defined
   * value.
   *
   * @param modulusLen the bit length of the RSA modulus.
   * @param exponent the RSA exponent
   * @param minModulusLen if > 0, check to see if modulusLen is at least this long, otherwise
   *     unused.
   * @param maxModulusLen caller will allow this max number of bits. Allow the smaller of the
   *     system-defined maximum and this param.
   * @throws InvalidKeyException if any of the values are unacceptable.
   */
  public static void checkKeyLengths(
      int modulusLen, BigInteger exponent, int minModulusLen, int maxModulusLen)
      throws InvalidKeyException {

    if ((minModulusLen > 0) && (modulusLen < (minModulusLen))) {
      throw new InvalidKeyException("RSA keys must be at least " + minModulusLen + " bits long");
    }

    // Even though our policy file may allow this, we don't want
    // either value (mod/exp) to be too big.

    int maxLen = Math.min(maxModulusLen, MAX_MODLEN);

    // If a RSAPrivateKey/RSAPublicKey, make sure the
    // modulus len isn't too big.
    if (modulusLen > maxLen) {
      throw new InvalidKeyException("RSA keys must be no longer than " + maxLen + " bits");
    }

    // If a RSAPublicKey, make sure the exponent isn't too big.
    if (restrictExpLen
        && (exponent != null)
        && (modulusLen > MAX_MODLEN_RESTRICT_EXP)
        && (exponent.bitLength() > MAX_RESTRICTED_EXPLEN)) {
      throw new InvalidKeyException(
          "RSA exponents can be no longer than "
              + MAX_RESTRICTED_EXPLEN
              + " bits "
              + " if modulus is greater than "
              + MAX_MODLEN_RESTRICT_EXP
              + " bits");
    }
  }
Example #7
0
  /**
   * Creates a byte array representation from the specified double value; inspired by Xavier Franc's
   * Qizx/open processor.
   *
   * @param dbl double value to be converted
   * @return byte array
   */
  public static byte[] token(final double dbl) {
    final byte[] b = tok(dbl);
    if (b != null) return b;

    final double a = Math.abs(dbl);
    return chopNumber(token(a >= 1e-6 && a < 1e6 ? DD.format(dbl) : SD.format(dbl)));
  }
    public void run() {
      try {
        if (myPreviousThread != null) myPreviousThread.join();
        Thread.sleep(delay);
        log("> run MouseMoveThread " + x + ", " + y);
        while (!hasFocus()) {
          Thread.sleep(1000);
        }
        int x1 = lastMouseX;
        int x2 = x;
        int y1 = lastMouseY;
        int y2 = y;
        // shrink range by 1 px on both ends
        // manually move this 1px to trip DND code
        if (x1 != x2) {
          int dx = x - lastMouseX;
          if (dx > 0) {
            x1 += 1;
            x2 -= 1;
          } else {
            x1 -= 1;
            x2 += 1;
          }
        }
        if (y1 != y2) {
          int dy = y - lastMouseY;
          if (dy > 0) {
            y1 += 1;
            y2 -= 1;
          } else {
            y1 -= 1;
            y2 += 1;
          }
        }
        robot.setAutoDelay(Math.max(duration / 100, 1));
        robot.mouseMove(x1, y1);
        int d = 100;
        for (int t = 0; t <= d; t++) {
          x1 =
              (int)
                  easeInOutQuad(
                      (double) t, (double) lastMouseX, (double) x2 - lastMouseX, (double) d);
          y1 =
              (int)
                  easeInOutQuad(
                      (double) t, (double) lastMouseY, (double) y2 - lastMouseY, (double) d);
          robot.mouseMove(x1, y1);
        }
        robot.mouseMove(x, y);
        lastMouseX = x;
        lastMouseY = y;
        robot.waitForIdle();
        robot.setAutoDelay(1);
      } catch (Exception e) {
        log("Bad parameters passed to mouseMove");
        e.printStackTrace();
      }

      log("< run MouseMoveThread");
    }
  /**
   * Computes CPU usage (fraction of 1.0) between <code>start[1]</code> and <code>end[1]</code> time
   * points [1.0 corresponds to 100% utilization of all processors].
   *
   * @throws IllegalArgumentException if start and end time points are less than #MIN_ELAPSED_TIME
   *     ms apart.
   * @throws IllegalArgumentException if either argument is null
   * @param start,end long[2]: [0] system time stamp, [1] process CPU time (as returned by
   *     makeCPUUsageSnapshot()).
   */
  public static double getProcessCPUUsage(long[] start, long[] end) {
    if (start == null) throw new IllegalArgumentException("null input: start");
    if (end == null) throw new IllegalArgumentException("null input: end");
    // if (end[0] < start[0] + MIN_ELAPSED_TIME) throw new IllegalArgumentException("end time must
    // be at least " + MIN_ELAPSED_TIME + " ms later than start time");
    end[0] = Math.max(end[0], start[0] + MIN_ELAPSED_TIME);

    return ((double) (end[1] - start[1])) / (double) (end[0] - start[0]);
  }
Example #10
0
 /**
  * Compares two tokens lexicographically.
  *
  * @param token first token
  * @param compare token to be compared
  * @return 0 if tokens are equal, negative if first token is smaller, positive if first token is
  *     bigger
  */
 public static int diff(final byte[] token, final byte[] compare) {
   final int tl = token.length;
   final int cl = compare.length;
   final int l = Math.min(tl, cl);
   for (int i = 0; i < l; ++i) {
     final int c = (token[i] & 0xFF) - (compare[i] & 0xFF);
     if (c != 0) return c;
   }
   return tl - cl;
 }
Example #11
0
 /**
  * Checks if the specified value equals a constant token.
  *
  * @param dbl value to be converted
  * @return byte array or zero, or {@code null}
  */
 private static byte[] tok(final double dbl) {
   if (dbl == Double.POSITIVE_INFINITY) return INF;
   if (dbl == Double.NEGATIVE_INFINITY) return NINF;
   if (dbl == 0) return 1 / dbl > 0 ? ZERO : MZERO;
   if (Double.isNaN(dbl)) return NAN;
   final double a = Math.abs(dbl);
   if (a < 1e6) {
     final int i = (int) dbl;
     if (i == dbl) return token(i);
   }
   return null;
 }
Example #12
0
  /**
   * Creates a byte array representation from the specified float value.
   *
   * @param flt float value to be converted
   * @return byte array
   */
  public static byte[] token(final float flt) {
    final byte[] b = tok(flt);
    if (b != null) return b;

    // not that brilliant here.. no chance for elegant code either
    // due to the nifty differences between Java and XQuery
    for (int i = 0; i < FLT.length; ++i) if (flt == FLT[i]) return FLTSTR[i];
    final float a = Math.abs(flt);
    final boolean small = a >= 1e-6f && a < 1e6f;
    String s1 = small ? DF.format(flt) : SF.format(flt);
    final String s2 = Float.toString(flt);
    if (s2.length() < s1.length() && (!s2.contains("E") || !small)) s1 = s2;
    return chopNumber(token(s1));
  }
 public void run() {
   try {
     if (myPreviousThread != null) myPreviousThread.join();
     Thread.sleep(delay);
     log("> run MouseWheelThread " + amount);
     while (!hasFocus()) {
       Thread.sleep(1000);
     }
     int dir = 1;
     if (System.getProperty("os.name").toUpperCase().indexOf("MAC") != -1) {
       // yay for Apple
       dir = -1;
     }
     robot.setAutoDelay(Math.max(duration / Math.abs(amount), 1));
     for (int i = 0; i < Math.abs(amount); i++) {
       robot.mouseWheel(amount > 0 ? dir : -dir);
     }
     robot.setAutoDelay(1);
   } catch (Exception e) {
     log("Bad parameters passed to mouseWheel");
     e.printStackTrace();
   }
   log("< run MouseWheelThread ");
 }
Example #14
0
  /**
   * Returns a string of the specified UTF8 token.
   *
   * @param token token
   * @param start start position
   * @param length length
   * @return string
   */
  private static String utf8(final byte[] token, final int start, final int length) {
    // input is assumed to be correct UTF8. if input contains codepoints
    // larger than Character.MAX_CODE_POINT, results might be unexpected.

    final StringBuilder sb = new StringBuilder(length << 1);
    final int il = Math.min(start + length, token.length);
    for (int i = start; i < il; i += cl(token, i)) {
      final int cp = cp(token, i);
      if (cp < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
        sb.append((char) cp);
      } else {
        final int o = cp - Character.MIN_SUPPLEMENTARY_CODE_POINT;
        sb.append((char) ((o >>> 10) + Character.MIN_HIGH_SURROGATE));
        sb.append((char) ((o & 0x3ff) + Character.MIN_LOW_SURROGATE));
      }
    }
    return sb.toString();
  }
Example #15
0
  /**
   * Compute the hash an IP address. The hash is the first 8 bytes of the SHA digest of the IP
   * address.
   */
  private static byte[] computeAddressHash() {

    /*
     * Get the local host's IP address.
     */
    byte[] addr =
        (byte[])
            java.security.AccessController.doPrivileged(
                new PrivilegedAction() {
                  public Object run() {
                    try {
                      return InetAddress.getLocalHost().getAddress();
                    } catch (Exception e) {
                    }
                    return new byte[] {0, 0, 0, 0};
                  }
                });

    byte[] addrHash;
    final int ADDR_HASH_LENGTH = 8;

    try {
      /*
       * Calculate message digest of IP address using SHA.
       */
      MessageDigest md = MessageDigest.getInstance("SHA");
      ByteArrayOutputStream sink = new ByteArrayOutputStream(64);
      DataOutputStream out = new DataOutputStream(new DigestOutputStream(sink, md));
      out.write(addr, 0, addr.length);
      out.flush();

      byte digest[] = md.digest();
      int hashlength = Math.min(ADDR_HASH_LENGTH, digest.length);
      addrHash = new byte[hashlength];
      System.arraycopy(digest, 0, addrHash, 0, hashlength);

    } catch (IOException ignore) {
      /* can't happen, but be deterministic anyway. */
      addrHash = new byte[0];
    } catch (NoSuchAlgorithmException complain) {
      throw new InternalError(complain.toString());
    }
    return addrHash;
  }
 /**
  * Method returns a digital signature. It finds the RSA private key object from the active token
  * and then signs the given data with this key and RSA mechanism.
  *
  * @param digest digest of the data to be signed.
  * @param token token index
  * @param passwd users pin code or in case of pkcs12 file password
  * @param sig Signature object to provide info about desired signature method
  * @return an array of bytes containing digital signature.
  * @throws DigiDocException if signing the data fails.
  */
 public byte[] sign(byte[] xml, int token, String passwd, Signature sig) throws DigiDocException {
   try {
     if (m_keyStore == null)
       throw new DigiDocException(
           DigiDocException.ERR_NOT_INITED, "Keystore not initialized", null);
     String alias = getTokenName(token);
     if (alias == null)
       throw new DigiDocException(
           DigiDocException.ERR_TOKEN_LOGIN, "Invalid token nr: " + token, null);
     // get key
     if (m_logger.isDebugEnabled())
       m_logger.debug(
           "loading key: " + alias + " passwd-len: " + ((passwd != null) ? passwd.length() : 0));
     Key key = m_keyStore.getKey(alias, passwd.toCharArray());
     if (m_logger.isDebugEnabled())
       m_logger.debug("Key: " + ((key != null) ? "OK, algorithm: " + key.getAlgorithm() : "NULL"));
     if (key == null)
       throw new DigiDocException(
           DigiDocException.ERR_TOKEN_LOGIN, "Invalid password for token nr: " + token, null);
     String sigMeth = null;
     if (sig != null
         && sig.getSignedInfo() != null
         && sig.getSignedInfo().getSignatureMethod() != null)
       sigMeth = sig.getSignedInfo().getSignatureMethod();
     if (m_logger.isDebugEnabled())
       m_logger.debug("Signing\n---\n" + new String(xml) + "\n---\n method: " + sigMeth);
     java.security.Signature instance = sigMeth2SigSignatureInstance(sig, key);
     if (m_logger.isDebugEnabled())
       m_logger.debug("Signature instance: " + ((instance != null) ? "OK" : "NULL"));
     instance.initSign((PrivateKey) key);
     instance.update(xml);
     byte[] signature = instance.sign();
     boolean bEcCvcKey = isCvcEcKey(sig);
     if (m_logger.isDebugEnabled())
       m_logger.debug(
           "Signature algorithm: "
               + key.getAlgorithm()
               + " siglen: "
               + signature.length
               + " ec-key: "
               + bEcCvcKey);
     if (bEcCvcKey) {
       int nKeyLen = ((ECPrivateKey) key).getParams().getCurve().getField().getFieldSize();
       int nReqLen = ((int) Math.ceil((double) nKeyLen / 8)) * 2;
       int nSigLen = signature.length;
       if (m_logger.isDebugEnabled())
         m_logger.debug("EC Signature length: " + nSigLen + " required: " + nReqLen);
       if (nSigLen < nReqLen) {
         if (m_logger.isDebugEnabled())
           m_logger.debug("Padding EC signature length: " + nSigLen + " to required: " + nReqLen);
         byte[] padsig = new byte[nReqLen];
         System.arraycopy(signature, 0, padsig, (nReqLen - nSigLen) / 2, nSigLen / 2);
         System.arraycopy(
             signature, nSigLen / 2, padsig, (nReqLen / 2) + (nReqLen - nSigLen) / 2, nSigLen / 2);
         signature = padsig;
       }
     }
     if (m_logger.isDebugEnabled() && signature != null)
       m_logger.debug(
           "Signature len: "
               + signature.length
               + "\n---\n sig: "
               + ConvertUtils.bin2hex(signature));
     return signature;
   } catch (DigiDocException ex) {
     m_logger.error("DigiDoc Error signing: " + ex);
     throw ex;
   } catch (Exception ex) {
     m_logger.error("Error signing: " + ex);
   }
   return null;
 }
 /**
  * Parses the given text into a Java class capable of being run
  *
  * @param text the text of the script/class to parse
  * @return the main class defined in the given script
  */
 public Class parseClass(String text) throws CompilationFailedException {
   return parseClass(
       text, "script" + System.currentTimeMillis() + Math.abs(text.hashCode()) + ".groovy");
 }
Example #18
0
 /**
  * Returns a substring of the specified token. Note that this method does not correctly split UTF8
  * character; use {@link #subtoken} instead.
  *
  * @param token input token
  * @param start start position
  * @param end end position
  * @return substring
  */
 public static byte[] substring(final byte[] token, final int start, final int end) {
   final int s = Math.max(0, start);
   final int e = Math.min(end, token.length);
   if (s == 0 && e == token.length) return token;
   return s >= e ? EMPTY : Arrays.copyOfRange(token, s, e);
 }
Example #19
0
 /**
  * Calculates a hash code for the specified token.
  *
  * @param token specified token
  * @return hash code
  */
 public static int hash(final byte[] token) {
   int h = 0;
   final int l = Math.min(token.length, MAXLENGTH);
   for (int i = 0; i != l; ++i) h = (h << 5) - h + token[i];
   return h;
 }
Example #20
0
  public static boolean showLicensing() {
    if (Config.getLicenseResource() == null) return true;
    ClassLoader cl = Main.class.getClassLoader();
    URL url = cl.getResource(Config.getLicenseResource());
    if (url == null) return true;

    String license = null;
    try {
      URLConnection con = url.openConnection();
      int size = con.getContentLength();
      byte[] content = new byte[size];
      InputStream in = new BufferedInputStream(con.getInputStream());
      in.read(content);
      license = new String(content);
    } catch (IOException ioe) {
      Config.trace("Got exception when reading " + Config.getLicenseResource() + ": " + ioe);
      return false;
    }

    // Build dialog
    JTextArea ta = new JTextArea(license);
    ta.setEditable(false);
    final JDialog jd = new JDialog(_installerFrame, true);
    Container comp = jd.getContentPane();
    jd.setTitle(Config.getLicenseDialogTitle());
    comp.setLayout(new BorderLayout(10, 10));
    comp.add(new JScrollPane(ta), "Center");
    Box box = new Box(BoxLayout.X_AXIS);
    box.add(box.createHorizontalStrut(10));
    box.add(new JLabel(Config.getLicenseDialogQuestionString()));
    box.add(box.createHorizontalGlue());
    JButton acceptButton = new JButton(Config.getLicenseDialogAcceptString());
    JButton exitButton = new JButton(Config.getLicenseDialogExitString());
    box.add(acceptButton);
    box.add(box.createHorizontalStrut(10));
    box.add(exitButton);
    box.add(box.createHorizontalStrut(10));
    jd.getRootPane().setDefaultButton(acceptButton);
    Box box2 = new Box(BoxLayout.Y_AXIS);
    box2.add(box);
    box2.add(box2.createVerticalStrut(5));
    comp.add(box2, "South");
    jd.pack();

    final boolean accept[] = new boolean[1];
    acceptButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            accept[0] = true;
            jd.hide();
            jd.dispose();
          }
        });

    exitButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            accept[0] = false;
            jd.hide();
            jd.dispose();
          }
        });

    // Apply any defaults the user may have, constraining to the size
    // of the screen, and default (packed) size.
    Rectangle size = new Rectangle(0, 0, 500, 300);
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    size.width = Math.min(screenSize.width, size.width);
    size.height = Math.min(screenSize.height, size.height);
    // Center the window
    jd.setBounds(
        (screenSize.width - size.width) / 2,
        (screenSize.height - size.height) / 2,
        size.width,
        size.height);

    // Show dialog
    jd.show();

    return accept[0];
  }
Example #21
0
  //
  // Build installer window
  //
  public static void showInstallerWindow() {
    _installerFrame = new JFrame(Config.getWindowTitle());

    Container cont = _installerFrame.getContentPane();
    cont.setLayout(new BorderLayout());

    // North pane
    Box topPane = new Box(BoxLayout.X_AXIS);
    JLabel title = new JLabel(Config.getWindowHeading());
    Font titleFont = new Font("SansSerif", Font.BOLD, 22);
    title.setFont(titleFont);
    title.setForeground(Color.black);

    // Create Sun logo
    URL urlLogo = Main.class.getResource(Config.getWindowLogo());
    Image img = Toolkit.getDefaultToolkit().getImage(urlLogo);
    MediaTracker md = new MediaTracker(_installerFrame);
    md.addImage(img, 0);
    try {
      md.waitForAll();
    } catch (Exception ioe) {
      Config.trace(ioe.toString());
    }
    if (md.isErrorID(0)) Config.trace("Error loading image");
    Icon sunLogo = new ImageIcon(img);
    JLabel logoLabel = new JLabel(sunLogo);
    logoLabel.setOpaque(true);
    topPane.add(topPane.createHorizontalStrut(5));
    topPane.add(title);
    topPane.add(topPane.createHorizontalGlue());
    topPane.add(logoLabel);
    topPane.add(topPane.createHorizontalStrut(5));

    // West Pane
    Box westPane = new Box(BoxLayout.X_AXIS);
    westPane.add(westPane.createHorizontalStrut(10));

    // South Pane
    Box bottomPane = new Box(BoxLayout.X_AXIS);
    bottomPane.add(bottomPane.createHorizontalGlue());
    JButton abortButton = new JButton(Config.getWindowAbortButton());
    abortButton.setMnemonic(Config.getWindowAbortMnemonic());
    bottomPane.add(abortButton);
    bottomPane.add(bottomPane.createHorizontalGlue());
    bottomPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0));

    // Center Pane
    Box centerPane = new Box(BoxLayout.Y_AXIS);
    JLabel hidden = new JLabel(Config.getWindowHiddenLabel());
    hidden.setVisible(false);
    centerPane.add(hidden);
    _stepLabels = new JLabel[5];
    for (int i = 0; i < _stepLabels.length; i++) {
      _stepLabels[i] = new JLabel(Config.getWindowStep(i));
      _stepLabels[i].setEnabled(false);
      centerPane.add(_stepLabels[i]);

      // install label's length will expand,so set a longer size.
      if (i == STEP_INSTALL) {
        Dimension dim = new JLabel(Config.getWindowStepWait(STEP_INSTALL)).getPreferredSize();
        _stepLabels[i].setPreferredSize(dim);
      }
    }
    hidden = new JLabel(Config.getWindowHiddenLabel());
    hidden.setVisible(false);
    centerPane.add(hidden);

    // Setup box layout
    cont.add(topPane, "North");
    cont.add(westPane, "West");
    cont.add(bottomPane, "South");
    cont.add(centerPane, "Center");

    _installerFrame.pack();
    Dimension dim = _installerFrame.getSize();

    // hard code to ensure title is completely visible on Sol/lin.
    if (dim.width < 400) {
      dim.width = 400;
      _installerFrame.setSize(dim);
    }

    Rectangle size = _installerFrame.getBounds();
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    size.width = Math.min(screenSize.width, size.width);
    size.height = Math.min(screenSize.height, size.height);
    // Put window at 1/4, 1/4 of screen resoluion
    _installerFrame.setBounds(
        (screenSize.width - size.width) / 4,
        (screenSize.height - size.height) / 4,
        size.width,
        size.height);

    // Setup event listners
    _installerFrame.addWindowListener(
        new WindowAdapter() {
          public void windowClosing(WindowEvent we) {
            installFailed("Window closed", null);
          }
        });

    abortButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent ae) {
            installFailed("Abort pressed", null);
          }
        });

    // Show window
    _installerFrame.show();
  }
Example #22
0
  // Uses supplied hash algorithm
  static byte[] derive(
      char[] chars, byte[] salt, int ic, int n, int type, String hashAlgo, int blockLength) {

    // Add in trailing NULL terminator.  Special case:
    // no terminator if password is "\0".
    int length = chars.length * 2;
    if (length == 2 && chars[0] == 0) {
      chars = new char[0];
      length = 0;
    } else {
      length += 2;
    }

    byte[] passwd = new byte[length];
    for (int i = 0, j = 0; i < chars.length; i++, j += 2) {
      passwd[j] = (byte) ((chars[i] >>> 8) & 0xFF);
      passwd[j + 1] = (byte) (chars[i] & 0xFF);
    }
    byte[] key = new byte[n];

    try {
      MessageDigest sha = MessageDigest.getInstance(hashAlgo);

      int v = blockLength;
      int u = sha.getDigestLength();
      int c = roundup(n, u) / u;
      byte[] D = new byte[v];
      int s = roundup(salt.length, v);
      int p = roundup(passwd.length, v);
      byte[] I = new byte[s + p];

      Arrays.fill(D, (byte) type);
      concat(salt, I, 0, s);
      concat(passwd, I, s, p);

      byte[] Ai;
      byte[] B = new byte[v];
      byte[] tmp = new byte[v];

      int i = 0;
      for (; ; i++, n -= u) {
        sha.update(D);
        sha.update(I);
        Ai = sha.digest();
        for (int r = 1; r < ic; r++) Ai = sha.digest(Ai);
        System.arraycopy(Ai, 0, key, u * i, Math.min(n, u));
        if (i + 1 == c) break;
        concat(Ai, B, 0, B.length);
        BigInteger B1;
        B1 = new BigInteger(1, B).add(BigInteger.ONE);

        for (int j = 0; j < I.length; j += v) {
          BigInteger Ij;
          int trunc;

          if (tmp.length != v) tmp = new byte[v];
          System.arraycopy(I, j, tmp, 0, v);
          Ij = new BigInteger(1, tmp);
          Ij = Ij.add(B1);
          tmp = Ij.toByteArray();
          trunc = tmp.length - v;
          if (trunc >= 0) {
            System.arraycopy(tmp, trunc, I, j, v);
          } else if (trunc < 0) {
            Arrays.fill(I, j, j + (-trunc), (byte) 0);
            System.arraycopy(tmp, 0, I, j + (-trunc), tmp.length);
          }
        }
      }
    } catch (Exception e) {
      throw new RuntimeException("internal error: " + e);
    }
    return key;
  }