Exemplo n.º 1
0
  public Tessellator getSubTessellatorImpl(int i) {
    for (int j = 0; j < subTextures.length; j++) {
      int l = subTextures[j];
      if (l == i) {
        Tessellator tessellator1 = subTessellators[j];
        return tessellator1;
      }
    }

    for (int k = 0; k < subTextures.length; k++) {
      int i1 = subTextures[k];
      if (i1 <= 0) {
        Tessellator tessellator2 = subTessellators[k];
        subTextures[k] = i;
        return tessellator2;
      }
    }

    Tessellator tessellator = new Tessellator();
    Tessellator atessellator[] = subTessellators;
    int ai[] = subTextures;
    subTessellators = new Tessellator[atessellator.length + 1];
    subTextures = new int[ai.length + 1];
    System.arraycopy(atessellator, 0, subTessellators, 0, atessellator.length);
    System.arraycopy(ai, 0, subTextures, 0, ai.length);
    subTessellators[atessellator.length] = tessellator;
    subTextures[ai.length] = i;
    Config.dbg(
        (new StringBuilder())
            .append("Allocated subtessellator, count: ")
            .append(subTessellators.length)
            .toString());
    return tessellator;
  }
Exemplo n.º 2
0
 static byte[] encode(char[] cc, Charset cs, boolean testDirect, Time t) throws Exception {
   ByteBuffer bbf;
   CharBuffer cbf;
   CharsetEncoder enc = cs.newEncoder();
   String csn = cs.name();
   if (testDirect) {
     bbf = ByteBuffer.allocateDirect(cc.length * 4);
     cbf = ByteBuffer.allocateDirect(cc.length * 2).asCharBuffer();
     cbf.put(cc).flip();
   } else {
     bbf = ByteBuffer.allocate(cc.length * 4);
     cbf = CharBuffer.wrap(cc);
   }
   CoderResult cr = null;
   long t1 = System.nanoTime() / 1000;
   for (int i = 0; i < iteration; i++) {
     cbf.rewind();
     bbf.clear();
     enc.reset();
     cr = enc.encode(cbf, bbf, true);
   }
   long t2 = System.nanoTime() / 1000;
   t.t = (t2 - t1) / iteration;
   if (cr != CoderResult.UNDERFLOW) {
     System.out.println("ENC-----------------");
     int pos = cbf.position();
     System.out.printf("  cr=%s, cbf.pos=%d, cc[pos]=%x%n", cr.toString(), pos, cc[pos] & 0xffff);
     throw new RuntimeException("Encoding err: " + csn);
   }
   byte[] bb = new byte[bbf.position()];
   bbf.flip();
   bbf.get(bb);
   return bb;
 }
Exemplo n.º 3
0
  /**
   * Method to provide a gross level of synchronization with the target monitored jvm.
   *
   * <p>gross synchronization works by polling for the hotspot.rt.hrt.ticks counter, which is the
   * last counter created by the StatSampler initialization code. The counter is updated when the
   * watcher thread starts scheduling tasks, which is the last thing done in vm initialization.
   */
  protected void synchWithTarget(Map<String, Monitor> map) throws MonitorException {
    /*
     * synch must happen with syncWaitMs from now. Default is 5 seconds,
     * which is reasonabally generous and should provide for extreme
     * situations like startup delays due to allocation of large ISM heaps.
     */
    long timeLimit = System.currentTimeMillis() + syncWaitMs;

    String name = "hotspot.rt.hrt.ticks";
    LongMonitor ticks = (LongMonitor) pollFor(map, name, timeLimit);

    /*
     * loop waiting for the ticks counter to be non zero. This is
     * an indication that the jvm is initialized.
     */
    log("synchWithTarget: " + lvmid + " ");
    while (ticks.longValue() == 0) {
      log(".");

      try {
        Thread.sleep(20);
      } catch (InterruptedException e) {
      }

      if (System.currentTimeMillis() > timeLimit) {
        lognl("failed: " + lvmid);
        throw new MonitorException("Could Not Synchronize with target");
      }
    }
    lognl("success: " + lvmid);
  }
Exemplo n.º 4
0
  public static void main(String[] args) throws IOException {
    System.out.println("Input Stream:");
    long start = System.currentTimeMillis();
    Path filename = Paths.get(args[0]);
    long crcValue = checksumInputStream(filename);
    long end = System.currentTimeMillis();
    System.out.println(Long.toHexString(crcValue));
    System.out.println((end - start) + " milliseconds");

    System.out.println("Buffered Input Stream:");
    start = System.currentTimeMillis();
    crcValue = checksumBufferedInputStream(filename);
    end = System.currentTimeMillis();
    System.out.println(Long.toHexString(crcValue));
    System.out.println((end - start) + " milliseconds");

    System.out.println("Random Access File:");
    start = System.currentTimeMillis();
    crcValue = checksumRandomAccessFile(filename);
    end = System.currentTimeMillis();
    System.out.println(Long.toHexString(crcValue));
    System.out.println((end - start) + " milliseconds");

    System.out.println("Mapped File:");
    start = System.currentTimeMillis();
    crcValue = checksumMappedFile(filename);
    end = System.currentTimeMillis();
    System.out.println(Long.toHexString(crcValue));
    System.out.println((end - start) + " milliseconds");
  }
Exemplo n.º 5
0
  /**
   * Sets one or more icons for the Display.
   *
   * <ul>
   *   <li>On Windows you should supply at least one 16x16 icon and one 32x32.
   *   <li>Linux (and similar platforms) expect one 32x32 icon.
   *   <li>Mac OS X should be supplied one 128x128 icon
   * </ul>
   *
   * The implementation will use the supplied ByteBuffers with image data in RGBA and perform any
   * conversions nescesarry for the specific platform.
   *
   * @param icons Array of icons in RGBA mode
   * @return number of icons used.
   */
  public int setIcon(ByteBuffer[] icons) {
    boolean done_small = false;
    boolean done_large = false;
    int used = 0;

    int small_icon_size = 16;
    int large_icon_size = 32;
    for (ByteBuffer icon : icons) {
      int size = icon.limit() / 4;

      if ((((int) Math.sqrt(size)) == small_icon_size) && (!done_small)) {
        long small_new_icon = createIcon(small_icon_size, small_icon_size, icon.asIntBuffer());
        sendMessage(hwnd, WM_SETICON, ICON_SMALL, small_new_icon);
        freeSmallIcon();
        small_icon = small_new_icon;
        used++;
        done_small = true;
      }
      if ((((int) Math.sqrt(size)) == large_icon_size) && (!done_large)) {
        long large_new_icon = createIcon(large_icon_size, large_icon_size, icon.asIntBuffer());
        sendMessage(hwnd, WM_SETICON, ICON_BIG, large_new_icon);
        freeLargeIcon();
        large_icon = large_new_icon;
        used++;
        done_large = true;

        // Problem: The taskbar icon won't update until Windows sends a WM_GETICON to our window
        // proc and we reply. But this method is usually called
        // on init and it might take a while before the next call to nUpdate (because of resources
        // being loaded, etc). So we wait for the next
        // WM_GETICON message (usually received about 100ms after WM_SETICON) to make sure the
        // taskbar icon has updated before we return to the user.
        // (We wouldn't need to do this if the event loop was running continuously on its own
        // thread.)
        iconsLoaded = false;

        // Track how long the wait takes and give up at 500ms, just in case.
        long time = System.nanoTime();
        long MAX_WAIT = 500L * 1000L * 1000L;
        while (true) {
          nUpdate();
          if (iconsLoaded || MAX_WAIT < System.nanoTime() - time) break;

          Thread.yield();
        }
      }
    }

    return used;
  }
Exemplo n.º 6
0
  static void compare(Charset cs1, Charset cs2, char[] cc) throws Exception {
    System.gc(); // enqueue finalizable objects
    Thread.sleep(1000);
    System.gc(); // enqueue finalizable objects

    String csn1 = cs1.name();
    String csn2 = cs2.name();
    System.out.printf("Diff     <%s> <%s>...%n", csn1, csn2);

    Time t1 = new Time();
    Time t2 = new Time();

    byte[] bb1 = encode(cc, cs1, false, t1);
    byte[] bb2 = encode(cc, cs2, false, t2);

    System.out.printf(
        "    Encoding TimeRatio %s/%s: %d,%d :%f%n",
        csn2, csn1, t2.t, t1.t, (double) (t2.t) / (t1.t));
    if (!Arrays.equals(bb1, bb2)) {
      System.out.printf("        encoding failed%n");
    }

    char[] cc2 = decode(bb1, cs2, false, t2);
    char[] cc1 = decode(bb1, cs1, false, t1);
    System.out.printf(
        "    Decoding TimeRatio %s/%s: %d,%d :%f%n",
        csn2, csn1, t2.t, t1.t, (double) (t2.t) / (t1.t));
    if (!Arrays.equals(cc1, cc2)) {
      System.out.printf("        decoding failed%n");
    }

    bb1 = encode(cc, cs1, true, t1);
    bb2 = encode(cc, cs2, true, t2);

    System.out.printf(
        "    Encoding(dir) TimeRatio %s/%s: %d,%d :%f%n",
        csn2, csn1, t2.t, t1.t, (double) (t2.t) / (t1.t));

    if (!Arrays.equals(bb1, bb2)) System.out.printf("        encoding (direct) failed%n");

    cc1 = decode(bb1, cs1, true, t1);
    cc2 = decode(bb1, cs2, true, t2);
    System.out.printf(
        "    Decoding(dir) TimeRatio %s/%s: %d,%d :%f%n",
        csn2, csn1, t2.t, t1.t, (double) (t2.t) / (t1.t));
    if (!Arrays.equals(cc1, cc2)) {
      System.out.printf("        decoding (direct) failed%n");
    }
  }
Exemplo n.º 7
0
    void add(Target t) {
      SocketChannel sc = null;
      try {

        sc = SocketChannel.open();
        sc.configureBlocking(false);

        boolean connected = sc.connect(t.address);

        t.channel = sc;
        t.connectStart = System.currentTimeMillis();

        if (connected) {
          t.connectFinish = t.connectStart;
          sc.close();
          printer.add(t);
        } else {
          synchronized (pending) {
            pending.add(t);
          }

          sel.wakeup();
        }
      } catch (IOException x) {
        if (sc != null) {
          try {
            sc.close();
          } catch (IOException xx) {
          }
        }
        t.failure = x;
        printer.add(t);
      }
    }
Exemplo n.º 8
0
 private static void usage() {
   System.out.println("\nUSAGE: java " + classname + " [options]\n");
   System.out.println("Options:\n");
   System.out.println("-yuv = test YUV encoding/decoding support\n");
   System.out.println("-bi = test BufferedImage support\n");
   System.exit(1);
 }
Exemplo n.º 9
0
  public boolean export(String src) {
    boolean result = true;
    String fs = System.getProperty("file.separator");

    String contents = getSticker();
    try {
      File file = new File(this.name + "." + src);

      FileWriter fwrite = new FileWriter(file, true);

      fwrite.write(contents);

      fwrite.close();
      JOptionPane.showMessageDialog(
          null, Local.getString("Document was sucessfully created in your Memoranda folder =D"));
      // Original message said: "Documento creado con exito en su carpeta Memoranda =D"

    } catch (IOException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          null, Local.getString("We have failed to create your document =(..."));
      // Original message said: "NO Logramos crear su documento =(..."
    }

    return result;
  }
Exemplo n.º 10
0
  /**
   * Method to poll the instrumentation memory for a counter with the given name. The polling period
   * is bounded by the timeLimit argument.
   */
  protected Monitor pollFor(Map<String, Monitor> map, String name, long timeLimit)
      throws MonitorException {
    Monitor monitor = null;

    log("polling for: " + lvmid + "," + name + " ");

    pollForEntry = nextEntry;
    while ((monitor = map.get(name)) == null) {
      log(".");

      try {
        Thread.sleep(20);
      } catch (InterruptedException e) {
      }

      long t = System.currentTimeMillis();
      if ((t > timeLimit) || (overflow.intValue() > 0)) {
        lognl("failed: " + lvmid + "," + name);
        dumpAll(map, lvmid);
        throw new MonitorException("Could not find expected counter");
      }

      getNewMonitors(map);
    }
    lognl("success: " + lvmid + "," + name);
    return monitor;
  }
Exemplo n.º 11
0
  public void addTarget(Target target) {
    // 向targets队列中加入一个任务
    SocketChannel socketChannel = null;
    try {
      socketChannel = SocketChannel.open();
      socketChannel.configureBlocking(false);
      socketChannel.connect(target.address);

      target.channel = socketChannel;
      target.connectStart = System.currentTimeMillis();

      synchronized (targets) {
        targets.add(target);
      }
      selector.wakeup();
    } catch (Exception x) {
      if (socketChannel != null) {
        try {
          socketChannel.close();
        } catch (IOException xx) {
        }
      }
      target.failure = x;
      addFinishedTarget(target);
    }
  }
Exemplo n.º 12
0
 void send(byte[] data) throws IOException {
   SocketChannel channel = (SocketChannel) key.channel();
   verboseLog("TCP write", data);
   byte[] lengthArray = new byte[2];
   lengthArray[0] = (byte) (data.length >>> 8);
   lengthArray[1] = (byte) (data.length & 0xFF);
   ByteBuffer[] buffers = new ByteBuffer[2];
   buffers[0] = ByteBuffer.wrap(lengthArray);
   buffers[1] = ByteBuffer.wrap(data);
   int nsent = 0;
   key.interestOps(SelectionKey.OP_WRITE);
   try {
     while (nsent < data.length + 2) {
       if (key.isWritable()) {
         long n = channel.write(buffers);
         if (n < 0) throw new EOFException();
         nsent += (int) n;
         if (nsent < data.length + 2 && System.currentTimeMillis() > endTime)
           throw new SocketTimeoutException();
       } else blockUntil(key, endTime);
     }
   } finally {
     if (key.isValid()) key.interestOps(0);
   }
 }
Exemplo n.º 13
0
  public static void main(String args[]) throws IOException {
    ServerSocket sSocket = new ServerSocket(sPort, 10);

    // Arguments Handling
    if (args.length != 1) {
      System.out.println("Must specify a file-path argument.");
    } else {
      String currentDir = System.getProperty("user.dir");
      filePath = currentDir + "/src/srcFile/" + args[0];
      filename = args[0];
    }

    // Get list of chunks owned
    chunkOwned();

    // Call FileSplitter
    FileSplitter fs = new FileSplitter();
    fs.split(filePath);

    System.out.println("Waiting for connection");
    while (true) {
      Socket connection = sSocket.accept();
      System.out.println("Connection received from " + connection.getInetAddress().getHostName());

      new Thread(new MultiThreadServer(connection)).start();
    }
  }
Exemplo n.º 14
0
  // Send File
  public void sendFile(String chunkName) throws IOException {
    OutputStream os = null;
    String currentDir = System.getProperty("user.dir");
    chunkName = currentDir + "/src/srcFile/" + chunkName;
    File myFile = new File(chunkName);

    byte[] arrby = new byte[(int) myFile.length()];

    try {
      FileInputStream fis = new FileInputStream(myFile);
      BufferedInputStream bis = new BufferedInputStream(fis);
      bis.read(arrby, 0, arrby.length);

      os = csocket.getOutputStream();
      System.out.println("Sending File.");
      os.write(arrby, 0, arrby.length);
      os.flush();
      System.out.println("File Sent.");
      //			os.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      //			os.close();
    }
  }
Exemplo n.º 15
0
 public void keyPressed(KeyEvent key) {
   switch (key.getKeyChar()) {
     case KeyEvent.VK_ESCAPE:
       System.exit(0);
       break;
   }
 }
 /** run */
 public void run() {
   long now = System.currentTimeMillis();
   if ((socketCleaner == null) || (now - entry.getLastUse() >= connectionTimeout)) {
     if (logger.isDebugEnabled()) {
       logger.debug(
           "Socket has not been used for "
               + (now - entry.getLastUse())
               + " micro seconds, closing it");
     }
     sockets.remove(entry.getPeerAddress());
     try {
       synchronized (entry) {
         entry.getSocket().close();
       }
       logger.info("Socket to " + entry.getPeerAddress() + " closed due to timeout");
     } catch (IOException ex) {
       logger.error(ex);
     }
   } else {
     if (logger.isDebugEnabled()) {
       logger.debug("Scheduling " + ((entry.getLastUse() + connectionTimeout) - now));
     }
     socketCleaner.schedule(
         new SocketTimeout(entry), (entry.getLastUse() + connectionTimeout) - now);
   }
 }
Exemplo n.º 17
0
 private static Charset getDefaultCharset() {
   try {
     String encoding = System.getProperty("file.encoding");
     return Charset.forName(encoding);
   } catch (UnsupportedCharsetException e) {
     return Charset.forName("UTF-8");
   }
 }
 /**
  * Sets the substitution characters to use when the converter is in substitution mode. The given
  * chars must not be longer than the value returned by getMaxCharsPerByte for this converter.
  *
  * @param chars the substitution chars
  * @exception IllegalArgumentException if given byte array is longer than the value returned by
  *     the method getMaxBytesPerChar.
  * @see #setSubstitutionMode
  * @see #getMaxBytesPerChar
  */
 public void setSubstitutionChars(char[] chars) throws IllegalArgumentException {
   if (decoder != null) decoder.replaceWith(new String(chars));
   else { // only provided for subclasses
     if (chars.length > getMaxCharsPerByte()) throw new IllegalArgumentException();
     subChars = new char[chars.length];
     System.arraycopy(chars, 0, subChars, 0, chars.length);
   }
 }
Exemplo n.º 19
0
  public static void runTests() {
    try {

      // SHA1 sha1Jmule = new SHA1();
      MessageDigest sha1Sun = MessageDigest.getInstance("SHA-1");
      SHA1 sha1Gudy = new SHA1();
      // SHA1Az shaGudyResume = new SHA1Az();

      ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024);

      File dir = new File(dirname);
      File[] files = dir.listFiles();

      for (int i = 0; i < files.length; i++) {
        FileChannel fc = new RandomAccessFile(files[i], "r").getChannel();

        System.out.println("Testing " + files[i].getName() + " ...");

        while (fc.position() < fc.size()) {
          fc.read(buffer);
          buffer.flip();

          byte[] raw = new byte[buffer.limit()];
          System.arraycopy(buffer.array(), 0, raw, 0, raw.length);

          sha1Gudy.update(buffer);
          sha1Gudy.saveState();
          ByteBuffer bb = ByteBuffer.wrap(new byte[56081]);
          sha1Gudy.digest(bb);
          sha1Gudy.restoreState();

          sha1Sun.update(raw);

          buffer.clear();
        }

        byte[] sun = sha1Sun.digest();
        sha1Sun.reset();

        byte[] gudy = sha1Gudy.digest();
        sha1Gudy.reset();

        if (Arrays.equals(sun, gudy)) {
          System.out.println("  SHA1-Gudy: OK");
        } else {
          System.out.println("  SHA1-Gudy: FAILED");
        }

        buffer.clear();
        fc.close();
        System.out.println();
      }

    } catch (Throwable e) {
      Debug.printStackTrace(e);
    }
  }
Exemplo n.º 20
0
  void _open() throws IOException {

    long sleepTime = 100;

    final long start = System.currentTimeMillis();
    while (true) {

      IOException lastError = null;

      try {
        _sock = SocketChannel.open();
        _socket = _sock.socket();
        _socket.connect(_addr, _options.connectTimeout);

        _socket.setTcpNoDelay(!USE_NAGLE);
        _socket.setSoTimeout(_options.socketTimeout);
        _in = _socket.getInputStream();
        return;
      } catch (IOException ioe) {
        //  TODO  - erh to fix                lastError = new IOException( "couldn't connect to [" +
        // _addr + "] bc:" + lastError , lastError );
        lastError = new IOException("couldn't connect to [" + _addr + "] bc:" + ioe);
        _logger.log(Level.INFO, "connect fail to : " + _addr, ioe);
      }

      if (!_options.autoConnectRetry || (_pool != null && !_pool._everWorked)) throw lastError;

      long sleptSoFar = System.currentTimeMillis() - start;

      if (sleptSoFar >= CONN_RETRY_TIME_MS) throw lastError;

      if (sleepTime + sleptSoFar > CONN_RETRY_TIME_MS) sleepTime = CONN_RETRY_TIME_MS - sleptSoFar;

      _logger.severe(
          "going to sleep and retry.  total sleep time after = "
              + (sleptSoFar + sleptSoFar)
              + "ms  this time:"
              + sleepTime
              + "ms");
      ThreadUtil.sleep(sleepTime);
      sleepTime *= 2;
    }
  }
Exemplo n.º 21
0
  private void checkAndLaunchUpdate() {
    Log.i(LOG_FILE_NAME, "Checking for an update");

    int statusCode = 8; // UNEXPECTED_ERROR
    File baseUpdateDir = null;
    if (Build.VERSION.SDK_INT >= 8)
      baseUpdateDir = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
    else baseUpdateDir = new File(Environment.getExternalStorageDirectory().getPath(), "download");

    File updateDir = new File(new File(baseUpdateDir, "updates"), "0");

    File updateFile = new File(updateDir, "update.apk");
    File statusFile = new File(updateDir, "update.status");

    if (!statusFile.exists() || !readUpdateStatus(statusFile).equals("pending")) return;

    if (!updateFile.exists()) return;

    Log.i(LOG_FILE_NAME, "Update is available!");

    // Launch APK
    File updateFileToRun = new File(updateDir, getPackageName() + "-update.apk");
    try {
      if (updateFile.renameTo(updateFileToRun)) {
        String amCmd =
            "/system/bin/am start -a android.intent.action.VIEW "
                + "-n com.android.packageinstaller/.PackageInstallerActivity -d file://"
                + updateFileToRun.getPath();
        Log.i(LOG_FILE_NAME, amCmd);
        Runtime.getRuntime().exec(amCmd);
        statusCode = 0; // OK
      } else {
        Log.i(LOG_FILE_NAME, "Cannot rename the update file!");
        statusCode = 7; // WRITE_ERROR
      }
    } catch (Exception e) {
      Log.i(LOG_FILE_NAME, "error launching installer to update", e);
    }

    // Update the status file
    String status = statusCode == 0 ? "succeeded\n" : "failed: " + statusCode + "\n";

    OutputStream outStream;
    try {
      byte[] buf = status.getBytes("UTF-8");
      outStream = new FileOutputStream(statusFile);
      outStream.write(buf, 0, buf.length);
      outStream.close();
    } catch (Exception e) {
      Log.i(LOG_FILE_NAME, "error writing status file", e);
    }

    if (statusCode == 0) System.exit(0);
  }
Exemplo n.º 22
0
  public String getSticker() {
    Map stickers = EventsManager.getStickers();
    String result = "";
    String nl = System.getProperty("line.separator");
    for (Iterator i = stickers.keySet().iterator(); i.hasNext(); ) {
      String id = (String) i.next();
      result += (String) (((Element) stickers.get(id)).getValue()) + nl;
    }

    return result;
  }
Exemplo n.º 23
0
 public void addEnvToIntent(Intent intent) {
   Map<String, String> envMap = System.getenv();
   Set<Map.Entry<String, String>> envSet = envMap.entrySet();
   Iterator<Map.Entry<String, String>> envIter = envSet.iterator();
   int c = 0;
   while (envIter.hasNext()) {
     Map.Entry<String, String> entry = envIter.next();
     intent.putExtra("env" + c, entry.getKey() + "=" + entry.getValue());
     c++;
   }
 }
Exemplo n.º 24
0
 static char[] decode(byte[] bb, Charset cs, boolean testDirect, Time t) throws Exception {
   String csn = cs.name();
   CharsetDecoder dec = cs.newDecoder();
   ByteBuffer bbf;
   CharBuffer cbf;
   if (testDirect) {
     bbf = ByteBuffer.allocateDirect(bb.length);
     cbf = ByteBuffer.allocateDirect(bb.length * 2).asCharBuffer();
     bbf.put(bb);
   } else {
     bbf = ByteBuffer.wrap(bb);
     cbf = CharBuffer.allocate(bb.length);
   }
   CoderResult cr = null;
   long t1 = System.nanoTime() / 1000;
   for (int i = 0; i < iteration; i++) {
     bbf.rewind();
     cbf.clear();
     dec.reset();
     cr = dec.decode(bbf, cbf, true);
   }
   long t2 = System.nanoTime() / 1000;
   t.t = (t2 - t1) / iteration;
   if (cr != CoderResult.UNDERFLOW) {
     System.out.println("DEC-----------------");
     int pos = bbf.position();
     System.out.printf(
         "  cr=%s, bbf.pos=%d, bb[pos]=%x,%x,%x,%x%n",
         cr.toString(),
         pos,
         bb[pos++] & 0xff,
         bb[pos++] & 0xff,
         bb[pos++] & 0xff,
         bb[pos++] & 0xff);
     throw new RuntimeException("Decoding err: " + csn);
   }
   char[] cc = new char[cbf.position()];
   cbf.flip();
   cbf.get(cc);
   return cc;
 }
Exemplo n.º 25
0
  @Override
  public void run() {
    try {
      out = new ObjectOutputStream(csocket.getOutputStream());
      out.flush();
      in = new ObjectInputStream(csocket.getInputStream());

      // Look for chunks
      String currentDir = System.getProperty("user.dir");
      File folder = new File(currentDir + "/src/srcFile");
      File[] listOfFiles = folder.listFiles();
      int fileCount = 0;
      OutputStream os;
      for (int i = 0; i < listOfFiles.length; i++) {
        if (listOfFiles[i].isFile()
            && listOfFiles[i]
                .getName()
                .toLowerCase()
                .contains("chunk")) { // 0 1 10 11 12 13 14 2 20 21 22 23 3 4 5 ....
          fileCount++;
          String chunkName = listOfFiles[i].getName().toString();
          chunkId = chunkName.substring(chunkName.lastIndexOf('.') + 6);

          xPayload(chunkId);
          if ((connTo.equals("2") && Integer.parseInt(chunkId) % noDev == 0)
              || (connTo.equals("3") && (Integer.parseInt(chunkId) - 1) % noDev == 0)
              || (connTo.equals("4") && (Integer.parseInt(chunkId) - 2) % noDev == 0)
              || (connTo.equals("5") && (Integer.parseInt(chunkId) - 3) % noDev == 0)
              || (connTo.equals("6") && (Integer.parseInt(chunkId) - 4) % noDev == 0)) {

            System.out.println(chunkName);
            sendFile(chunkName);
          }
        }
      }

      xPayload("-1");
      System.out.println("All chunks sent.");

    } catch (IOException ioException) {
      ioException.printStackTrace();
    } finally {
      // Close connections
      try {
        in.close();
        out.close();
        csocket.close();
        System.out.println("Thread closed.");
      } catch (IOException ioException) {
        System.out.println("Client " + devId + " disconnected.");
      }
    }
  }
Exemplo n.º 26
0
  public static void main(String args[]) {
    Connection c = null;
    PreparedStatement stmt = null;
    try {
      Class.forName("org.postgresql.Driver");
      c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test", "pdv", "pdv");
      System.out.println("Opened database successfully");
      List<String> results = new ArrayList<String>();
      File dir = new File("D:/jboss/eclipse/workspace/LTF");
      Iterator<File> files =
          FileUtils.iterateFilesAndDirs(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
      StopWatch timerAll = new StopWatch();
      timerAll.start();
      while (files.hasNext()) {
        File file = (File) files.next();
        if (file.isFile()) {
          StopWatch timeForAFile = new StopWatch();
          timeForAFile.start();
          String toDB = encodeFileToBase64Binary(file);
          String sql =
              "INSERT INTO test (file_id,file_name,file_data,file_date) VALUES (nextval('test_file_id_seq'),?,?,?)";
          stmt = c.prepareStatement(sql);

          stmt.setString(1, file.getAbsolutePath());
          stmt.setString(2, toDB);
          stmt.setDate(3, new java.sql.Date(Calendar.getInstance().getTimeInMillis()));
          stmt.executeUpdate();
          timeForAFile.stop();
          System.out.println(timeForAFile.toString());
        }
      }
      timerAll.stop();
      System.out.println("=================================================");
      System.out.println(timerAll.toString());

      stmt.close();
      /*
       * Statement statement = null; statement = c.createStatement();
       * ResultSet rs = statement.executeQuery(
       * "select file_data from test limit 1"); while (rs.next()) { String
       * encoded = rs.getString("file_data"); byte[] decoded =
       * Base64.getDecoder().decode(encoded); FileOutputStream fos = new
       * FileOutputStream("c:/temp/2.jpg"); fos.write(decoded);
       * fos.close(); }
       */

      c.close();
    } catch (Exception e) {
      System.err.println(e.getClass().getName() + ": " + e.getMessage());
      System.exit(0);
    }
    System.out.println("Table created successfully");
  }
Exemplo n.º 27
0
  public void run() {
    init();
    engine = new Engine();

    long lastTime = System.nanoTime();
    double delta = 0.0;
    // Amout of nanoseconds in 1/60th of a second
    double ns = 1000000000.0 / 60.0;
    long timer = System.currentTimeMillis();
    int updates = 0;
    int frames = 0;
    while (running) {
      long now = System.nanoTime();
      delta += (now - lastTime) / ns;
      lastTime = now;
      // if delta >= than one then the amount of time >= 1/60th of a second
      if (delta >= 1.0) {
        update();
        updates++;
        delta--;
      }
      render();
      frames++;
      // If a second has passed, we print the stats
      if (System.currentTimeMillis() - timer > 1000) {
        timer += 1000;
        System.out.println(updates + " ups, " + frames + " fps");
        updates = 0;
        frames = 0;
      }
      if (glfwWindowShouldClose(window) == GL_TRUE) running = false;
    }
    engine.CleanUp();
    keyCallback.release();
    sizeCallback.release();
    mouseCallback.release();
    focusCallback.release();
    glfwDestroyWindow(window);
    glfwTerminate();
  }
Exemplo n.º 28
0
 @Override
 public void close() throws BlockStoreException {
   try {
     buffer.force();
     if (System.getProperty("os.name").toLowerCase().contains("win")) {
       log.info("Windows mmap hack: Forcing buffer cleaning");
       WindowsMMapHack.forceRelease(buffer);
     }
     buffer = null; // Allow it to be GCd and the underlying file mapping to go away.
     randomAccessFile.close();
   } catch (IOException e) {
     throw new BlockStoreException(e);
   }
 }
Exemplo n.º 29
0
  public static void main(String[] args) {
    if (args.length < 1) {
      System.err.println("usage: [jre] event.Speed [client|server]");
    }

    if ("client".equals(args[0])) {
      time = System.currentTimeMillis();
      client();
    } else if ("classic-client".equals(args[0])) {
      classicClient();
    } else {
      server();
    }
  }
Exemplo n.º 30
0
 public FilePlayback(String hostname, int port, String dataDir, double speedup, int blockSize) {
   this.hostname = hostname;
   this.port = port;
   this.dataDir = dataDir;
   this.speedup = speedup;
   this.blockSize = blockSize;
   client = new BufferClient();
   // Open the header/events/samples files
   try {
     initFiles(dataDir);
   } catch (FileNotFoundException e) {
     e.printStackTrace();
     System.exit(-1);
   }
 }