List of usage examples for java.io RandomAccessFile readFully
public final void readFully(byte b[]) throws IOException
From source file:com.liferay.faces.bridge.renderkit.primefaces.internal.PrimeFacesFileItem.java
public byte[] get() { byte[] bytes = null; try {/* ww w . ja v a 2 s . c om*/ File file = new File(uploadedFile.getAbsolutePath()); if (file.exists()) { RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); bytes = new byte[(int) randomAccessFile.length()]; randomAccessFile.readFully(bytes); randomAccessFile.close(); file.delete(); } } catch (Exception e) { logger.error(e); } return bytes; }
From source file:org.apache.jackrabbit.oak.segment.file.TarReader.java
/** * Scans through the tar file, looking for all segment entries. * * @throws IOException if the tar file could not be read *///from w ww .ja v a 2 s . co m private static void recoverEntries(File file, RandomAccessFile access, LinkedHashMap<UUID, byte[]> entries) throws IOException { byte[] header = new byte[BLOCK_SIZE]; while (access.getFilePointer() + BLOCK_SIZE <= access.length()) { // read the tar header block access.readFully(header); // compute the header checksum int sum = 0; for (int i = 0; i < BLOCK_SIZE; i++) { sum += header[i] & 0xff; } // identify possible zero block if (sum == 0 && access.getFilePointer() + 2 * BLOCK_SIZE == access.length()) { return; // found the zero blocks at the end of the file } // replace the actual stored checksum with spaces for comparison for (int i = 148; i < 148 + 8; i++) { sum -= header[i] & 0xff; sum += ' '; } byte[] checkbytes = String.format("%06o\0 ", sum).getBytes(UTF_8); for (int i = 0; i < checkbytes.length; i++) { if (checkbytes[i] != header[148 + i]) { log.warn("Invalid entry checksum at offset {} in tar file {}, skipping...", access.getFilePointer() - BLOCK_SIZE, file); } } // The header checksum passes, so read the entry name and size ByteBuffer buffer = wrap(header); String name = readString(buffer, 100); buffer.position(124); int size = readNumber(buffer, 12); if (access.getFilePointer() + size > access.length()) { // checksum was correct, so the size field should be accurate log.warn("Partial entry {} in tar file {}, ignoring...", name, file); return; } Matcher matcher = NAME_PATTERN.matcher(name); if (matcher.matches()) { UUID id = UUID.fromString(matcher.group(1)); String checksum = matcher.group(3); if (checksum != null || !entries.containsKey(id)) { byte[] data = new byte[size]; access.readFully(data); // skip possible padding to stay at block boundaries long position = access.getFilePointer(); long remainder = position % BLOCK_SIZE; if (remainder != 0) { access.seek(position + (BLOCK_SIZE - remainder)); } if (checksum != null) { CRC32 crc = new CRC32(); crc.update(data); if (crc.getValue() != Long.parseLong(checksum, 16)) { log.warn("Checksum mismatch in entry {} of tar file {}, skipping...", name, file); continue; } } entries.put(id, data); } } else if (!name.equals(file.getName() + ".idx")) { log.warn("Unexpected entry {} in tar file {}, skipping...", name, file); long position = access.getFilePointer() + size; long remainder = position % BLOCK_SIZE; if (remainder != 0) { position += BLOCK_SIZE - remainder; } access.seek(position); } } }
From source file:IntergrationTest.OCSPIntegrationTest.java
@Before public void setUp() throws Exception { OCSP_URL = new URI("http://localhost:" + serverPort + "/verify-mocked-good"); OCSP_MODE_URL = new URI("http://localhost:" + serverPort + "/set-response-mode"); RandomAccessFile raf = new RandomAccessFile("certs/client/client.cer.pem", "r"); byte[] buf = new byte[(int) raf.length()]; raf.readFully(buf); raf.close();//from w ww . ja v a 2 s .c o m clientCert = readPemCert(buf); MatcherAssert.assertThat(clientCert, CoreMatchers.notNullValue()); issuerCert = getX509Certificate(httpGetBin(getIssuerCertURL(clientCert), true)); MatcherAssert.assertThat(issuerCert, CoreMatchers.notNullValue()); }
From source file:com.l2jfree.gameserver.cache.CrestCache.java
public synchronized void reload() { FileFilter filter = new BmpFilter(); File dir = new File(Config.DATAPACK_ROOT, "data/crests/"); File[] files = dir.listFiles(filter); if (files == null) files = new File[0]; byte[] content; _loadedFiles = 0;/*from w w w . ja v a 2s. c o m*/ _bytesBuffLen = 0; _cachePledge.clear(); _cachePledgeLarge.clear(); _cacheAlly.clear(); for (File file : files) { RandomAccessFile f = null; try { f = new RandomAccessFile(file, "r"); content = new byte[(int) f.length()]; f.readFully(content); if (file.getName().startsWith("Crest_Large_")) { _cachePledgeLarge.put( Integer.valueOf(file.getName().substring(12, file.getName().length() - 4)), content); } else if (file.getName().startsWith("Crest_")) { _cachePledge.put(Integer.valueOf(file.getName().substring(6, file.getName().length() - 4)), content); } else if (file.getName().startsWith("AllyCrest_")) { _cacheAlly.put(Integer.valueOf(file.getName().substring(10, file.getName().length() - 4)), content); } _loadedFiles++; _bytesBuffLen += content.length; } catch (Exception e) { _log.warn("Problem with loading crest bmp file: " + file, e); } finally { try { if (f != null) f.close(); } catch (Exception e) { e.printStackTrace(); } } } _log.info(this); }
From source file:org.apache.jackrabbit.oak.plugins.segment.file.TarReader.java
/** * Tries to read an existing index from the given tar file. The index is * returned if it is found and looks valid (correct checksum, passes * sanity checks)./* w w w .j a v a 2 s.c om*/ * * @param file tar file * @param name name of the tar file, for logging purposes * @return tar index, or {@code null} if not found or not valid * @throws IOException if the tar file could not be read */ private static ByteBuffer loadAndValidateIndex(RandomAccessFile file, String name) throws IOException { long length = file.length(); if (length % BLOCK_SIZE != 0 || length < 6 * BLOCK_SIZE || length > Integer.MAX_VALUE) { log.warn("Unexpected size {} of tar file {}", length, name); return null; // unexpected file size } // read the index metadata just before the two final zero blocks ByteBuffer meta = ByteBuffer.allocate(16); file.seek(length - 2 * BLOCK_SIZE - 16); file.readFully(meta.array()); int crc32 = meta.getInt(); int count = meta.getInt(); int bytes = meta.getInt(); int magic = meta.getInt(); if (magic != INDEX_MAGIC) { return null; // magic byte mismatch } if (count < 1 || bytes < count * 24 + 16 || bytes % BLOCK_SIZE != 0) { log.warn("Invalid index metadata in tar file {}", name); return null; // impossible entry and/or byte counts } // this involves seeking backwards in the file, which might not // perform well, but that's OK since we only do this once per file ByteBuffer index = ByteBuffer.allocate(count * 24); file.seek(length - 2 * BLOCK_SIZE - 16 - count * 24); file.readFully(index.array()); index.mark(); CRC32 checksum = new CRC32(); long limit = length - 2 * BLOCK_SIZE - bytes - BLOCK_SIZE; long lastmsb = Long.MIN_VALUE; long lastlsb = Long.MIN_VALUE; byte[] entry = new byte[24]; for (int i = 0; i < count; i++) { index.get(entry); checksum.update(entry); ByteBuffer buffer = ByteBuffer.wrap(entry); long msb = buffer.getLong(); long lsb = buffer.getLong(); int offset = buffer.getInt(); int size = buffer.getInt(); if (lastmsb > msb || (lastmsb == msb && lastlsb > lsb)) { log.warn("Incorrect index ordering in tar file {}", name); return null; } else if (lastmsb == msb && lastlsb == lsb && i > 0) { log.warn("Duplicate index entry in tar file {}", name); return null; } else if (offset < 0 || offset % BLOCK_SIZE != 0) { log.warn("Invalid index entry offset in tar file {}", name); return null; } else if (size < 1 || offset + size > limit) { log.warn("Invalid index entry size in tar file {}", name); return null; } lastmsb = msb; lastlsb = lsb; } if (crc32 != (int) checksum.getValue()) { log.warn("Invalid index checksum in tar file {}", name); return null; // checksum mismatch } index.reset(); return index; }
From source file:hydrograph.ui.perspective.dialog.PreStartActivity.java
private boolean updateINIFile(String javaHome) { logger.debug("Updating JAVA_HOME in ini file ::" + javaHome); javaHome = "-vm\n" + javaHome + "\n"; RandomAccessFile file = null; boolean isUpdated = false; try {//from w w w. j ava2s . com file = new RandomAccessFile(new File(HYDROGRAPH_INI), "rw"); byte[] text = new byte[(int) file.length()]; file.readFully(text); file.seek(0); file.writeBytes(javaHome); file.write(text); isUpdated = true; } catch (IOException ioException) { logger.error("IOException occurred while updating " + HYDROGRAPH_INI + " file", ioException); } finally { try { if (file != null) { file.close(); } } catch (IOException ioException) { logger.error("IOException occurred while updating " + HYDROGRAPH_INI + " file", ioException); } } return isUpdated; }
From source file:de.micromata.genome.logging.spi.ifiles.IndexHeader.java
public String readSearchFromLog(Integer offset, RandomAccessFile file, String name) throws IOException { Integer fieldoffset = searchFieldsOffsets.get(name); if (fieldoffset == null) { return null; }/* www . j a va2s . c o m*/ file.seek(offset.intValue() + fieldoffset.intValue()); byte[] fieldBuffer = new byte[searchFieldsLength.get(name)]; file.readFully(fieldBuffer); String ret = new String(fieldBuffer); ret = ret.trim(); return ret; }
From source file:org.apache.jackrabbit.oak.segment.file.TarReader.java
/** * Tries to read an existing index from the given tar file. The index is * returned if it is found and looks valid (correct checksum, passes * sanity checks)./*from w w w . j a v a2 s . c om*/ * * @param file tar file * @param name name of the tar file, for logging purposes * @return tar index, or {@code null} if not found or not valid * @throws IOException if the tar file could not be read */ private static ByteBuffer loadAndValidateIndex(RandomAccessFile file, String name) throws IOException { long length = file.length(); if (length % BLOCK_SIZE != 0 || length < 6 * BLOCK_SIZE || length > Integer.MAX_VALUE) { log.warn("Unexpected size {} of tar file {}", length, name); return null; // unexpected file size } // read the index metadata just before the two final zero blocks ByteBuffer meta = ByteBuffer.allocate(16); file.seek(length - 2 * BLOCK_SIZE - 16); file.readFully(meta.array()); int crc32 = meta.getInt(); int count = meta.getInt(); int bytes = meta.getInt(); int magic = meta.getInt(); if (magic != INDEX_MAGIC) { return null; // magic byte mismatch } if (count < 1 || bytes < count * TarEntry.SIZE + 16 || bytes % BLOCK_SIZE != 0) { log.warn("Invalid index metadata in tar file {}", name); return null; // impossible entry and/or byte counts } // this involves seeking backwards in the file, which might not // perform well, but that's OK since we only do this once per file ByteBuffer index = ByteBuffer.allocate(count * TarEntry.SIZE); file.seek(length - 2 * BLOCK_SIZE - 16 - count * TarEntry.SIZE); file.readFully(index.array()); index.mark(); CRC32 checksum = new CRC32(); long limit = length - 2 * BLOCK_SIZE - bytes - BLOCK_SIZE; long lastmsb = Long.MIN_VALUE; long lastlsb = Long.MIN_VALUE; byte[] entry = new byte[TarEntry.SIZE]; for (int i = 0; i < count; i++) { index.get(entry); checksum.update(entry); ByteBuffer buffer = wrap(entry); long msb = buffer.getLong(); long lsb = buffer.getLong(); int offset = buffer.getInt(); int size = buffer.getInt(); if (lastmsb > msb || (lastmsb == msb && lastlsb > lsb)) { log.warn("Incorrect index ordering in tar file {}", name); return null; } else if (lastmsb == msb && lastlsb == lsb && i > 0) { log.warn("Duplicate index entry in tar file {}", name); return null; } else if (offset < 0 || offset % BLOCK_SIZE != 0) { log.warn("Invalid index entry offset in tar file {}", name); return null; } else if (size < 1 || offset + size > limit) { log.warn("Invalid index entry size in tar file {}", name); return null; } lastmsb = msb; lastlsb = lsb; } if (crc32 != (int) checksum.getValue()) { log.warn("Invalid index checksum in tar file {}", name); return null; // checksum mismatch } index.reset(); return index; }
From source file:com.filelocker.encryption.AES_Encryption.java
/** * If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv). * We have the password from initializing the class. pass the iv and salt here which is * obtained when encrypting the file initially. * * @param inFile - The Encrypted File containing encrypted data , salt and InitVec * @throws NoSuchAlgorithmException/*from w w w . j a v a2 s. c o m*/ * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws InvalidKeyException * @throws InvalidAlgorithmParameterException * @throws DecoderException * @throws IOException */ public void setupDecrypt(File inFile) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, DecoderException, IOException { SecretKeyFactory factory = null; SecretKey tmp = null; SecretKey secret = null; byte[] vSalt = new byte[8]; byte[] vInitVec = new byte[16]; RandomAccessFile vFile = new RandomAccessFile(inFile, "rw"); //The last 8 bits are salt so seek to length of file minus 9 bits vFile.seek(vFile.length() - 8); vFile.readFully(vSalt); //The last 8 bits are salt and 16 bits before last 8 are Initialization Vectory so 8+16=24 //Thus to seek to length of file minus 24 bits vFile.seek(vFile.length() - 24); vFile.readFully(vInitVec); vFile.seek(0); File tmpFile = new File(inFile.getAbsolutePath() + ".tmpEncryption.file"); RandomAccessFile vTmpFile = new RandomAccessFile(tmpFile, "rw"); for (int i = 0; i < (vFile.length() - 24); ++i) { vTmpFile.write(vFile.readByte()); } vFile.close(); vTmpFile.close(); inFile.delete(); tmpFile.renameTo(inFile); Db("got salt " + Hex.encodeHexString(vSalt)); Db("got initvector :" + Hex.encodeHexString(vInitVec)); /* Derive the key, given password and salt. */ // in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security" // The end user must also install them (not compiled in) so beware. // see here: // http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml // PBKDF2WithHmacSHA1,Constructs secret keys using the Password-Based Key Derivation Function function //found in PKCS #5 v2.0. (PKCS #5: Password-Based Cryptography Standard) factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec spec = new PBEKeySpec(vPassword.toCharArray(), vSalt, ITERATIONS, KEYLEN_BITS); tmp = factory.generateSecret(spec); secret = new SecretKeySpec(tmp.getEncoded(), "AES"); // Decrypt the message, given derived key and initialization vector. vDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); vDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(vInitVec)); }
From source file:org.kalypso.shape.shp.SHPFile.java
/** * method: getByRecNo (int RecNo) <BR> * returns a ShapeRecord-Geometry by RecorcNumber <BR> *///from w ww. j a va 2 s . c o m public ISHPGeometry getShape(final SHXRecord record) throws IOException { final RandomAccessFile raf = getRandomAccessFile(); final int position = record.getOffset() * 2; final int contentLength = record.getLength() * 2; final byte[] recBuf = new byte[contentLength]; raf.seek(position + 8); raf.readFully(recBuf); final ShapeType shpType = ShapeType.valueOf(ByteUtils.readLEInt(recBuf, 0)); if (shpType == ShapeType.NULL) return new SHPNullShape(); // create a geometry out of record buffer with shape type switch (shpType) { case NULL: return new SHPNullShape(); case POINT: return new SHPPoint(recBuf); case MULTIPOINT: return SHPMultiPoint.read(recBuf); case POLYLINE: return new SHPPolyLine(recBuf); case POLYGON: return new SHPPolygon(recBuf); case POINTZ: return new SHPPointz(recBuf); case POLYLINEZ: return new SHPPolyLinez(recBuf); case POLYGONZ: return new SHPPolygonz(recBuf); case MULTIPOINTZ: return SHPMultiPointz.read(recBuf); case POINTM: return new SHPPointm(recBuf); case MULTIPOINTM: return SHPMultiPointm.read(recBuf); case POLYLINEM: return new SHPPolyLinem(recBuf); case POLYGONM: return new SHPPolyLinem(recBuf); } throw new UnsupportedOperationException("Unknown shape type: " + shpType); }