/**
  * Writes the <code>shape</code>, <code>coords</code>, <code>href</code>,
  * <code>nohref</code> Attribute for the specified figure and ellipse.
  *
  * @return Returns true, if the circle is inside of the image bounds.
  */
 private boolean writeCircleAttributes(IXMLElement elem, SVGFigure f, Ellipse2D.Double ellipse) {
     AffineTransform t = TRANSFORM.getClone(f);
     if (t == null) {
         t = drawingTransform;
     } else {
         t.preConcatenate(drawingTransform);
     }
     
     if ((t.getType() &
             (AffineTransform.TYPE_UNIFORM_SCALE | AffineTransform.TYPE_TRANSLATION)) ==
             t.getType() &&
             ellipse.width == ellipse.height
             ) {
         
         Point2D.Double start = new Point2D.Double(ellipse.x, ellipse.y);
         Point2D.Double end = new Point2D.Double(ellipse.x + ellipse.width, ellipse.y + ellipse.height);
         t.transform(start, start);
         t.transform(end, end);
         ellipse.x = Math.min(start.x, end.x);
         ellipse.y = Math.min(start.y, end.y);
         ellipse.width = Math.abs(start.x - end.x);
         ellipse.height = Math.abs(start.y - end.y);
         
         elem.setAttribute("shape", "circle");
         elem.setAttribute("coords",
                 (int) (ellipse.x + ellipse.width / 2d)+","+
                 (int) (ellipse.y + ellipse.height / 2d)+","+
                 (int) (ellipse.width / 2d)
                 );
         writeHrefAttribute(elem, f);
         return bounds.intersects(ellipse.getBounds());
     } else {
         return writePolyAttributes(elem, f, (Shape) ellipse);
     }
 }
 protected void drawImageMosaic(Graphics2D g2) {
   // Break the image up into tiles. Draw each
   //   tile with its own transparency, allowing
   //   the background to show through to varying
   //   degrees.
   int side = 36;
   int width = mImage.getWidth();
   int height = mImage.getHeight();
   for (int y = 0; y < height; y += side) {
     for (int x = 0; x < width; x += side) {
       // Calculate an appropriate transparency value.
       float xBias = (float) x / (float) width;
       float yBias = (float) y / (float) height;
       float alpha = 1.0f - Math.abs(xBias - yBias);
       g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
       // Draw the subimage.
       int w = Math.min(side, width - x);
       int h = Math.min(side, height - y);
       BufferedImage tile = mImage.getSubimage(x, y, w, h);
       g2.drawImage(tile, x, y, null);
     }
   }
   // Reset the composite.
   g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
 }
  private void sendEntityBodyToClient(
      DataOutputStream socketOutputStream, HtmlResponse htmlResponse, boolean isChunked)
      throws IOException {

    byte[] content = htmlResponse.getEntityBody();

    if (!isChunked) {
      try {
        socketOutputStream.write(content, 0, content.length);
        socketOutputStream.flush();
      } catch (IOException e) {
        System.out.println("Writing the answer caused an error" + e.toString());
      }
    } else {

      int currentIndexStart = 0;
      int currentIndexEnd = Math.min(CHUNCKED_BYTES - 1, content.length - 1);
      int lengthOfBytesSent = currentIndexEnd - currentIndexStart + 1;

      while (currentIndexStart < content.length - 1) {
        socketOutputStream.writeBytes(Integer.toHexString(lengthOfBytesSent) + CRLF);
        socketOutputStream.write(content, currentIndexStart, lengthOfBytesSent);
        socketOutputStream.writeBytes(CRLF);
        socketOutputStream.flush();

        currentIndexStart = currentIndexEnd + 1;
        currentIndexEnd = Math.min(currentIndexStart + CHUNCKED_BYTES - 1, content.length - 1);
        lengthOfBytesSent = currentIndexEnd - currentIndexStart + 1;
      }

      socketOutputStream.writeBytes("0" + CRLF);
      socketOutputStream.writeBytes(CRLF);
      socketOutputStream.flush();
    }
  }
  /**
   * @param replica
   * @param externalizable
   * @param tcpReplicatorBuilder
   * @param maxEntrySizeBytes used to check that the last entry will fit into the buffer, it can not
   *     be smaller than the size of and entry, if it is set smaller the buffer will over flow, it
   *     can be larger then the entry, but setting it too large reduces the workable space in the
   *     buffer.
   * @throws IOException
   */
  TcpReplicator(
      @NotNull final Replica replica,
      @NotNull final EntryExternalizable externalizable,
      @NotNull final TcpReplicatorBuilder tcpReplicatorBuilder,
      final int maxEntrySizeBytes)
      throws IOException {

    super("TcpSocketReplicator-" + replica.identifier(), tcpReplicatorBuilder, maxEntrySizeBytes);

    serverInetSocketAddress = tcpReplicatorBuilder.serverInetSocketAddress();

    heartBeatInterval = tcpReplicatorBuilder.heartBeatInterval(MILLISECONDS);

    long throttleBucketInterval = tcpReplicatorBuilder.throttleBucketInterval(MILLISECONDS);
    selectorTimeout = Math.min(heartBeatInterval, throttleBucketInterval);

    packetSize = tcpReplicatorBuilder.packetSize();
    endpoints = tcpReplicatorBuilder.endpoints();

    this.replica = replica;
    this.localIdentifier = replica.identifier();
    this.maxEntrySizeBytes = maxEntrySizeBytes;
    this.externalizable = externalizable;

    start();
  }
Beispiel #5
0
 public int rate() {
   int score = 0;
   int cur = 1;
   for (int i = 0; i < properties.values.size(); i++) {
     score += 10000 - Math.min(10000, Math.abs((1 << i) - properties.values.get(i)));
   }
   return score;
 }
Beispiel #6
0
  /**
   * 访问服务器环境
   *
   * @param names 参数名字
   * @param values 参数值
   */
  public static void visitEnvServerByParameters(String[] names, String[] values) {
    int len = Math.min(ArrayUtils.getLength(names), ArrayUtils.getLength(values));
    String[] segs = new String[len];
    for (int i = 0; i < len; i++) {
      try {
        // 设计器里面据说为了改什么界面统一, 把分隔符统一用File.separator, 意味着在windows里面报表路径变成了\
        // 以前的超链, 以及预览url什么的都是/, 产品组的意思就是用到的地方替换下, 真恶心.
        String value = values[i].replaceAll("\\\\", "/");
        segs[i] =
            URLEncoder.encode(CodeUtils.cjkEncode(names[i]), EncodeConstants.ENCODING_UTF_8)
                + "="
                + URLEncoder.encode(CodeUtils.cjkEncode(value), "UTF-8");
      } catch (UnsupportedEncodingException e) {
        FRContext.getLogger().error(e.getMessage(), e);
      }
    }
    String postfixOfUri = (segs.length > 0 ? "?" + StableUtils.join(segs, "&") : StringUtils.EMPTY);

    if (FRContext.getCurrentEnv() instanceof RemoteEnv) {
      try {
        if (Utils.isEmbeddedParameter(postfixOfUri)) {
          String time = Calendar.getInstance().getTime().toString().replaceAll(" ", "");
          boolean isUserPrivilege =
              ((RemoteEnv) FRContext.getCurrentEnv()).writePrivilegeMap(time, postfixOfUri);
          postfixOfUri =
              isUserPrivilege
                  ? postfixOfUri
                      + "&fr_check_url="
                      + time
                      + "&id="
                      + FRContext.getCurrentEnv().getUserID()
                  : postfixOfUri;
        }

        String urlPath = getWebBrowserPath();
        Desktop.getDesktop().browse(new URI(urlPath + postfixOfUri));
      } catch (Exception e) {
        FRContext.getLogger().error("cannot open the url Successful", e);
      }
    } else {
      try {
        String web = GeneralContext.getCurrentAppNameOfEnv();
        String url =
            "http://localhost:"
                + DesignerEnvManager.getEnvManager().getJettyServerPort()
                + "/"
                + web
                + "/"
                + ConfigManager.getProviderInstance().getServletMapping()
                + postfixOfUri;
        StartServer.browerURLWithLocalEnv(url);
      } catch (Throwable e) {
        //
      }
    }
  }
Beispiel #7
0
 public static void hashpipe(InputStream is, OutputStream os, long len, MessageDigest md)
     throws IOException {
   byte[] buf = new byte[SMALL_BUFF];
   long read = 0;
   while (read < len) {
     int thisRead = is.read(buf, 0, (int) Math.min(SMALL_BUFF, len - read));
     read += thisRead;
     os.write(buf, 0, thisRead);
     md.update(buf, 0, thisRead);
   }
 }
 public long skip(long n) throws IOException {
   try {
     lock.getBusyFlag();
     int sizeskip = Math.min(reslen, (int) n);
     if (sizeskip > 0) {
       byte c[] = getChars(sizeskip);
     }
     return ((long) sizeskip);
   } finally {
     lock.freeBusyFlag();
   }
 }
Beispiel #9
0
    @Override
    @SuppressWarnings("SleepWhileHoldingLock")
    public void run() {
      try {
        // initialize the statusbar
        status.removeAll();
        JProgressBar progress = new JProgressBar();
        progress.setMinimum(0);
        progress.setMaximum(doc.getLength());
        status.add(progress);
        status.revalidate();

        // start writing
        Writer out = new FileWriter(f);
        Segment text = new Segment();
        text.setPartialReturn(true);
        int charsLeft = doc.getLength();
        int offset = 0;
        while (charsLeft > 0) {
          doc.getText(offset, Math.min(4096, charsLeft), text);
          out.write(text.array, text.offset, text.count);
          charsLeft -= text.count;
          offset += text.count;
          progress.setValue(offset);
          try {
            Thread.sleep(10);
          } catch (InterruptedException e) {
            Logger.getLogger(FileSaver.class.getName()).log(Level.SEVERE, null, e);
          }
        }
        out.flush();
        out.close();
      } catch (IOException e) {
        final String msg = e.getMessage();
        SwingUtilities.invokeLater(
            new Runnable() {

              public void run() {
                JOptionPane.showMessageDialog(
                    getFrame(),
                    "Could not save file: " + msg,
                    "Error saving file",
                    JOptionPane.ERROR_MESSAGE);
              }
            });
      } catch (BadLocationException e) {
        System.err.println(e.getMessage());
      }
      // we are done... get rid of progressbar
      status.removeAll();
      status.revalidate();
    }
 /**
  * All other write methods delegate their work to here.
  */
 public void write(OutputStream out, java.util.List<Figure> figures) throws IOException {
     Rectangle2D.Double drawingRect = null;
     
     for (Figure f : figures) {
         if (drawingRect == null) {
             drawingRect = f.getBounds();
         } else {
             drawingRect.add(f.getBounds());
         }
     }
     
     AffineTransform drawingTransform = new AffineTransform();
     drawingTransform.translate(
             -Math.min(0, drawingRect.x),
             -Math.min(0, drawingRect.y)
             );
     
     write(out, figures, drawingTransform,
             new Dimension(
             (int) (Math.abs(drawingRect.x) + drawingRect.width),
             (int) (Math.abs(drawingRect.y) + drawingRect.height))
             );
 }
Beispiel #11
0
 FoundItem getFoundItem(Node n, String text) {
   String s = n.getNodeValue();
   if (s == null) s = n.getNodeName();
   String string;
   if (text != null) {
     int index = s.indexOf(text);
     int left = Math.max(0, index - 5);
     int right = Math.min(s.length(), index + text.length() + 20);
     string = s.substring(left, right);
   } else string = s;
   TreeNode tn = jtree.getTreeNode(n);
   TreePath tp = getTreePath(tn);
   return new FoundItem(string, tp);
 }
 /**
  * Writes the <code>shape</code>, <code>coords</code>, <code>href</code>,
  * <code>nohref</code> Attribute for the specified figure and rectangle.
  *
  * @return Returns true, if the rect is inside of the image bounds.
  */
 private boolean writeRectAttributes(IXMLElement elem, SVGFigure f, Rectangle2D.Double rect) {
     AffineTransform t = TRANSFORM.getClone(f);
     if (t == null) {
         t = drawingTransform;
     } else {
         t.preConcatenate(drawingTransform);
     }
     
     if ((t.getType() &
             (AffineTransform.TYPE_UNIFORM_SCALE | AffineTransform.TYPE_TRANSLATION)) ==
             t.getType()
             ) {
         
         Point2D.Double start = new Point2D.Double(rect.x, rect.y);
         Point2D.Double end = new Point2D.Double(rect.x + rect.width, rect.y + rect.height);
         t.transform(start, start);
         t.transform(end, end);
         Rectangle r = new Rectangle(
                 (int) Math.min(start.x, end.x),
                 (int) Math.min(start.y, end.y),
                 (int) Math.abs(start.x - end.x),
                 (int) Math.abs(start.y - end.y)
                 );
         
         elem.setAttribute("shape", "rect");
         elem.setAttribute("coords",
                 r.x + ","+
                 r.y + ","+
                 (r.x + r.width) + ","+
                 (r.y + r.height)
                 );
         writeHrefAttribute(elem, f);
         return bounds.intersects(r);
     } else {
         return writePolyAttributes(elem, f, (Shape) rect);
     }
 }
  /**
   * Read block from file.
   *
   * @param file - File to read.
   * @param off - Marker position in file to start read from if {@code -1} read last blockSz bytes.
   * @param blockSz - Maximum number of chars to read.
   * @param lastModified - File last modification time.
   * @return Read file block.
   * @throws IOException In case of error.
   */
  public static VisorFileBlock readBlock(File file, long off, int blockSz, long lastModified)
      throws IOException {
    RandomAccessFile raf = null;

    try {
      long fSz = file.length();
      long fLastModified = file.lastModified();

      long pos = off >= 0 ? off : Math.max(fSz - blockSz, 0);

      // Try read more that file length.
      if (fLastModified == lastModified && fSz != 0 && pos >= fSz)
        throw new IOException(
            "Trying to read file block with wrong offset: " + pos + " while file size: " + fSz);

      if (fSz == 0)
        return new VisorFileBlock(file.getPath(), pos, fLastModified, 0, false, EMPTY_FILE_BUF);
      else {
        int toRead = Math.min(blockSz, (int) (fSz - pos));

        byte[] buf = new byte[toRead];

        raf = new RandomAccessFile(file, "r");

        raf.seek(pos);

        int cntRead = raf.read(buf, 0, toRead);

        if (cntRead != toRead)
          throw new IOException(
              "Count of requested and actually read bytes does not match [cntRead="
                  + cntRead
                  + ", toRead="
                  + toRead
                  + ']');

        boolean zipped = buf.length > 512;

        return new VisorFileBlock(
            file.getPath(), pos, fSz, fLastModified, zipped, zipped ? zipBytes(buf) : buf);
      }
    } finally {
      U.close(raf, null);
    }
  }
Beispiel #14
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;
  }
  public int read(byte b[], int off, int len) throws IOException {
    try {
      lock.getBusyFlag();
      while (reslen == 0) {
        try {
          if (EOF) return (-1);
          if (IOError != null) throw IOError;
          empty.cvWait();
        } catch (InterruptedException e) {
        }
      }

      int sizeread = Math.min(reslen, len);
      byte c[] = getChars(sizeread);
      System.arraycopy(c, 0, b, off, sizeread);
      return (sizeread);
    } finally {
      lock.freeBusyFlag();
    }
  }
Beispiel #16
0
 public static void sendFile(Socket sock, File in, byte[] hash)
     throws IOException, NoSuchAlgorithmException {
   long len = in.length();
   int block = 0;
   FileInputStream fis = new FileInputStream(in);
   while (block * BLOCK_SIZE < len) { // while the client is waiting for the file
     int blockSize = (int) Math.min(len - block * BLOCK_SIZE, BLOCK_SIZE);
     writeInteger(sock.getOutputStream(), blockSize); // send the size of this block
     byte[] minorHash =
         hashpipe(fis, sock.getOutputStream(), blockSize); // send the contents of the block
     if (hashMatch(
         sock.getInputStream(),
         minorHash)) { // read the client's minor hash, if the client's hash was correct
       writeInteger(
           sock.getOutputStream(), TRANS_SUCCESS); // tell the client it read everything correctly
       block++; // increment the block and keep reading
     } else { // if the client's hash was incorrect
       writeInteger(
           sock.getOutputStream(), TRANS_ERROR); // tell the client it misread that last block
       fis =
           resetInput(
               fis,
               in,
               block * BLOCK_SIZE); // reset the file reader to the start of the current block
     }
     if (block * BLOCK_SIZE >= len) { // if this is the last block
       writeInteger(sock.getOutputStream(), TRANS_FINISH); // send the end signal
       if (hashMatch(
           sock.getInputStream(), hash)) { // read the client's major hash, if the hash is correct
         fis.close(); // complete the transaction
         writeInteger(sock.getOutputStream(), TRANS_FINISH);
       } else { // if the hash is incorrect
         // ive no idea how we could have gotten to here
         writeInteger(sock.getOutputStream(), TRANS_RESTART); // send the restart signal
         block = 0; // set the block to be 0
         fis = resetInput(fis, in, 0); // reset the file reader to the start of the current block
       }
     }
   }
 }
Beispiel #17
0
 /**
  * Prints the current stack trace to System.err.
  *
  * @param i number of steps to print
  */
 public static void stack(final int i) {
   errln("You're here:");
   final String[] stack = toArray(new Throwable());
   final int l = Math.min(Math.max(2, i + 2), stack.length);
   for (int s = 2; s < l; ++s) errln(stack[s]);
 }
Beispiel #18
0
  /**
   * A tracker wants to know if there's a Task to run. Returns a task we'd like the TaskTracker to
   * execute right now.
   *
   * <p>Eventually this function should compute load on the various TaskTrackers, and incorporate
   * knowledge of DFS file placement. But for right now, it just grabs a single item out of the
   * pending task list and hands it back.
   */
  public synchronized Task pollForNewTask(String taskTracker) {
    //
    // Compute average map and reduce task numbers across pool
    //
    int avgMaps = 0;
    int avgReduces = 0;
    int numTaskTrackers;
    TaskTrackerStatus tts;
    synchronized (taskTrackers) {
      numTaskTrackers = taskTrackers.size();
      tts = (TaskTrackerStatus) taskTrackers.get(taskTracker);
    }
    if (numTaskTrackers > 0) {
      avgMaps = totalMaps / numTaskTrackers;
      avgReduces = totalReduces / numTaskTrackers;
    }
    int totalCapacity = numTaskTrackers * maxCurrentTasks;
    //
    // Get map + reduce counts for the current tracker.
    //
    if (tts == null) {
      LOG.warning("Unknown task tracker polling; ignoring: " + taskTracker);
      return null;
    }

    int numMaps = tts.countMapTasks();
    int numReduces = tts.countReduceTasks();

    //
    // In the below steps, we allocate first a map task (if appropriate),
    // and then a reduce task if appropriate.  We go through all jobs
    // in order of job arrival; jobs only get serviced if their
    // predecessors are serviced, too.
    //

    //
    // We hand a task to the current taskTracker if the given machine
    // has a workload that's equal to or less than the averageMaps
    // +/- TASK_ALLOC_EPSILON.  (That epsilon is in place in case
    // there is an odd machine that is failing for some reason but
    // has not yet been removed from the pool, making capacity seem
    // larger than it really is.)
    //
    synchronized (jobsByArrival) {
      if ((numMaps < maxCurrentTasks) && (numMaps <= (avgMaps + TASK_ALLOC_EPSILON))) {

        int totalNeededMaps = 0;
        for (Iterator it = jobsByArrival.iterator(); it.hasNext(); ) {
          JobInProgress job = (JobInProgress) it.next();
          if (job.getStatus().getRunState() != JobStatus.RUNNING) {
            continue;
          }

          Task t = job.obtainNewMapTask(taskTracker, tts);
          if (t != null) {
            return t;
          }

          //
          // Beyond the highest-priority task, reserve a little
          // room for failures and speculative executions; don't
          // schedule tasks to the hilt.
          //
          totalNeededMaps += job.desiredMaps();
          double padding = 0;
          if (totalCapacity > MIN_SLOTS_FOR_PADDING) {
            padding = Math.min(maxCurrentTasks, totalNeededMaps * PAD_FRACTION);
          }
          if (totalNeededMaps + padding >= totalCapacity) {
            break;
          }
        }
      }

      //
      // Same thing, but for reduce tasks
      //
      if ((numReduces < maxCurrentTasks) && (numReduces <= (avgReduces + TASK_ALLOC_EPSILON))) {

        int totalNeededReduces = 0;
        for (Iterator it = jobsByArrival.iterator(); it.hasNext(); ) {
          JobInProgress job = (JobInProgress) it.next();
          if (job.getStatus().getRunState() != JobStatus.RUNNING) {
            continue;
          }

          Task t = job.obtainNewReduceTask(taskTracker, tts);
          if (t != null) {
            return t;
          }

          //
          // Beyond the highest-priority task, reserve a little
          // room for failures and speculative executions; don't
          // schedule tasks to the hilt.
          //
          totalNeededReduces += job.desiredReduces();
          double padding = 0;
          if (totalCapacity > MIN_SLOTS_FOR_PADDING) {
            padding = Math.min(maxCurrentTasks, totalNeededReduces * PAD_FRACTION);
          }
          if (totalNeededReduces + padding >= totalCapacity) {
            break;
          }
        }
      }
    }
    return null;
  }
Beispiel #19
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();
  }
Beispiel #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];
  }
Beispiel #21
0
  /**
   * Performs the connection identification phase of the Wire protocol and returns the
   * FbWireDatabase implementation for the agreed protocol.
   *
   * @return FbWireDatabase
   * @throws SQLTimeoutException
   * @throws SQLException
   */
  @Override
  public final C identify() throws SQLException {
    try {
      xdrIn = new XdrInputStream(socket.getInputStream());
      xdrOut = new XdrOutputStream(socket.getOutputStream());

      // Here we identify the user to the engine.
      // This may or may not be used as login info to a database.
      final byte[] userBytes = getSystemUserName().getBytes();
      final byte[] hostBytes = getSystemHostName().getBytes();

      ByteArrayOutputStream userId = new ByteArrayOutputStream();
      userId.write(CNCT_user);
      int userLength = Math.min(userBytes.length, 255);
      userId.write(userLength);
      userId.write(userBytes, 0, userLength);

      userId.write(CNCT_host);
      int hostLength = Math.min(hostBytes.length, 255);
      userId.write(hostLength);
      userId.write(hostBytes, 0, hostLength);
      userId.write(CNCT_user_verification);
      userId.write(0);

      xdrOut.writeInt(op_connect);
      xdrOut.writeInt(op_attach);
      xdrOut.writeInt(CONNECT_VERSION2);
      xdrOut.writeInt(arch_generic);

      xdrOut.writeString(getAttachObjectName(), getEncoding());
      xdrOut.writeInt(protocols.getProtocolCount()); // Count of protocols understood
      xdrOut.writeBuffer(userId.toByteArray());

      for (ProtocolDescriptor protocol : protocols) {
        xdrOut.writeInt(protocol.getVersion()); // Protocol version
        xdrOut.writeInt(protocol.getArchitecture()); // Architecture of client
        xdrOut.writeInt(protocol.getMinimumType()); // Minimum type
        xdrOut.writeInt(protocol.getMaximumType()); // Maximum type
        xdrOut.writeInt(protocol.getWeight()); // Preference weight
      }

      xdrOut.flush();

      if (readNextOperation() == op_accept) {
        protocolVersion = xdrIn.readInt(); // Protocol version
        protocolArchitecture = xdrIn.readInt(); // Architecture for protocol
        protocolMinimumType = xdrIn.readInt(); // Minimum type
        if (protocolVersion < 0) {
          protocolVersion = (protocolVersion & FB_PROTOCOL_MASK) | FB_PROTOCOL_FLAG;
        }

        ProtocolDescriptor descriptor = protocols.getProtocolDescriptor(protocolVersion);
        if (descriptor == null) {
          throw new SQLException(
              String.format(
                  "Unsupported or unexpected protocol version %d connecting to database %s. Supported version(s): %s",
                  protocolVersion, getServerName(), protocols.getProtocolVersions()));
        }
        return createConnectionHandle(descriptor);
      } else {
        try {
          close();
        } catch (Exception ex) {
          log.debug("Ignoring exception on disconnect in connect phase of protocol", ex);
        }
        throw new FbExceptionBuilder().exception(ISCConstants.isc_connect_reject).toSQLException();
      }
    } catch (SocketTimeoutException ste) {
      throw new FbExceptionBuilder()
          .timeoutException(ISCConstants.isc_network_error)
          .messageParameter(getServerName())
          .cause(ste)
          .toSQLException();
    } catch (IOException ioex) {
      throw new FbExceptionBuilder()
          .exception(ISCConstants.isc_network_error)
          .messageParameter(getServerName())
          .cause(ioex)
          .toSQLException();
    }
  }
  private DarkBotMCSpambot(
      DarkBot darkBot,
      String server,
      String username,
      String password,
      String sessionId,
      String loginProxy,
      String proxy,
      String owner) {
    synchronized (bots) {
      bots.add(this);
      // slotsTaken.incrementAndGet();
      synchronized (slotsTaken) {
        slotsTaken.notifyAll();
      }
    }
    MinecraftBotData.Builder builder = MinecraftBotData.builder();
    // botData.nickname = "";
    // for(int i = 0; i < 10; i++)
    // botData.nickname += alphas[random.nextInt(alphas.length)];
    if (proxy != null && !proxy.isEmpty()) {
      int port = 80;
      ProxyType type = ProxyType.SOCKS;
      if (proxy.contains(":")) {
        String[] parts = proxy.split(":");
        proxy = parts[0];
        port = Integer.parseInt(parts[1]);
        if (parts.length > 2) type = ProxyType.values()[Integer.parseInt(parts[2]) - 1];
      }
      builder.withSocksProxy(new ProxyData(proxy, port, type));
      this.proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxy, port));
    }
    if (loginProxy != null && !loginProxy.isEmpty()) {
      int port = 80;
      if (loginProxy.contains(":")) {
        String[] parts = loginProxy.split(":");
        loginProxy = parts[0];
        port = Integer.parseInt(parts[1]);
      }
      builder.withHttpProxy(new ProxyData(loginProxy, port, ProxyType.HTTP));
      this.loginProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(loginProxy, port));
    }
    builder.withUsername(username);
    if (sessionId != null) builder.withSessionId(sessionId);
    else builder.withPassword(password);
    if (server != null && !server.isEmpty()) {
      int port = 25565;
      if (server.contains(":")) {
        String[] parts = server.split(":");
        server = parts[0];
        port = Integer.parseInt(parts[1]);
      }
      builder.withServer(server).withPort(port);
    } else throw new IllegalArgumentException("Unknown server!");

    this.owner = owner;
    MinecraftBotData botData = builder.build();
    System.setProperty("socksProxyHost", "");
    System.setProperty("socksProxyPort", "");
    System.out.println("[" + username + "] Connecting...");
    bot = new MinecraftBot(darkBot, botData);
    bot.setMovementDisabled(true);
    connectionHandler = bot.getConnectionHandler();
    Session session = bot.getSession();
    // System.gc();
    System.out.println("[" + username + "] Done! (" + amountJoined.incrementAndGet() + ")");
    bot.getEventManager().registerListener(this);
    bot.getGameHandler().registerListener(this);

    long lastShoutTime = System.currentTimeMillis();
    while (bot.isConnected()) {
      if (die) {
        connectionHandler.sendPacket(new Packet255KickDisconnect("Goodbye"));
        return;
      }
      try {
        Thread.sleep(3000 + random.nextInt(1000));
      } catch (InterruptedException exception) {
        exception.printStackTrace();
      }
      if (!bot.hasSpawned()) continue;
      connectionHandler.sendPacket(new Packet0KeepAlive(random.nextInt()));
      if (spamMessage == null || !canSpam) continue;
      String message = spamMessage;
      if (message.contains("%skill")) message = message.replace("%skill", skills[nextSkill++]);
      if (nextSkill >= skills.length) nextSkill = 0;
      if (message.contains("%bot")) {
        synchronized (bots) {
          message =
              message.replace(
                  "%bot",
                  bots.get(nextBot > bots.size() ? (nextBot = 0) * 0 : nextBot++)
                      .bot
                      .getSession()
                      .getUsername());
        }
      }
      if (message.contains("%spamlist"))
        message = message.replace("%spamlist", spamList[nextSpamList++]);
      if (nextSpamList >= spamList.length) nextSpamList = 0;
      if (message.contains("%rnd")) {
        int length = 1;
        int index = message.indexOf("%rnd") + "%rnd".length();
        int lastIndex;
        for (lastIndex = index; lastIndex < message.length(); lastIndex++)
          if (Character.isDigit(message.charAt(lastIndex))) lastIndex++;
          else break;
        if (lastIndex > message.length()) lastIndex--;
        try {
          System.out.println(index + "," + lastIndex + "," + message.length());
          length = Integer.parseInt(message.substring(index, lastIndex));
        } catch (Exception exception) {
        }

        String randomChars = "";
        for (int i = 0; i < length; i++) randomChars += alphas[random.nextInt(alphas.length)];
        message = message.replace("%rnd", randomChars);
      }
      if (message.contains("%msg"))
        message = "/msg " + msgChars[nextMsgChar++] + " " + message.replace("%msg", "");
      if (message.contains("%ernd")) {
        message = message.replace("%ernd", "");
        int extraMessageLength = 15 + random.nextInt(6);
        message = message.substring(0, Math.min(100 - extraMessageLength, message.length())) + " [";
        extraMessageLength -= 3;
        for (int i = 0; i < extraMessageLength; i++)
          message += alphas[random.nextInt(alphas.length)];
        message += "]";
      } else message = message.substring(0, Math.min(100, message.length()));
      connectionHandler.sendPacket(new Packet3Chat(message));
    }
    synchronized (bots) {
      bots.remove(this);
    }
    amountJoined.decrementAndGet();
    slotsTaken.decrementAndGet();
    synchronized (slotsTaken) {
      slotsTaken.notifyAll();
    }
  }
  /**
   * used to exchange identifiers and timestamps and heartbeat intervals between the server and
   * client
   *
   * @param key the SelectionKey relating to the this cha
   * @throws java.io.IOException
   * @throws InterruptedException
   */
  private void doHandShaking(@NotNull final SelectionKey key)
      throws IOException, InterruptedException {
    final Attached attached = (Attached) key.attachment();
    final TcpSocketChannelEntryWriter writer = attached.entryWriter;
    final TcpSocketChannelEntryReader reader = attached.entryReader;

    if (attached.remoteIdentifier == Byte.MIN_VALUE) {

      final byte remoteIdentifier = reader.identifierFromBuffer();

      if (remoteIdentifier == Byte.MIN_VALUE) return;

      attached.remoteIdentifier = remoteIdentifier;

      // we use the as iterating the activeKeys via the bitset wont create and Objects
      // but if we use the selector.keys() this will.
      selectionKeysStore[remoteIdentifier] = key;
      activeKeys.set(remoteIdentifier);

      if (LOG.isDebugEnabled()) {
        LOG.debug(
            "server-connection id={}, remoteIdentifier={}", localIdentifier, remoteIdentifier);
      }

      if (remoteIdentifier == localIdentifier) {
        throw new IllegalStateException(
            "Where are connecting to a remote "
                + "map with the same "
                + "identifier as this map, identifier="
                + localIdentifier
                + ", "
                + "please change either this maps identifier or the remote one");
      }

      attached.remoteModificationIterator =
          replica.acquireModificationIterator(remoteIdentifier, attached);

      writer.writeRemoteBootstrapTimestamp(replica.lastModificationTime(remoteIdentifier));

      // tell the remote node, what are heartbeat interval is
      writer.writeRemoteHeartbeatInterval(heartBeatInterval);
    }

    if (attached.remoteBootstrapTimestamp == Long.MIN_VALUE) {
      attached.remoteBootstrapTimestamp = reader.remoteBootstrapTimestamp();
      if (attached.remoteBootstrapTimestamp == Long.MIN_VALUE) return;
    }

    if (!attached.hasRemoteHeartbeatInterval) {

      long value = reader.remoteHeartbeatIntervalFromBuffer();

      if (value == Long.MIN_VALUE) return;

      if (value < 0) {
        LOG.error("value=" + value);
      }

      // we add a 10% safety margin to the timeout time due to latency fluctuations on the network,
      // in other words we wont consider a connection to have
      // timed out, unless the heartbeat interval has exceeded 25% of the expected time.
      attached.remoteHeartbeatInterval = (long) (value * 1.25);

      // we have to make our selector poll interval at least as short as the minimum selector
      // timeout
      selectorTimeout = Math.min(selectorTimeout, value);

      if (selectorTimeout < 0) LOG.info("");

      attached.hasRemoteHeartbeatInterval = true;

      // now we're finished we can get on with reading the entries
      attached.setHandShakingComplete();
      attached.remoteModificationIterator.dirtyEntries(attached.remoteBootstrapTimestamp);
      reader.entriesFromBuffer();
    }
  }