Esempio n. 1
1
 // see DbFile.java for javadocs
 public Page readPage(PageId pid) {
   int offset = BufferPool.PAGE_SIZE * pid.pageNumber();
   byte[] b = new byte[BufferPool.PAGE_SIZE];
   try {
     InputStream is = new FileInputStream(m_file);
     is.skip(offset);
     is.read(b, 0, BufferPool.PAGE_SIZE);
     is.close();
     return new HeapPage((HeapPageId) pid, b);
   } catch (IOException ioe) {
     ioe.printStackTrace();
     return null;
   }
 }
Esempio n. 2
0
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    String filePickerResult = "";
    if (data != null && resultCode == RESULT_OK) {
      try {
        ContentResolver cr = getContentResolver();
        Uri uri = data.getData();
        Cursor cursor =
            GeckoApp.mAppContext
                .getContentResolver()
                .query(uri, new String[] {OpenableColumns.DISPLAY_NAME}, null, null, null);
        String name = null;
        if (cursor != null) {
          try {
            if (cursor.moveToNext()) {
              name = cursor.getString(0);
            }
          } finally {
            cursor.close();
          }
        }
        String fileName = "tmp_";
        String fileExt = null;
        int period;
        if (name == null || (period = name.lastIndexOf('.')) == -1) {
          String mimeType = cr.getType(uri);
          fileExt = "." + GeckoAppShell.getExtensionFromMimeType(mimeType);
        } else {
          fileExt = name.substring(period);
          fileName = name.substring(0, period);
        }
        File file = File.createTempFile(fileName, fileExt, sGREDir);

        FileOutputStream fos = new FileOutputStream(file);
        InputStream is = cr.openInputStream(uri);
        byte[] buf = new byte[4096];
        int len = is.read(buf);
        while (len != -1) {
          fos.write(buf, 0, len);
          len = is.read(buf);
        }
        fos.close();
        filePickerResult = file.getAbsolutePath();
      } catch (Exception e) {
        Log.e(LOG_FILE_NAME, "showing file picker", e);
      }
    }
    try {
      mFilePickerResult.put(filePickerResult);
    } catch (InterruptedException e) {
      Log.i(LOG_FILE_NAME, "error returning file picker result", e);
    }
  }
Esempio n. 3
0
  private boolean unpackFile(ZipFile zip, byte[] buf, ZipEntry fileEntry, String name)
      throws IOException, FileNotFoundException {
    if (fileEntry == null) fileEntry = zip.getEntry(name);
    if (fileEntry == null)
      throw new FileNotFoundException("Can't find " + name + " in " + zip.getName());

    File outFile = new File(sGREDir, name);
    if (outFile.lastModified() == fileEntry.getTime() && outFile.length() == fileEntry.getSize())
      return false;

    File dir = outFile.getParentFile();
    if (!dir.exists()) dir.mkdirs();

    InputStream fileStream;
    fileStream = zip.getInputStream(fileEntry);

    OutputStream outStream = new FileOutputStream(outFile);

    while (fileStream.available() > 0) {
      int read = fileStream.read(buf, 0, buf.length);
      outStream.write(buf, 0, read);
    }

    fileStream.close();
    outStream.close();
    outFile.setLastModified(fileEntry.getTime());
    return true;
  }
Esempio n. 4
0
 /**
  * Checks if a given file exists and, if not, create it by copying a default template from
  * resources; used to create default conf files.
  *
  * @param file The path of the file that needs to exist
  * @param template The path of the template for the file
  */
 public static void ensureFileExists(final String file, final String template) {
   if (LAUNCHED_FROM_JAR && !Files.exists(Paths.get(file))) {
     if (Debug.on) printDebug("[Meta] " + file + " does not exist: creating a default one.");
     InputStream stream = Meta.class.getResourceAsStream(template);
     if (stream == null) {
       printDebug(
           "[ WARNING ] template for "
               + template
               + " not found. Won't create a default "
               + file
               + ".");
     } else {
       int readBytes;
       byte[] buffer = new byte[4096];
       try (OutputStream outStream = new FileOutputStream(new File(file))) {
         while ((readBytes = stream.read(buffer)) > 0) {
           outStream.write(buffer, 0, readBytes);
         }
         if (Debug.on)
           printDebug("[Meta] created default file " + file + " from " + template + ".");
       } catch (IOException e) {
         e.printStackTrace();
       } finally {
         try {
           stream.close();
         } catch (IOException ignore) {
         }
       }
     }
   } else {
     if (Meta.LAUNCHED_FROM_JAR && Debug.on) printDebug("[Meta] file exists: " + file + ".");
   }
 }
  public static long checksumBufferedInputStream(Path filename) throws IOException {
    try (InputStream in = new BufferedInputStream(Files.newInputStream(filename))) {
      CRC32 crc = new CRC32();

      int c;
      while ((c = in.read()) != -1) crc.update(c);
      return crc.getValue();
    }
  }
Esempio n. 6
0
 /**
  * Determines from the magic number whether the given InputStream points to a DDS image. The given
  * InputStream must return true from markSupported() and support a minimum of four bytes of
  * read-ahead.
  *
  * @param in Stream to check
  * @return true if input stream is DDS image or false otherwise
  * @throws java.io.IOException if an I/O exception occurred
  */
 public static boolean isDDSImage(InputStream in) throws IOException {
   if (!(in instanceof BufferedInputStream)) {
     in = new BufferedInputStream(in);
   }
   if (!in.markSupported()) {
     throw new IOException(
         "Can not test non-destructively whether given InputStream is a DDS image");
   }
   in.mark(4);
   int magic = 0;
   for (int i = 0; i < 4; i++) {
     int tmp = in.read();
     if (tmp < 0) {
       in.reset();
       return false;
     }
     magic = ((magic >>> 8) | (tmp << 24));
   }
   in.reset();
   return (magic == MAGIC);
 }
Esempio n. 7
0
  public void mainloop() {

    while (!client.isConnected()) {
      try {
        System.out.println("Connecting to " + hostname + ":" + port);
        client.connect(hostname, port);
      } catch (IOException e) {
      }
      if (!client.isConnected()) {
        System.out.println("Couldn't connect. waiting");
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          run = false;
          System.exit(-1);
        }
      }
    }

    // Load the header information in one go into a bytebuffer
    byte[] rawbytebuf = new byte[BUFFERSIZE];

    int n = 0;

    try {
      n = headerReader.read(rawbytebuf);
    } catch (IOException e) {
      e.printStackTrace();
    }

    // Byte-buffer used to parse the byte-stream. Force native ordering
    ByteBuffer hdrBuf = ByteBuffer.wrap(rawbytebuf, 0, n);
    hdrBuf.order(ByteOrder.nativeOrder());
    Header hdr = new Header(hdrBuf);
    if (VERB > 0) {
      System.out.println("Sending header: " + hdr.toString());
    }
    hdr.nSamples = 0; // reset number of samples to 0

    try {
      client.putHeader(hdr);
    } catch (IOException e) {
      e.printStackTrace();
    }

    // Interval between sending samples to the buffer
    int pktSamples = hdr.nChans * blockSize; // number data samples in each buffer packet
    int pktBytes = pktSamples * DataType.wordSize[hdr.dataType];
    int nsamp = 0; // sample counter
    int nblk = 0;
    int nevent = 0;
    byte[] samples = new byte[pktBytes];

    // Size of the event header: type,type_numel,val,val_numel,sample,offset,duration,bufsz
    int evtHdrSz = DataType.wordSize[DataType.INT32] * 8;
    byte[] evtRawBuf = new byte[BUFFERSIZE]; // buffer to hold complete event structure

    // Byte-buffer used to parse the byte-stream. Force native ordering
    ByteBuffer evtBuf = ByteBuffer.wrap(evtRawBuf);
    evtBuf.order(ByteOrder.nativeOrder());
    int payloadSz = 0;
    int evtSample = 0;
    int evtSz = 0;
    long sample_ms = 0;
    long starttime_ms = java.lang.System.currentTimeMillis();
    long elapsed_ms = 0;
    long print_ms = 0;

    // Now do the data forwarding
    boolean eof = false;

    while (!eof
        && run) { // The run switch allows control of stopping the thread and getting out of the
      // loop
      // Read one buffer packets worth of samples
      // increment the cursor position
      if (VERB > 0 && elapsed_ms > print_ms + 500) {
        print_ms = elapsed_ms;
        System.out.println(
            nblk
                + " "
                + nsamp
                + " "
                + nevent
                + " "
                + (elapsed_ms / 1000)
                + " (blk,samp,event,sec)\r");
      }

      // read and write the samples
      try {
        n = dataReader.read(samples);
      } catch (IOException e) {
        e.printStackTrace();
      }
      if (n <= 0) {
        eof = true;
        break;
      } // stop if run out of samples

      try {
        client.putRawData(blockSize, hdr.nChans, hdr.dataType, samples);
      } catch (IOException e) {
        e.printStackTrace();
      }

      // update the sample count
      nsamp += blockSize;
      while (evtSample <= nsamp) {
        if (evtSample > 0) { // send the current event
          try {
            client.putRawEvent(evtRawBuf, 0, evtSz);
          } catch (IOException e) {
            e.printStackTrace();
          }
          nevent++;
        }

        // read the next event
        try {
          n = eventReader.read(evtRawBuf, 0, evtHdrSz); // read the fixed size header
        } catch (IOException e) {
          e.printStackTrace();
        }
        if (n <= 0) {
          eof = true;
          break;
        }
        evtSample = ((ByteBuffer) evtBuf.position(4 * 4)).getInt(); // sample index for this event
        payloadSz = ((ByteBuffer) evtBuf.position(4 * 7)).getInt(); // payload size for this event
        evtSz = evtHdrSz + payloadSz;

        // read the variable part
        try {
          n = eventReader.read(evtRawBuf, evtHdrSz, payloadSz);
        } catch (IOException e) {
          e.printStackTrace();
        }
        if (n <= 0) {
          eof = true;
          break;
        }

        // print the event we just read
        if (VERB > 1) {
          ByteBuffer tmpev = ByteBuffer.wrap(evtRawBuf, 0, evtSz);
          tmpev.order(evtBuf.order());
          BufferEvent evt = new BufferEvent(tmpev);
          System.out.println("Read Event: " + evt);
        }
      }

      // sleep until the next packet should be send OR EOF
      /*when to send the next sample */
      sample_ms = (long) ((float) (nsamp * 1000) / hdr.fSample / (float) speedup);
      elapsed_ms = java.lang.System.currentTimeMillis() - starttime_ms; // current time
      if (sample_ms > elapsed_ms)
        try {
          Thread.sleep(sample_ms - elapsed_ms);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      nblk++;
    }

    stop();
  }
Esempio n. 8
0
  public static void main(String[] args) throws Exception {
    //////////////////// STAGE A//////////////////////////////////////////
    int portNum = 12235;
    //        InetAddress ip=InetAddress.getLocalHost();
    InetAddress ip = InetAddress.getByName("attu2.cs.washington.edu");

    DatagramSocket sock = new DatagramSocket();

    byte[] response = new byte[HEADER_SIZE + 16];
    String partA = "hello world\0";
    byte[] buf = createBuffer(partA.getBytes(), 0, STEP1);
    DatagramPacket packet = new DatagramPacket(buf, buf.length, ip, portNum);
    sock.send(packet);
    packet = new DatagramPacket(response, response.length);
    sock.receive(packet);
    int[] a2 = partA(response); // putting the 4 ints from server into int[]

    //      for (int i = 0; i < a2.length; i++) {
    //          System.out.println(a2[i]);
    //      }

    ////////////////////// STAGE B////////////////////////////////////////

    int numSent = 0;
    int send = a2[0];
    int len = a2[1];
    portNum = a2[2];
    int secretA = a2[3];
    System.out.println("The secrets:\nA: " + secretA);

    sock.setSoTimeout(500); // .5s

    while (numSent < send) {
      // create packet
      buf = createBuffer(partB(numSent, len), secretA, STEP1);
      packet = new DatagramPacket(buf, buf.length, ip, portNum);
      sock.send(packet);
      // send packet
      try {
        sock.receive(new DatagramPacket(response, response.length));
        numSent++;
        ByteBuffer temp = ByteBuffer.wrap(response);
        checkHeader(temp, 4, secretA, STEP1);
        //              System.out.println(temp.getInt());  // For debug. See if counts up by 1
      } catch (SocketTimeoutException e) {
        // if there's a timeout, try again
        continue;
      }
    }
    response = new byte[HEADER_SIZE + 8]; // 8 bytes -- 2 integers
    sock.receive(new DatagramPacket(response, response.length));
    ByteBuffer bb = ByteBuffer.wrap(response);
    // Header
    checkHeader(bb, 8, secretA, STEP2);

    // reset the port number to the one given
    portNum = bb.getInt();
    int secretB = bb.getInt();
    System.out.println("B: " + secretB);

    // close the UDP socket
    sock.close();

    /////////////////////////// STAGE C///////////////////////////////////
    Socket socket = new Socket(ip, portNum);
    InputStream in = socket.getInputStream();
    OutputStream out = socket.getOutputStream();
    response = new byte[HEADER_SIZE + 16]; // 4 ints given to us this time
    in.read(response);
    bb = ByteBuffer.wrap(response);
    // Header
    checkHeader(bb, 13, secretB, STEP2);

    // num2 len2 secretC and char c

    numSent = bb.getInt();
    len = bb.getInt();
    int secretC = bb.getInt();
    System.out.println("C: " + secretC);

    // stage d
    byte c = (byte) bb.getChar();
    buf = new byte[len];
    Arrays.fill(buf, c);
    for (int i = 0; i < numSent; i++) {
      byte[] b = createBuffer(buf, secretC, STEP1);
      out.write(b);
    }
    response = new byte[12 + 4]; // one integer. secretD plus header
    in.read(response);
    bb = ByteBuffer.wrap(response);
    checkHeader(bb, 4, secretC, STEP2);

    int secretD = bb.getInt();
    socket.close();
    in.close();
    out.close();
    System.out.println("D: " + secretD);
  }