Exemple #1
0
 private int atariChecksum(String filePath, int offset) {
   FileInputStream f = null;
   try {
     int cksum = 0;
     f = new FileInputStream(filePath);
     int b = -1;
     // we only calculate the checksum for the rom data, starting
     // at offset 16
     f.skip(offset);
     while ((b = f.read()) > -1) {
       cksum += b;
     }
     return cksum;
   } catch (Throwable e) {
     e.printStackTrace();
     return -1;
   } finally {
     if (null != f) {
       try {
         f.close();
       } catch (Throwable e) {
         e.printStackTrace();
       }
     }
   }
 }
Exemple #2
0
  public void readID3Tag(String a) {
    try {
      URI anURI = new URI(a);
      String astring = anURI.toString();
      File song = new File(astring);

      File[] list = song.listFiles();
      for (int i = 0; i < list.length; i++) {
        FileInputStream file = new FileInputStream(list[i]);
        int size = (int) list[i].length();
        file.skip(size - 128);
        byte[] last128 = new byte[128];
        file.read(last128);
        String id3 = new String(last128);
        String tag = id3.substring(0, 3);
        if (tag.equals("TAG")) {
          name = "Title: " + id3.substring(3, 32);
          artist = "Artist: " + id3.substring(33, 62);
          album = "Album: " + id3.substring(63, 91);
        } else System.out.println(" does not contain ID3 info.");
        file.close();
      }
    } catch (Exception e) {
      System.out.println("Error ? " + e.toString());
    }
  }
 @Override
 public long skip(long n) throws IOException {
   abortIfNeeded();
   long skipped = fis.skip(n);
   bytesReadPastMarkPoint += skipped;
   return skipped;
 }
 public boolean accept(File value) {
   FileInputStream in = null;
   try {
     in = new FileInputStream(value);
   } catch (FileNotFoundException e) {
     return false;
   }
   try {
     long length = in.skip(128l);
     if (length != 128l) {
       in.close();
       return false;
     }
     byte[] read = new byte[4];
     length = in.read(read);
     if (length != 4l) {
       in.close();
       return false;
     }
     String test = new String(read);
     if (test.equalsIgnoreCase("DICM")) {
       in.close();
       return true;
     } else {
       in.close();
       return false;
     }
   } catch (IOException e) {
     log("Error reading file");
     return false;
   }
 }
 /**
  * Read a log file from start to end positions. The offsets may be negative, in which case they
  * are relative to the end of the file. For example, Reader(taskid, kind, 0, -1) is the entire
  * file and Reader(taskid, kind, -4197, -1) is the last 4196 bytes.
  *
  * @param taskid the id of the task to read the log file for
  * @param kind the kind of log to read
  * @param start the offset to read from (negative is relative to tail)
  * @param end the offset to read upto (negative is relative to tail)
  * @param isCleanup whether the attempt is cleanup attempt or not
  * @throws IOException
  */
 public Reader(TaskAttemptID taskid, LogName kind, long start, long end, boolean isCleanup)
     throws IOException {
   // find the right log file
   Map<LogName, LogFileDetail> allFilesDetails = getAllLogsFileDetails(taskid, isCleanup);
   LogFileDetail fileDetail = allFilesDetails.get(kind);
   // calculate the start and stop
   long size = fileDetail.length;
   if (start < 0) {
     start += size + 1;
   }
   if (end < 0) {
     end += size + 1;
   }
   start = Math.max(0, Math.min(start, size));
   end = Math.max(0, Math.min(end, size));
   start += fileDetail.start;
   end += fileDetail.start;
   bytesRemaining = end - start;
   String owner = obtainLogDirOwner(taskid);
   file = SecureIOUtils.openForRead(new File(fileDetail.location, kind.toString()), owner);
   // skip upto start
   long pos = 0;
   while (pos < start) {
     long result = file.skip(start - pos);
     if (result < 0) {
       bytesRemaining = 0;
       break;
     }
     pos += result;
   }
 }
Exemple #6
0
  /**
   * Reads the version string from a signed update file.
   *
   * @param signedFile A signed update file.
   * @return The version string read, or an empty string if no version string is present.
   */
  public static String getVersionString(File signedFile) {
    FileInputStream fileInputStream = null;

    try {
      fileInputStream = new FileInputStream(signedFile);
      long skipped = fileInputStream.skip(Signature.SIGNATURE_BYTES);
      if (skipped != Signature.SIGNATURE_BYTES) return "";
      byte[] data = new byte[VERSION_BYTES];
      int bytesRead = DataHelper.read(fileInputStream, data);

      if (bytesRead != VERSION_BYTES) {
        return "";
      }

      for (int i = 0; i < VERSION_BYTES; i++)
        if (data[i] == 0x00) {
          return new String(data, 0, i, "UTF-8");
        }

      return new String(data, "UTF-8");
    } catch (UnsupportedEncodingException uee) {
      throw new RuntimeException("wtf, your JVM doesnt support utf-8? " + uee.getMessage());
    } catch (IOException ioe) {
      return "";
    } finally {
      if (fileInputStream != null)
        try {
          fileInputStream.close();
        } catch (IOException ioe) {
        }
    }
  }
Exemple #7
0
 public static FileInputStream resetInput(FileInputStream stream, File in, long toPoint)
     throws IOException {
   stream.close();
   FileInputStream ret = new FileInputStream(in);
   ret.skip(toPoint);
   return ret;
 }
 @Override
 public long skip(long n) throws IOException {
   long value = fis.skip(n);
   if (value > 0) {
     this.position += value;
   }
   return value;
 }
Exemple #9
0
  /**
   * If this is an audio ubin, we store the resource as a file that can be played with MediaPlayer.
   *
   * @param ubinData An object honding information about this resource.
   * @param resHandle The id of the audio resource.
   */
  public void storeIfAudioUBin(UBinData ubinData, int resHandle) {
    SYSLOG("MoSyncSound.storeIfAudioUBin - ubinData.getSize(): " + ubinData.getSize() + "bytes");

    if (!checkIfMimeAudioType(ubinData)) {
      // This is not an audio resource.
      return;
    }

    try {
      // Open the resource file.
      AssetManager assetManager = getActivity().getAssets();
      // RESOURCE_FILE = "resources.mp3"
      AssetFileDescriptor fileDescriptor = assetManager.openFd(MoSyncThread.RESOURCE_FILE);
      FileInputStream inputStream = fileDescriptor.createInputStream();

      // Jump to beginning of resource.
      inputStream.skip(ubinData.getOffset() - mMoSyncThread.getResourceStartOffset());

      // Read mime string.
      String mimeType = readMimeStringFromFile(inputStream);
      int mimeStringLength = mimeType.length() + 1;

      // Calculate size of audio data.
      int length = ubinData.getSize() - mimeStringLength;

      // Create buffer to hold audio data.
      byte[] buffer = new byte[length];

      // We should be at the start of audio data after reading the mime string.
      inputStream.read(buffer);

      // Close input stream.
      inputStream.close();

      // Create a temporary audio file
      String fileName = "MOSYNCTEMP:audio" + resHandle + ".tmp";
      FileOutputStream outputStream =
          getActivity()
              .openFileOutput(fileName, Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);

      // Write audio data.
      outputStream.write(buffer);

      // Close output steram.
      outputStream.close();

      // Store sound data in audio table.
      // TODO: Unify AudioStore with UBinData ?
      mAudioStores.put(resHandle, new AudioStore(mimeType, length, fileName));
    } catch (Exception ex) {
      Log.e("MoSyncAudio.storeIfAudioUBin", "Unable to save temporary audio file.");
      ex.printStackTrace();
    }
  }
Exemple #10
0
 public static byte[] getSliceBytes(File file, Integer offset, Integer length) {
   byte[] buffer = new byte[length];
   try {
     if (file == null) return null;
     FileInputStream in = new FileInputStream(file);
     in.skip(offset);
     in.read(buffer);
     in.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return buffer;
 }
 /** 准备更新一个新的xml */
 public void init4updateXml() {
   try {
     fis = new FileInputStream(fullPath);
     fis.skip(headBytes.getBytes().length);
     builder = new SAXBuilder();
     doc = builder.build(fis);
     root = doc.getRootElement();
     nodes = root.getChild("nodes");
   } catch (Exception e) {
     e.printStackTrace();
     SysLogger.error("Error in XmlOperator.init4updateXml(),file=" + fullPath);
   }
 }
Exemple #12
0
 private void calculateDigest() {
   assert headSize.get() == headLength : "Head hasn't catched up, can't calculate digest";
   try {
     FileInputStream stream = new FileInputStream(file);
     stream.skip(headLength);
     byte[] buffer = new byte[4096];
     int bytesRead;
     while ((bytesRead = stream.read(buffer, 0, 4096)) > 0) {
       md.update(buffer, 0, bytesRead);
     }
     stream.close();
   } catch (IOException ex) {
     logger.error("error accessing file to calculate digest", ex);
   }
 }
  protected void fillBuffer() throws IOException {
    if (_eofReached) {
      return;
    }

    if (_bufferPtr < 0) {
      throw new IOException("Invalid Buffer Pointer: " + _bufferPtr);
    }

    if (_bufferPtr > 0) {
      // Do some housekeeping on our _buffer
      if (_bufferPtr < _bufferSize) {
        // Move any existing data to the front of the _buffer...
        // A circular _buffer would be faster, but we're really only talking
        // about a few dozen bytes at a time.

        // Note that System.arraycopy is explicitly safe for self-to-self copies.
        System.arraycopy(_buffer, _bufferPtr, _buffer, 0, _bufferSize - _bufferPtr);
        _bufferSize = _bufferSize - _bufferPtr;
      } else {
        // If we've precisely exhausted our _buffer (_bufferPtr should never be >
        // _bufferSize), then don't bother copying;
        _bufferSize = 0;
      }
      _bufferPtr = 0;
    }

    FileInputStream fis = new FileInputStream(_file);
    int bytesRead = -100;
    try {
      if (_filePtr > 0) {
        for (long i = 0; i < _filePtr; i += fis.skip(_filePtr - i)) {}
      }

      bytesRead = fis.read(_buffer, _bufferSize, _buffer.length - _bufferSize);

      if (bytesRead < 0) {
        _eofReached = true;
      } else {
        _bufferSize += bytesRead;
        _filePtr += bytesRead;
      }
    } finally {
      fis.close();
    }

    // System.err.println("==== Filling : "+stats()+"; read="+bytesRead+" ====");
  }
  public void test_skipJ() throws IOException {
    byte[] buf1 = new byte[10];
    is = new FileInputStream(fileName);
    is.skip(1000);
    is.read(buf1, 0, buf1.length);
    assertTrue(
        "Test 1: Failed to skip to correct position.",
        new String(buf1, 0, buf1.length).equals(fileString.substring(1000, 1010)));

    is.close();
    try {
      is.read();
      fail("Test 2: IOException expected.");
    } catch (IOException e) {
      // Expected.
    }
  }
Exemple #15
0
  private void initSomePoints() {
    File file;
    // if( Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ) {
    // String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
    // file = new File(baseDir + File.separator + fileName);
    file = new File(Global.file);
    if (file.isFile()) {
      try {
        // DataInputStream data = new DataInputStream(new FileInputStream(file));
        FileInputStream data = new FileInputStream(file);
        String magicNumber;
        byte[] magicNumberByte = new byte[4];

        int lengthFile = (int) (file.length() - 5);
        sizeBuffer = lengthFile;

        data.read(magicNumberByte, 0, 4);
        magicNumber = new String(magicNumberByte);
        if (magicNumber.equals("PCl2")) {
          // Log.d(TAG,"Magic Number = PCL2");
          mPointCloudWithColor = true;
          totalPoints = (lengthFile / 15);
        } else {
          // Log.d(TAG,"Magic Number = PCL1");
          mPointCloudWithColor = false;
          problemBufferInterleaved = false;
          totalPoints = (lengthFile / 12);
        }
        System.gc();

        buffer = ByteBuffer.allocate(lengthFile);
        // buffer.order(ByteOrder.BIG_ENDIAN);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        buffer.position(0);
        data.skip(1); // pula o '\n' depois do número mágico
        data.read(buffer.array(), 0, lengthFile);
        // data.readFully( buffer.array(),0,lengthFile );

        data.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    // }
  }
  @Override
  public FormatInfo process(String templatePath, ImageFormat format, String templateName) {
    if (format != null) {
      s_logger.debug("We currently don't handle conversion from " + format + " to QCOW2.");
      return null;
    }

    String qcow2Path =
        templatePath + File.separator + templateName + "." + ImageFormat.QCOW2.getFileExtension();

    if (!_storage.exists(qcow2Path)) {
      s_logger.debug("Unable to find the qcow2 file: " + qcow2Path);
      return null;
    }

    FormatInfo info = new FormatInfo();
    info.format = ImageFormat.QCOW2;
    info.filename = templateName + "." + ImageFormat.QCOW2.getFileExtension();

    File qcow2File = _storage.getFile(qcow2Path);

    info.size = _storage.getSize(qcow2Path);
    FileInputStream strm = null;
    byte[] b = new byte[8];
    try {
      strm = new FileInputStream(qcow2File);
      strm.skip(24);
      strm.read(b);
    } catch (Exception e) {
      s_logger.warn("Unable to read qcow2 file " + qcow2Path, e);
      return null;
    } finally {
      if (strm != null) {
        try {
          strm.close();
        } catch (IOException e) {
        }
      }
    }

    long templateSize = NumbersUtil.bytesToLong(b);
    info.virtualSize = templateSize;

    return info;
  }
  public void test_read$B() throws IOException {
    byte[] buf1 = new byte[100];
    is = new FileInputStream(fileName);
    is.skip(3000);
    is.read(buf1);
    is.close();
    assertTrue(
        "Test 1: Failed to read correct data.",
        new String(buf1, 0, buf1.length).equals(fileString.substring(3000, 3100)));

    is.close();
    try {
      is.read(buf1);
      fail("Test 2: IOException expected.");
    } catch (IOException e) {
      // Expected.
    }
  }
 public static void main(String[] args) {
   try {
     LinkedHashMap<Long, Long> readers =
         SolrMultiThreadIndexingJob.getReaders(args[0], Integer.parseInt(args[1]));
     System.out.println(readers.toString());
     File file = new File(args[0]);
     FileInputStream fileInputStreamMain = new FileInputStream(file);
     for (Long key : readers.keySet()) {
       fileInputStreamMain.close();
       fileInputStreamMain = new FileInputStream(file);
       fileInputStreamMain.skip(readers.get(key));
       System.out.println(((char) fileInputStreamMain.read()) == lineBreak);
     }
     LinkedHashMap<String, Integer> distribution =
         SolrMultiThreadIndexingJob.getThreadsPerFile(Arrays.asList(fileNames), 500);
     System.out.println(distribution.toString());
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Exemple #19
0
  /**
   * Checks if the header of a resource is of audio mime type.
   *
   * @param ubinData A description of a ubin resource.
   * @return true if the header is of type "audio", false if not.
   */
  final boolean checkIfMimeAudioType(UBinData ubinData) {
    try {
      // Open the resource file.
      AssetManager assetManager = getActivity().getAssets();
      // RESOURCE_FILE = "resources.mp3"
      AssetFileDescriptor fileDescriptor = assetManager.openFd(MoSyncThread.RESOURCE_FILE);
      FileInputStream stream = fileDescriptor.createInputStream();

      // Jump to start of this audio resource.
      stream.skip(ubinData.getOffset() - mMoSyncThread.getResourceStartOffset());

      // Determine if this is an audio file by examining the header bytes.
      byte header[] = new byte[5];
      stream.read(header);
      stream.close();
      return checkIfMimeAudioType(header);
    } catch (Exception ex) {
      ex.printStackTrace();
      return false;
    }
  }
  public TaskLog getLog(long offset, int length) {
    File logFile = getLogFile();
    if (logFile.exists()) {
      FileInputStream fi = null;
      try {
        fi = new FileInputStream(logFile);
        if ((offset < 0) || (length < 0)) {
          return new TaskLog(new byte[0], 0);
        } else {
          if (logFile.length() <= offset) {
            return new TaskLog(new byte[0], 0);
          } else {
            fi.skip(offset);
            byte[] buffer = new byte[length];
            int remaining = length;
            while (remaining > 0) {
              int location = length - remaining;
              int count = fi.read(buffer, 0 + location, remaining);
              if (count == -1) { // EOF
                break;
              }
              remaining -= count;
            }
            int readLength = length - remaining;

            return new TaskLog(buffer, readLength);
          }
        }

      } catch (Throwable e) {
        log.error(
            String.format("Exception occurs while getting log(txId=%s)", Long.toString(this.id)),
            e);
      } finally {
        IOUtils.closeQuietly(fi);
      }
    }

    return new TaskLog(new byte[0], 0);
  }
Exemple #21
0
  /**
   * Extract the file. Skips and ignores the signature and version. No verification.
   *
   * @param signedFile A signed update file.
   * @param outputFile The file to write the verified data to.
   * @return <code>null</code> if the data was moved, and an error <code>String</code> otherwise.
   * @since 0.7.12
   */
  public String migrateFile(File signedFile, File outputFile) {
    if (!signedFile.exists()) return "File not found: " + signedFile.getAbsolutePath();

    FileInputStream fileInputStream = null;
    FileOutputStream fileOutputStream = null;

    try {
      fileInputStream = new FileInputStream(signedFile);
      fileOutputStream = new FileOutputStream(outputFile);
      long skipped = 0;

      while (skipped < HEADER_BYTES) skipped += fileInputStream.skip(HEADER_BYTES - skipped);

      byte[] buffer = new byte[16 * 1024];
      int bytesRead = 0;

      while ((bytesRead = fileInputStream.read(buffer)) != -1)
        fileOutputStream.write(buffer, 0, bytesRead);
    } catch (IOException ioe) {
      // probably permissions or disk full, so bring the message out to the console
      return "Error copying update: " + ioe;
    } finally {
      if (fileInputStream != null)
        try {
          fileInputStream.close();
        } catch (IOException ioe) {
        }

      if (fileOutputStream != null)
        try {
          fileOutputStream.close();
        } catch (IOException ioe) {
        }
    }

    return null;
  }
Exemple #22
0
  public static String md5(File file) throws Exception {
    FileInputStream is = new FileInputStream(file);
    char hexDigits[] = {
      '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    };
    MessageDigest md5 = null;
    try {
      md5 = MessageDigest.getInstance("MD5");
      int n = 0;
      byte[] buffer = new byte[1024];
      do {
        n = is.read(buffer);
        if (n > 0) {
          md5.update(buffer, 0, n);
        }
      } while (n != -1);
      is.skip(0);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      throw new RuntimeException(e.getMessage());
    } finally {
      is.close();
    }

    byte[] encodedValue = md5.digest();

    int j = encodedValue.length;
    char finalValue[] = new char[j * 2];
    int k = 0;
    for (int i = 0; i < j; i++) {
      byte encoded = encodedValue[i];
      finalValue[k++] = hexDigits[encoded >> 4 & 0xf];
      finalValue[k++] = hexDigits[encoded & 0xf];
    }

    return new String(finalValue);
  }
Exemple #23
0
  public byte[] getABlob(int row, int column) {
    int nRead = 0;
    int nOffset = 0;
    int nBufSize = 0;

    if ((column == 1) && (theFile != null)) {
      try {
        FileInputStream fin = new FileInputStream(theFile);
        nOffset = row * BUFSIZE;
        if (row < (nCount - 1)) {
          nBufSize = BUFSIZE;
        } else {
          nBufSize = (int) (lFileSize - nOffset);
        }
        theBuffer = new byte[nBufSize];

        if (theBuffer != null) {
          if (fin.skip(nOffset + lOffset) == (nOffset + lOffset)) {
            if ((nRead = fin.read(theBuffer, 0, nBufSize)) != -1) {
              if (nRead != nBufSize) {
                return null;
              }
            }
          }
        }

        fin.close();
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    return theBuffer;
  }
  /**
   * Renvoi la partie <b>partie</b> du fichier d'identifiant <b>id</b>.
   *
   * @param id String
   * @param partie int
   * @return un tableau de byte[], null en cas d'erreur.
   */
  public byte[] telechargerFichier(String id, long partie) {
    System.out.println("Telechargement de : " + id + ", partie : " + partie);
    if (!listeFichier.containsKey(id)) /* On a pas le fichier */ return null;
    AttributFichierClient atc = (AttributFichierClient) listeFichier.get(id);
    if (null == atc) /* On a pas les attributs du fichier du client */ return null;
    gui.addUpload(
        atc.getNomFichierAbsolu()
            + " "
            + atc.getNbPartieTotale()
            + " parties "
            + atc.getDateDerModif().toString());
    try {
      FileInputStream fread = new FileInputStream(atc.getNomFichierAbsolu());
      byte[] b = new byte[MAX_OCTET_LU];
      /* placement de la tete de lecture au bon endroit */
      long deplacement = partie * MAX_OCTET_LU;
      if (deplacement != fread.skip(deplacement))
        return null; /* on a pas réussi a se déplacer au bon endroit du fichier */
      /* Lecture des octets dans le fichier */
      int nbOctetLu = fread.read(b, 0, MAX_OCTET_LU);

      /* vérification qu'on a bien pu lire le nombre d'octet. attention pour la derniere partie
             A FAIRE
      */
      return b;

    } catch (java.io.FileNotFoundException ex1) {
      /* On a plus le fichier, on le retire du client */
      retirerFichier(id);
      /* prevenir le serveur ??? dans telechargeFichier de client ? */
      ex1.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
Exemple #25
0
  /**
   * Serves file from homeDir and its' subdirectories (only). Uses only URI, ignores all headers and
   * HTTP parameters.
   */
  Response serveFile(String uri, Map<String, String> header, File file, String mime) {
    Response res;
    try {
      // Calculate etag
      String etag =
          Integer.toHexString(
              (file.getAbsolutePath() + file.lastModified() + "" + file.length()).hashCode());

      // Support (simple) skipping:
      long startFrom = 0;
      long endAt = -1;
      String range = header.get("range");
      if (range != null) {
        if (range.startsWith("bytes=")) {
          range = range.substring("bytes=".length());
          int minus = range.indexOf('-');
          try {
            if (minus > 0) {
              startFrom = Long.parseLong(range.substring(0, minus));
              endAt = Long.parseLong(range.substring(minus + 1));
            }
          } catch (NumberFormatException ignored) {
          }
        }
      }

      // Change return code and add Content-Range header when skipping is
      // requested
      long fileLen = file.length();
      if (range != null && startFrom >= 0) {
        if (startFrom >= fileLen) {
          res = createResponse(Response.Status.RANGE_NOT_SATISFIABLE, NanoHTTPD.MIME_PLAINTEXT, "");
          res.addHeader("Content-Range", "bytes 0-0/" + fileLen);
          res.addHeader("ETag", etag);
        } else {
          if (endAt < 0) {
            endAt = fileLen - 1;
          }
          long newLen = endAt - startFrom + 1;
          if (newLen < 0) {
            newLen = 0;
          }

          final long dataLen = newLen;
          FileInputStream fis =
              new FileInputStream(file) {
                @Override
                public int available() throws IOException {
                  return (int) dataLen;
                }
              };
          fis.skip(startFrom);

          res = createResponse(Response.Status.PARTIAL_CONTENT, mime, fis);
          res.addHeader("Content-Length", "" + dataLen);
          res.addHeader("Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen);
          res.addHeader("ETag", etag);
        }
      } else {
        if (etag.equals(header.get("if-none-match")))
          res = createResponse(Response.Status.NOT_MODIFIED, mime, "");
        else {
          res = createResponse(Response.Status.OK, mime, new FileInputStream(file));
          res.addHeader("Content-Length", "" + fileLen);
          res.addHeader("ETag", etag);
        }
      }
    } catch (IOException ioe) {
      res =
          createResponse(
              Response.Status.FORBIDDEN,
              NanoHTTPD.MIME_PLAINTEXT,
              "FORBIDDEN: Reading file failed.");
    }

    return res;
  }
 /**
  * Skips at most {@code n} bytes in this stream. This method does nothing and returns 0 if {@code
  * n} is negative, but some subclasses may throw.
  *
  * <p>Note the "at most" in the description of this method: this method may choose to skip fewer
  * bytes than requested. Callers should <i>always</i> check the return value.
  *
  * <p>This default implementation reads bytes into a temporary buffer. Concrete subclasses should
  * provide their own implementation.
  *
  * @param byteCount the number of bytes to skip.
  * @return the number of bytes actually skipped.
  * @throws IOException if this stream is closed or another IOException occurs.
  */
 @Override
 public long skip(long byteCount) throws IOException {
   return fis.skip(byteCount);
 }
Exemple #27
0
  /**
   * Serves file from homeDir and its' subdirectories (only). Uses only URI, ignores all headers and
   * HTTP parameters.
   */
  public Response serveFile(
      String uri, Properties header, File homeDir, boolean allowDirectoryListing) {
    Response res = null;

    // Make sure we won't die of an exception later
    if (!homeDir.isDirectory())
      res =
          new Response(
              HTTP_INTERNALERROR,
              MIME_PLAINTEXT,
              "INTERNAL ERRROR: serveFile(): given homeDir is not a directory.");

    if (res == null) {
      // Remove URL arguments
      uri = uri.trim().replace(File.separatorChar, '/');
      if (uri.indexOf('?') >= 0) uri = uri.substring(0, uri.indexOf('?'));

      // Prohibit getting out of current directory
      if (uri.startsWith("..") || uri.endsWith("..") || uri.indexOf("../") >= 0)
        res =
            new Response(
                HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: Won't serve ../ for security reasons.");
    }

    File f = new File(homeDir, uri);
    if (res == null && !f.exists())
      res = new Response(HTTP_NOTFOUND, MIME_PLAINTEXT, "Error 404, file not found.");

    // List the directory, if necessary
    if (res == null && f.isDirectory()) {
      // Browsers get confused without '/' after the
      // directory, send a redirect.
      if (!uri.endsWith("/")) {
        uri += "/";
        res =
            new Response(
                HTTP_REDIRECT,
                MIME_HTML,
                "<html><body>Redirected: <a href=\"" + uri + "\">" + uri + "</a></body></html>");
        res.addHeader("Location", uri);
      }

      if (res == null) {
        // First try index.html and index.htm
        if (new File(f, "index.html").exists()) f = new File(homeDir, uri + "/index.html");
        else if (new File(f, "index.htm").exists()) f = new File(homeDir, uri + "/index.htm");
        // No index file, list the directory if it is readable
        else if (allowDirectoryListing && f.canRead()) {
          String[] files = f.list();
          String msg = "<html><body><h1>Directory " + uri + "</h1><br/>";

          if (uri.length() > 1) {
            String u = uri.substring(0, uri.length() - 1);
            int slash = u.lastIndexOf('/');
            if (slash >= 0 && slash < u.length())
              msg += "<b><a href=\"" + uri.substring(0, slash + 1) + "\">..</a></b><br/>";
          }

          if (files != null) {
            for (int i = 0; i < files.length; ++i) {
              File curFile = new File(f, files[i]);
              boolean dir = curFile.isDirectory();
              if (dir) {
                msg += "<b>";
                files[i] += "/";
              }

              msg += "<a href=\"" + encodeUri(uri + files[i]) + "\">" + files[i] + "</a>";

              // Show file size
              if (curFile.isFile()) {
                long len = curFile.length();
                msg += " &nbsp;<font size=2>(";
                if (len < 1024) msg += len + " bytes";
                else if (len < 1024 * 1024)
                  msg += len / 1024 + "." + (len % 1024 / 10 % 100) + " KB";
                else msg += len / (1024 * 1024) + "." + len % (1024 * 1024) / 10 % 100 + " MB";

                msg += ")</font>";
              }
              msg += "<br/>";
              if (dir) msg += "</b>";
            }
          }
          msg += "</body></html>";
          res = new Response(HTTP_OK, MIME_HTML, msg);
        } else {
          res = new Response(HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: No directory listing.");
        }
      }
    }

    try {
      if (res == null) {
        // Get MIME type from file name extension, if possible
        String mime = null;
        int dot = f.getCanonicalPath().lastIndexOf('.');
        if (dot >= 0)
          mime = (String) theMimeTypes.get(f.getCanonicalPath().substring(dot + 1).toLowerCase());
        if (mime == null) mime = MIME_DEFAULT_BINARY;

        // Calculate etag
        String etag =
            Integer.toHexString(
                (f.getAbsolutePath() + f.lastModified() + "" + f.length()).hashCode());

        // Support (simple) skipping:
        long startFrom = 0;
        long endAt = -1;
        String range = header.getProperty("range");
        if (range != null) {
          if (range.startsWith("bytes=")) {
            range = range.substring("bytes=".length());
            int minus = range.indexOf('-');
            try {
              if (minus > 0) {
                startFrom = Long.parseLong(range.substring(0, minus));
                endAt = Long.parseLong(range.substring(minus + 1));
              }
            } catch (NumberFormatException nfe) {
            }
          }
        }

        // Change return code and add Content-Range header when skipping is requested
        long fileLen = f.length();
        if (range != null && startFrom >= 0) {
          if (startFrom >= fileLen) {
            res = new Response(HTTP_RANGE_NOT_SATISFIABLE, MIME_PLAINTEXT, "");
            res.addHeader("Content-Range", "bytes 0-0/" + fileLen);
            res.addHeader("ETag", etag);
          } else {
            if (endAt < 0) endAt = fileLen - 1;
            long newLen = endAt - startFrom + 1;
            if (newLen < 0) newLen = 0;

            final long dataLen = newLen;
            FileInputStream fis =
                new FileInputStream(f) {
                  public int available() throws IOException {
                    return (int) dataLen;
                  }
                };
            fis.skip(startFrom);

            res = new Response(HTTP_PARTIALCONTENT, mime, fis);
            res.addHeader("Content-Length", "" + dataLen);
            res.addHeader("Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen);
            res.addHeader("ETag", etag);
          }
        } else {
          if (etag.equals(header.getProperty("if-none-match")))
            res = new Response(HTTP_NOTMODIFIED, mime, "");
          else {
            res = new Response(HTTP_OK, mime, new FileInputStream(f));
            res.addHeader("Content-Length", "" + fileLen);
            res.addHeader("ETag", etag);
          }
        }
      }
    } catch (IOException ioe) {
      res = new Response(HTTP_FORBIDDEN, MIME_PLAINTEXT, "FORBIDDEN: Reading file failed.");
    }

    res.addHeader(
        "Accept-Ranges",
        "bytes"); // Announce that the file server accepts partial content requestes
    return res;
  }
 /**
  * open the file and skip to the read position
  *
  * @return returns the FileInputStream to read file
  * @since 1.0
  */
 private FileInputStream openFile() throws IOException {
   FileInputStream fs = new FileInputStream(fileName);
   fs.skip(position);
   return fs;
 }
  @SuppressWarnings("resource")
  public static void bspatch(File oldFile, File newFile, File diffFile) throws IOException {

    int oldpos, newpos;

    DataInputStream diffIn = new DataInputStream(new FileInputStream(diffFile));

    diffIn.readLong();

    // ctrlBlockLen after gzip compression at heater offset 8 (length 8
    // bytes)
    long ctrlBlockLen = diffIn.readLong();

    // diffBlockLen after gzip compression at header offset 16 (length 8
    // bytes)
    long diffBlockLen = diffIn.readLong();

    // size of new file at header offset 24 (length 8 bytes)
    int newsize = (int) diffIn.readLong();

    /*
     * System.err.println ("newsize=" + newsize); System.err.println
     * ("ctrlBlockLen=" + ctrlBlockLen); System.err.println ("diffBlockLen=" +
     * diffBlockLen); System.err.println ("newsize=" + newsize);
     */

    FileInputStream in;
    in = new FileInputStream(diffFile);
    in.skip(ctrlBlockLen + 32);
    GZIPInputStream diffBlockIn = new GZIPInputStream(in);

    in = new FileInputStream(diffFile);
    in.skip(diffBlockLen + ctrlBlockLen + 32);
    GZIPInputStream extraBlockIn = new GZIPInputStream(in);

    /*
     * Read in old file (file to be patched) to oldBuf
     */
    int oldsize = (int) oldFile.length();
    byte[] oldBuf = new byte[oldsize + 1];
    FileInputStream oldIn = new FileInputStream(oldFile);
    Util.readFromStream(oldIn, oldBuf, 0, oldsize);
    oldIn.close();

    byte[] newBuf = new byte[newsize + 1];

    try {
      oldpos = 0;
      newpos = 0;
      int[] ctrl = new int[3];
      while (newpos < newsize) {

        for (int i = 0; i <= 2; i++) {
          ctrl[i] = diffIn.readInt();
          // System.err.println ("  ctrl[" + i + "]=" + ctrl[i]);
        }

        if (newpos + ctrl[0] > newsize) {
          System.err.println("Corrupt patch\n");
          return;
        }

        /*
         * Read ctrl[0] bytes from diffBlock stream
         */

        if (!Util.readFromStream(diffBlockIn, newBuf, newpos, ctrl[0])) {
          System.err.println("error reading from extraIn");
          return;
        }

        for (int i = 0; i < ctrl[0]; i++) {
          if ((oldpos + i >= 0) && (oldpos + i < oldsize)) {
            newBuf[newpos + i] += oldBuf[oldpos + i];
          }
        }

        newpos += ctrl[0];
        oldpos += ctrl[0];

        if (newpos + ctrl[1] > newsize) {
          System.err.println("Corrupt patch");
          return;
        }

        if (!Util.readFromStream(extraBlockIn, newBuf, newpos, ctrl[1])) {
          System.err.println("error reading from extraIn");
          return;
        }

        newpos += ctrl[1];
        oldpos += ctrl[2];
      }

      // TODO: Check if at end of ctrlIn
      // TODO: Check if at the end of diffIn
      // TODO: Check if at the end of extraIn

    } finally {
      diffBlockIn.close();
      extraBlockIn.close();
      diffIn.close();
      in.close();
    }

    FileOutputStream out = new FileOutputStream(newFile);
    out.write(newBuf, 0, newBuf.length - 1);
    out.close();
  }
  /**
   * Serves file from homeDir and its' subdirectories (only). Uses only URI, ignores all headers and
   * HTTP parameters.
   */
  Response serveFile(String uri, Map<String, String> header, File file, String mime) {
    Response res;
    try {
      // Calculate etag
      String etag =
          Integer.toHexString(
              (file.getAbsolutePath() + file.lastModified() + "" + file.length()).hashCode());

      // Support (simple) skipping:
      long startFrom = 0;
      long endAt = -1;
      String range = header.get("range");
      if (range != null) {
        if (range.startsWith("bytes=")) {
          range = range.substring("bytes=".length());
          int minus = range.indexOf('-');
          try {
            if (minus > 0) {
              startFrom = Long.parseLong(range.substring(0, minus));
              endAt = Long.parseLong(range.substring(minus + 1));
            }
          } catch (NumberFormatException ignored) {
          }
        }
      }

      // get if-range header. If present, it must match etag or else we
      // should ignore the range request
      String ifRange = header.get("if-range");
      boolean headerIfRangeMissingOrMatching = (ifRange == null || etag.equals(ifRange));

      String ifNoneMatch = header.get("if-none-match");
      boolean headerIfNoneMatchPresentAndMatching =
          ifNoneMatch != null && (ifNoneMatch.equals("*") || ifNoneMatch.equals(etag));

      // Change return code and add Content-Range header when skipping is
      // requested
      long fileLen = file.length();

      if (headerIfRangeMissingOrMatching
          && range != null
          && startFrom >= 0
          && startFrom < fileLen) {
        // range request that matches current etag
        // and the startFrom of the range is satisfiable
        if (headerIfNoneMatchPresentAndMatching) {
          // range request that matches current etag
          // and the startFrom of the range is satisfiable
          // would return range from file
          // respond with not-modified
          res = newFixedLengthResponse(Response.Status.NOT_MODIFIED, mime, "");
          res.addHeader("ETag", etag);
        } else {
          if (endAt < 0) {
            endAt = fileLen - 1;
          }
          long newLen = endAt - startFrom + 1;
          if (newLen < 0) {
            newLen = 0;
          }

          FileInputStream fis = new FileInputStream(file);
          fis.skip(startFrom);

          res = newFixedLengthResponse(Response.Status.PARTIAL_CONTENT, mime, fis, newLen);
          res.addHeader("Accept-Ranges", "bytes");
          res.addHeader("Content-Length", "" + newLen);
          res.addHeader("Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen);
          res.addHeader("ETag", etag);
        }
      } else {

        if (headerIfRangeMissingOrMatching && range != null && startFrom >= fileLen) {
          // return the size of the file
          // 4xx responses are not trumped by if-none-match
          res =
              newFixedLengthResponse(
                  Response.Status.RANGE_NOT_SATISFIABLE, NanoHTTPD.MIME_PLAINTEXT, "");
          res.addHeader("Content-Range", "bytes */" + fileLen);
          res.addHeader("ETag", etag);
        } else if (range == null && headerIfNoneMatchPresentAndMatching) {
          // full-file-fetch request
          // would return entire file
          // respond with not-modified
          res = newFixedLengthResponse(Response.Status.NOT_MODIFIED, mime, "");
          res.addHeader("ETag", etag);
        } else if (!headerIfRangeMissingOrMatching && headerIfNoneMatchPresentAndMatching) {
          // range request that doesn't match current etag
          // would return entire (different) file
          // respond with not-modified

          res = newFixedLengthResponse(Response.Status.NOT_MODIFIED, mime, "");
          res.addHeader("ETag", etag);
        } else {
          // supply the file
          res = newFixedFileResponse(file, mime);
          res.addHeader("Content-Length", "" + fileLen);
          res.addHeader("ETag", etag);
        }
      }
    } catch (IOException ioe) {
      res = getForbiddenResponse("Reading file failed.");
    }

    return res;
  }