Example usage for java.io RandomAccessFile read

List of usage examples for java.io RandomAccessFile read

Introduction

In this page you can find the example usage for java.io RandomAccessFile read.

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads up to b.length bytes of data from this file into an array of bytes.

Usage

From source file:de.blinkt.openvpn.ActivityDashboard.java

private String loadLogFromFile() {
    String log = "";
    try {/* w w w  .  j  a  v a  2  s  .co  m*/
        RandomAccessFile fp = new RandomAccessFile(getCacheDir() + "/vpnlog.txt", "r");
        //           RandomAccessFile fp = new RandomAccessFile(Environment.getExternalStorageDirectory().getAbsolutePath() + "/vpnlog.txt", "r");
        while (true) {
            byte[] buf = new byte[0x1000];
            int size = fp.read(buf);
            if (size <= 0)
                break;
            log += new String(buf);
        }
        fp.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return log;
}

From source file:FileBaseDataMap.java

private long getLinePoint(String key, RandomAccessFile raf) throws Exception {

    long line = -1;
    long lineCount = 0L;

    byte[] keyBytes = key.getBytes();
    byte[] equalKeyBytes = new byte[keyBytes.length + 1];
    byte[] lineBufs = new byte[this.getDataSize];
    boolean matchFlg = true;

    // ???//from   w  ww  .  ja  va  2  s  .  c  o  m
    for (int idx = 0; idx < keyBytes.length; idx++) {
        equalKeyBytes[idx] = keyBytes[idx];
    }

    equalKeyBytes[equalKeyBytes.length - 1] = 38;

    try {

        raf.seek(0);
        int readLen = -1;
        while ((readLen = raf.read(lineBufs)) != -1) {

            matchFlg = true;

            int loop = readLen / lineDataSize;

            for (int loopIdx = 0; loopIdx < loop; loopIdx++) {

                int assist = (lineDataSize * loopIdx);

                matchFlg = true;
                if (equalKeyBytes[equalKeyBytes.length - 1] == lineBufs[assist + (equalKeyBytes.length - 1)]) {
                    for (int i = 0; i < equalKeyBytes.length; i++) {
                        if (equalKeyBytes[i] != lineBufs[assist + i]) {
                            matchFlg = false;
                            break;
                        }
                    }
                } else {
                    matchFlg = false;
                }

                // ???????
                if (matchFlg) {
                    line = lineCount;
                    break;
                }
                lineCount++;
            }
            if (matchFlg)
                break;
        }

    } catch (IOException ie) {
        throw ie;
    } catch (Exception e) {
        throw e;
    }
    return line;
}

From source file:org.commoncrawl.service.listcrawler.CrawlHistoryManager.java

/**
 * seek out next instance of sync bytes in the file input stream
 * /* ww w  .j  a  v  a  2s .co  m*/
 * @param file
 * @throws IOException
 */
private boolean seekToNextSyncBytesPos(RandomAccessFile file) throws IOException {
    // read in a sync.length buffer amount
    file.read(_syncByteBuffer);

    int syncLen = _header._sync.length;

    // start scan for next sync position ...
    for (int i = 0; file.getFilePointer() < _header._fileSize; i++) {
        int j = 0;
        for (; j < syncLen; j++) {
            if (_header._sync[j] != _syncByteBuffer[(i + j) % syncLen])
                break;
        }
        if (j == syncLen) {
            // found matching sync bytes - reset file pos to before sync bytes
            file.seek(file.getFilePointer() - LocalLogFileHeader.SYNC_BYTES_SIZE); // position
                                                                                   // before
                                                                                   // sync
            return true;
        }
        _syncByteBuffer[i % syncLen] = file.readByte();
    }
    return false;
}

From source file:org.commoncrawl.service.listcrawler.CrawlHistoryManager.java

private ProxyCrawlHistoryItem readItem(RandomAccessFile fileStream) throws IOException {

    try {/*from  w w w.j a  va  2 s .  c  om*/
        // read sync bytes ...
        fileStream.read(_syncByteBuffer);
        // validate ...
        if (!Arrays.equals(_header._sync, _syncByteBuffer)) {
            throw new IOException("Error Reading Sync Bytes for Item In Checkpoint");
        }
        int checksum = fileStream.readInt();
        int payloadSize = fileStream.readShort();

        if (payloadSize == 0) {
            throw new IOException("Invalid Payload Size Reading Item In Checkpoint");
        }
        // read the payload
        _payloadBuffer.setCapacity(payloadSize);

        fileStream.read(_payloadBuffer.get(), 0, payloadSize);

        _crc16in.reset();
        _crc16in.update(_payloadBuffer.get(), 0, payloadSize);

        // if computed checksum does not match file checksum !!!
        if (_crc16in.getValue() != (long) checksum) {
            throw new IOException("Checksum Mismatch Expected:" + checksum + " got:" + _crc16in.getValue()
                    + " while Reading Item");
        }
        _payloadInputStream.reset(_payloadBuffer.get(), 0, payloadSize);

        ProxyCrawlHistoryItem itemOut = new ProxyCrawlHistoryItem();

        itemOut.deserialize(_payloadInputStream, new BinaryProtocol());

        return itemOut;
    } catch (Exception e) {
        LOG.error(CCStringUtils.stringifyException(e));
        throw new IOException(e);
    }
}

From source file:aarddict.Volume.java

private void init(RandomAccessFile file, File cacheDir, Map<UUID, Metadata> knownMeta)
        throws IOException, FormatException {
    this.file = file;
    this.header = new Header(file);
    this.assertFormat();
    this.sha1sum = header.sha1sum;
    if (knownMeta.containsKey(header.uuid)) {
        this.metadata = knownMeta.get(header.uuid);
    } else {/*from w w  w.j  a va  2  s  . co  m*/
        String uuidStr = header.uuid.toString();
        File metadataCacheFile = new File(cacheDir, uuidStr);
        if (metadataCacheFile.exists()) {
            try {
                long t0 = System.currentTimeMillis();
                this.metadata = mapper.readValue(metadataCacheFile, Metadata.class);
                knownMeta.put(header.uuid, this.metadata);
                Log.d(TAG, format("Loaded meta for %s from cache in %s", metadataCacheFile.getName(),
                        (System.currentTimeMillis() - t0)));
            } catch (Exception e) {
                Log.e(TAG, format("Failed to restore meta from cache file %s ", metadataCacheFile.getName()),
                        e);
            }
        }
        if (this.metadata == null) {
            long t0 = System.currentTimeMillis();
            byte[] rawMeta = new byte[(int) header.metaLength];
            file.read(rawMeta);
            String metadataStr = decompress(rawMeta);
            this.metadata = mapper.readValue(metadataStr, Metadata.class);
            Log.d(TAG, format("Read meta for in %s", header.uuid, (System.currentTimeMillis() - t0)));
            knownMeta.put(header.uuid, this.metadata);
            try {
                mapper.writeValue(metadataCacheFile, this.metadata);
                Log.d(TAG, format("Wrote metadata to cache file %s", metadataCacheFile.getName()));
            } catch (IOException e) {
                Log.e(TAG, format("Failed to write metadata to cache file %s", metadataCacheFile.getName()), e);
            }
        }
    }
    initArticleURLTemplate();
}

From source file:FileBaseDataMap.java

/**
 * ??value??.<br>//from  w w w  . j  ava  2s . co  m
 *
 * @param key 
 * @param hashCode This is a key value hash code
 * @return 
 * @throws
 */
public String get(String key, int hashCode) {
    byte[] tmpBytes = null;

    String ret = null;
    byte[] keyBytes = key.getBytes();
    byte[] equalKeyBytes = new byte[keyBytes.length + 1];
    byte[] lineBufs = new byte[this.getDataSize];
    boolean matchFlg = true;

    // ???
    for (int idx = 0; idx < keyBytes.length; idx++) {
        equalKeyBytes[idx] = keyBytes[idx];
    }

    equalKeyBytes[equalKeyBytes.length - 1] = 38;

    try {

        File file = dataFileList[hashCode % numberOfDataFiles];

        CacheContainer accessor = (CacheContainer) innerCache.get(file.getAbsolutePath());
        RandomAccessFile raf = null;
        BufferedWriter wr = null;

        if (accessor == null || accessor.isClosed) {

            raf = new RandomAccessFile(file, "rwd");
            wr = new BufferedWriter(new FileWriter(file, true));
            accessor = new CacheContainer();
            accessor.raf = raf;
            accessor.wr = wr;
            accessor.file = file;
            innerCache.put(file.getAbsolutePath(), accessor);
        } else {

            raf = accessor.raf;
        }

        for (int tryIdx = 0; tryIdx < 2; tryIdx++) {

            try {
                raf.seek(0);
                int readLen = -1;
                while ((readLen = raf.read(lineBufs)) != -1) {

                    matchFlg = true;

                    int loop = readLen / lineDataSize;

                    for (int loopIdx = 0; loopIdx < loop; loopIdx++) {

                        int assist = (lineDataSize * loopIdx);

                        matchFlg = true;

                        if (equalKeyBytes[equalKeyBytes.length - 1] == lineBufs[assist
                                + (equalKeyBytes.length - 1)]) {

                            for (int i = 0; i < equalKeyBytes.length; i++) {

                                if (equalKeyBytes[i] != lineBufs[assist + i]) {
                                    matchFlg = false;
                                    break;
                                }
                            }
                        } else {

                            matchFlg = false;
                        }

                        // ???????
                        if (matchFlg) {

                            tmpBytes = new byte[lineDataSize];

                            for (int i = 0; i < lineDataSize; i++) {

                                tmpBytes[i] = lineBufs[assist + i];
                            }
                            break;
                        }
                    }
                    if (matchFlg)
                        break;
                }
                break;
            } catch (IOException ie) {

                // IOException???1????
                if (tryIdx == 1)
                    throw ie;

                try {
                    if (raf != null)
                        raf.close();
                    if (wr != null)
                        wr.close();

                    raf = new RandomAccessFile(file, "rwd");
                    wr = new BufferedWriter(new FileWriter(file, true));
                    accessor = new CacheContainer();
                    accessor.raf = raf;
                    accessor.wr = wr;
                    accessor.file = file;
                    innerCache.put(file.getAbsolutePath(), accessor);
                } catch (Exception e) {
                    throw e;
                }
            }
        }

        // ?
        if (tmpBytes != null) {

            if (tmpBytes[keyDataLength] != 38) {

                int i = keyDataLength;
                int counter = 0;

                for (; i < tmpBytes.length; i++) {

                    if (tmpBytes[i] == 38)
                        break;
                    counter++;
                }

                ret = new String(tmpBytes, keyDataLength, counter, "UTF-8");
            }
        }
    } catch (Exception e) {

        e.printStackTrace();
    }

    return ret;
}

From source file:com.turn.griffin.data.GriffinUploadTask.java

private void uploadFile(FileInfo fileInfo, BitSet availableBlockBitmap) {

    String filename = fileInfo.getFilename();
    long fileVersion = fileInfo.getVersion();
    long blockCount = fileInfo.getBlockCount();
    long blockSize = fileInfo.getBlockSize();
    byte[] buffer = new byte[(int) blockSize];

    GriffinLibCacheUtil libCacheManager = dataManager.getLibCacheManager().get();
    String dataTopicNameForProducer = GriffinKafkaTopicNameUtil.getDataTopicNameForProducer(filename,
            fileVersion);//from  w  ww . ja  va 2 s .c  om
    GriffinProducer producer = null;
    try {
        String libCacheUploadFilePath = libCacheManager.getUploadFilePath(fileInfo);
        RandomAccessFile libCacheUploadFile = new RandomAccessFile(libCacheUploadFilePath, "r");
        producer = new GriffinProducer(GriffinModule.BROKERS);

        logger.info(String.format("Starting to push %s",
                fileInfo.toString().replaceAll(System.getProperty("line.separator"), " ")));

        int uploadAttempts = 0;
        while (availableBlockBitmap.nextClearBit(0) != blockCount) {

            /* If a new version has arrived abort uploading older version */
            if (!libCacheManager.isLatestGlobalVersion(fileInfo)) {
                logger.info(
                        String.format("Aborting upload for %s version %s as a newer version is now available.",
                                filename, fileVersion));
                break;
            }

            if (uploadAttempts >= maxUploadAttempts) {
                logger.warn(String.format("Unable to upload %s version %s after %s attempts", filename,
                        fileVersion, uploadAttempts));
                String subject = String.format("WARNING: GriffinUploadTask failed for blob:%s", filename);
                String body = String.format(
                        "Action: GriffinUploadTask failed for blob:%s version:%s%n"
                                + "Reason: Unable to upload after %s attempts%n",
                        filename, fileVersion, uploadAttempts);
                GriffinModule.emailAlert(subject, body);
                break;
            }

            int blockToUpload = availableBlockBitmap.nextClearBit(0);
            libCacheUploadFile.seek(blockToUpload * blockSize);
            int bytesRead = libCacheUploadFile.read(buffer);
            DataMessage msg = DataMessage.newBuilder().setBlockSeqNo(blockToUpload).setByteCount(bytesRead)
                    .setData(ByteString.copyFrom(buffer)).build();
            try {
                producer.send(dataTopicNameForProducer, DigestUtils.md5Hex(buffer), msg);
                availableBlockBitmap.set(blockToUpload);
                uploadAttempts = 0;
            } catch (FailedToSendMessageException ftsme) {
                /* Retry the same block again */
                logger.warn(String.format("Unable to send block %s for file: %s version: %s "
                        + "due to FailedToSendMessageException", blockToUpload, filename, fileVersion));
                uploadAttempts++;
            } catch (Exception e) {
                logger.warn(String.format("Unable to send block %s for file: %s version: %s", blockToUpload,
                        filename, fileVersion), e);
                logger.warn("Exception", e);
                uploadAttempts++;
            }
        }
        logger.info(String.format("Ending file upload for file %s version %s to %s", filename, fileVersion,
                dataTopicNameForProducer));
        libCacheUploadFile.close();
    } catch (IOException | RuntimeException e) {
        logger.error(String.format("Unable to upload file %s to %s", filename, dataTopicNameForProducer), e);
        String subject = String.format("WARNING: GriffinUploadTask failed for blob:%s", filename);
        String body = String.format(
                "Action: GriffinUploadTask failed for blob:%s version:%s%n"
                        + "Reason: Exception in GriffinUploadTask%n %s",
                filename, fileVersion, Throwables.getStackTraceAsString(e));
        GriffinModule.emailAlert(subject, body);
    } finally {
        if (producer != null) {
            producer.shutdown();
        }
    }

}

From source file:com.xperia64.rompatcher.MainActivity.java

public void patch(final boolean c, final boolean d, final boolean r, final String ed) {
    final ProgressDialog myPd_ring = ProgressDialog.show(MainActivity.this,
            getResources().getString(R.string.wait), getResources().getString(R.string.wait_desc), true);
    myPd_ring.setCancelable(false);// w w  w.ja  va2s  .  c  o m
    new Thread(new Runnable() {
        public void run() {
            if (new File(Globals.patchToApply).exists() && new File(Globals.fileToPatch).exists()
                    && !Globals.fileToPatch.toLowerCase(Locale.US).endsWith(".ecm")) {
                String msg = getResources().getString(R.string.success);
                if (!new File(Globals.fileToPatch).canWrite()) {
                    Globals.msg = msg = "Can not write to output file. If you are on KitKat or Lollipop, move the file to your internal storage.";
                    return;
                }
                if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".ups")) {
                    int e = upsPatchRom(Globals.fileToPatch, Globals.patchToApply, Globals.fileToPatch + ".new",
                            r ? 1 : 0);
                    if (e != 0) {
                        msg = parseError(e, Globals.TYPE_UPS);
                    }
                } else if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".xdelta")
                        || Globals.patchToApply.toLowerCase(Locale.US).endsWith(".xdelta3")
                        || Globals.patchToApply.toLowerCase(Locale.US).endsWith(".vcdiff")) {
                    RandomAccessFile f = null;
                    try {
                        f = new RandomAccessFile(Globals.patchToApply, "r");
                    } catch (FileNotFoundException e1) {
                        e1.printStackTrace();
                        Globals.msg = msg = getResources().getString(R.string.fnf);
                        return;
                    }
                    StringBuilder s = new StringBuilder();
                    try {
                        if (f.length() >= 9) {
                            for (int i = 0; i < 8; i++) {
                                s.append((char) f.readByte());
                                f.seek(i + 1);
                            }
                        }
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    try {
                        f.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    // Header of xdelta patch determines version
                    if (s.toString().equals("%XDELTA%") || s.toString().equals("%XDZ000%")
                            || s.toString().equals("%XDZ001%") || s.toString().equals("%XDZ002%")
                            || s.toString().equals("%XDZ003%") || s.toString().equals("%XDZ004%")) {
                        int e = xdelta1PatchRom(Globals.fileToPatch, Globals.patchToApply,
                                Globals.fileToPatch + ".new");
                        if (e != 0) {
                            msg = parseError(e, Globals.TYPE_XDELTA1);
                        }
                    } else {
                        int e = xdelta3PatchRom(Globals.fileToPatch, Globals.patchToApply,
                                Globals.fileToPatch + ".new");
                        if (e != 0) {
                            msg = parseError(e, Globals.TYPE_XDELTA3);
                        }
                    }
                } else if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".bps")) {
                    int e = bpsPatchRom(Globals.fileToPatch, Globals.patchToApply, Globals.fileToPatch + ".new",
                            r ? 1 : 0);
                    if (e != 0) {
                        msg = parseError(e, Globals.TYPE_BPS);
                    }
                } else if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".dps")) {
                    int e = dpsPatchRom(Globals.fileToPatch, Globals.patchToApply,
                            Globals.fileToPatch + ".new");
                    if (e != 0) {
                        msg = parseError(e, Globals.TYPE_DPS);
                    }
                } else if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".bsdiff")) {
                    int e = bsdiffPatchRom(Globals.fileToPatch, Globals.patchToApply,
                            Globals.fileToPatch + ".new");
                    if (e != 0) {
                        msg = parseError(e, Globals.TYPE_BSDIFF);
                    }

                } else if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".aps")) {
                    File f = new File(Globals.fileToPatch);
                    File f2 = new File(Globals.fileToPatch + ".bak");
                    try {
                        Files.copy(f, f2);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    // Wow.
                    byte[] gbaSig = { 0x41, 0x50, 0x53, 0x31, 0x00 };
                    byte[] n64Sig = { 0x41, 0x50, 0x53, 0x31, 0x30 };
                    byte[] realSig = new byte[5];
                    RandomAccessFile raf = null;
                    System.out.println("APS Patch");
                    try {
                        raf = new RandomAccessFile(Globals.patchToApply, "r");
                    } catch (FileNotFoundException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                        Globals.msg = msg = getResources().getString(R.string.fnf);
                        return;
                    }
                    try {
                        raf.read(realSig);
                        raf.close();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                    if (Arrays.equals(realSig, gbaSig)) {
                        System.out.println("GBA APS");
                        APSGBAPatcher aa = new APSGBAPatcher();
                        aa.crcTableInit();
                        int e = 0;
                        try {
                            e = aa.ApplyPatch(Globals.patchToApply, Globals.fileToPatch, r);
                        } catch (IOException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                            e = -5;
                        }
                        System.out.println("e: " + e);
                        if (e != 0) {
                            msg = parseError(e, Globals.TYPE_APSGBA);
                        }
                    } else if (Arrays.equals(realSig, n64Sig)) {
                        System.out.println("N64 APS");
                        int e = apsN64PatchRom(Globals.fileToPatch, Globals.patchToApply);
                        if (e != 0) {
                            msg = parseError(e, Globals.TYPE_APSN64);
                        }
                    } else {
                        msg = parseError(-131, -10000);
                    }

                } else if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".ppf")) {
                    File f = new File(Globals.fileToPatch);
                    File f2 = new File(Globals.fileToPatch + ".bak");
                    try {
                        Files.copy(f, f2);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    int e = ppfPatchRom(Globals.fileToPatch, Globals.patchToApply, r ? 1 : 0);
                    if (e != 0) {
                        msg = parseError(e, Globals.TYPE_PPF);
                    }

                } else if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".patch")) {
                    int e = xdelta1PatchRom(Globals.fileToPatch, Globals.patchToApply,
                            Globals.fileToPatch + ".new");
                    if (e != 0) {
                        msg = parseError(e, Globals.TYPE_XDELTA1);
                    }
                } else if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".asm")) {
                    File f = new File(Globals.fileToPatch);
                    File f2 = new File(Globals.fileToPatch + ".bak");
                    try {
                        Files.copy(f, f2);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    int e;
                    if (Globals.asar)
                        e = asarPatchRom(Globals.fileToPatch, Globals.patchToApply, r ? 1 : 0);
                    else
                        e = asmPatchRom(Globals.fileToPatch, Globals.patchToApply);
                    if (e != 0) {
                        msg = parseError(e, Globals.TYPE_ASM);
                    }
                } else if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".dldi")) {
                    File f = new File(Globals.fileToPatch);
                    File f2 = new File(Globals.fileToPatch + ".bak");
                    try {
                        Files.copy(f, f2);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    int e = dldiPatchRom(Globals.fileToPatch, Globals.patchToApply);
                    if (e != 0) {
                        msg = parseError(e, Globals.TYPE_DLDI);
                    }
                } else if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".xpc")) {
                    int e = xpcPatchRom(Globals.fileToPatch, Globals.patchToApply,
                            Globals.fileToPatch + ".new");
                    if (e != 0) {
                        msg = parseError(e, Globals.TYPE_XPC);
                    }

                } else if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".nmp")) {

                    String drm = MainActivity.this.getPackageName();
                    System.out.println("Drm is: " + drm);
                    if (drm.equals("com.xperia64.rompatcher.donation")) {
                        if (c) {
                            File f = new File(Globals.fileToPatch);
                            File f2 = new File(Globals.fileToPatch + ".bak");
                            try {
                                Files.copy(f, f2);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        NitroROMFilesystem fs;
                        try {
                            fs = new NitroROMFilesystem(Globals.fileToPatch);
                            ROM.load(fs);
                            RealPatch.patch(Globals.patchToApply, new Object());
                            ROM.close();
                        } catch (Exception e1) {
                            // TODO Auto-generated catch block
                            //e1.printStackTrace();
                            Globals.msg = msg = String.format(getResources().getString(R.string.nmpDefault),
                                    e1.getStackTrace()[0].getFileName(), e1.getStackTrace()[0].getLineNumber());
                        }
                        if (c && d && !TextUtils.isEmpty(ed)) {
                            File f = new File(Globals.fileToPatch);
                            File f3 = new File(Globals.fileToPatch + ".bak");
                            File f2 = new File(
                                    Globals.fileToPatch.substring(0, Globals.fileToPatch.lastIndexOf('/') + 1)
                                            + ed);
                            f.renameTo(f2);
                            f3.renameTo(f);
                        }
                    } else {
                        Globals.msg = msg = getResources().getString(R.string.drmwarning);
                        MainActivity.this.runOnUiThread(new Runnable() {
                            public void run() {
                                AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this);
                                b.setTitle(getResources().getString(R.string.drmwarning));
                                b.setIcon(
                                        ResourcesCompat.getDrawable(getResources(), R.drawable.icon_pro, null));
                                b.setMessage(getResources().getString(R.string.drmwarning_desc));
                                b.setCancelable(false);
                                b.setNegativeButton(getResources().getString(android.R.string.cancel),
                                        new OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface arg0, int arg1) {
                                            }
                                        });
                                b.setPositiveButton(getResources().getString(R.string.nagInfo),
                                        new OnClickListener() {

                                            @Override
                                            public void onClick(DialogInterface arg0, int arg1) {
                                                try {
                                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(
                                                            "market://details?id=com.xperia64.rompatcher.donation")));
                                                } catch (android.content.ActivityNotFoundException anfe) {
                                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(
                                                            "http://play.google.com/store/apps/details?id=com.xperia64.rompatcher.donation")));
                                                }
                                            }
                                        });
                                b.create().show();
                            }
                        });
                    }

                } else {
                    RandomAccessFile f = null;
                    try {
                        f = new RandomAccessFile(Globals.patchToApply, "r");
                    } catch (FileNotFoundException e1) {
                        e1.printStackTrace();
                        Globals.msg = msg = getResources().getString(R.string.fnf);
                        return;
                    }
                    StringBuilder s = new StringBuilder();
                    try {
                        if (f.length() >= 6) {
                            for (int i = 0; i < 5; i++) {
                                s.append((char) f.readByte());
                                f.seek(i + 1);
                            }
                        }
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    try {
                        f.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    int e;
                    // Two variants of IPS, the normal PATCH type, then this weird one called IPS32 with messily hacked in 32 bit offsets
                    if (s.toString().equals("IPS32")) {
                        e = ips32PatchRom(Globals.fileToPatch, Globals.patchToApply);
                        if (e != 0) {
                            msg = parseError(e, Globals.TYPE_IPS);
                        }
                    } else {
                        e = ipsPatchRom(Globals.fileToPatch, Globals.patchToApply);
                        if (e != 0) {
                            msg = parseError(e, Globals.TYPE_IPS);
                        }
                    }

                }
                if (Globals.patchToApply.toLowerCase(Locale.US).endsWith(".ups")
                        || Globals.patchToApply.toLowerCase(Locale.US).endsWith(".xdelta")
                        || Globals.patchToApply.toLowerCase(Locale.US).endsWith(".xdelta3")
                        || Globals.patchToApply.toLowerCase(Locale.US).endsWith(".vcdiff")
                        || Globals.patchToApply.toLowerCase(Locale.US).endsWith(".patch")
                        || Globals.patchToApply.toLowerCase(Locale.US).endsWith(".bps")
                        || Globals.patchToApply.toLowerCase(Locale.US).endsWith(".bsdiff")
                        || Globals.patchToApply.toLowerCase(Locale.US).endsWith(".dps")
                        || Globals.patchToApply.toLowerCase(Locale.US).endsWith(".xpc")) {
                    File oldrom = new File(Globals.fileToPatch);
                    File bkrom = new File(Globals.fileToPatch + ".bak");
                    oldrom.renameTo(bkrom);
                    File newrom = new File(Globals.fileToPatch + ".new");
                    newrom.renameTo(oldrom);
                }
                if (!c) {
                    File f = new File(Globals.fileToPatch + ".bak");
                    if (f.exists()) {
                        f.delete();
                    }
                } else {
                    if (d) {
                        File one = new File(Globals.fileToPatch + ".bak");
                        File two = new File(Globals.fileToPatch);
                        File three = new File(
                                Globals.fileToPatch.substring(0, Globals.fileToPatch.lastIndexOf('/') + 1)
                                        + ed);
                        two.renameTo(three);
                        File four = new File(Globals.fileToPatch);
                        one.renameTo(four);
                    }
                }
                Globals.msg = msg;
            } else if (Globals.fileToPatch.toLowerCase(Locale.US).endsWith(".ecm")) {
                int e = 0;
                String msg = getResources().getString(R.string.success);
                if (c) {

                    if (d) {
                        e = ecmPatchRom(Globals.fileToPatch,
                                Globals.fileToPatch.substring(0, Globals.fileToPatch.lastIndexOf('/')) + ed, 1);
                    } else {
                        //new File(Globals.fileToPatch).renameTo(new File(Globals.fileToPatch+".bak"));
                        e = ecmPatchRom(Globals.fileToPatch,
                                Globals.fileToPatch.substring(0, Globals.fileToPatch.lastIndexOf('.')), 1);
                    }
                } else {
                    e = ecmPatchRom(Globals.fileToPatch, "", 0);
                }
                if (e != 0) {
                    msg = parseError(e, Globals.TYPE_ECM);
                }
                Globals.msg = msg;
            } else {
                Globals.msg = getResources().getString(R.string.fnf);
            }

        }
    }).start();
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                while (Globals.msg.equals("")) {
                    Thread.sleep(25);
                }
                ;
                myPd_ring.dismiss();
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast t = Toast.makeText(staticThis, Globals.msg, Toast.LENGTH_SHORT);
                        t.show();
                        Globals.msg = "";
                    }
                });
                if (Globals.msg.equals(getResources().getString(R.string.success))) // Don't annoy people who did something wrong even further
                {
                    final SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(MainActivity.this);
                    int x = prefs.getInt("purchaseNag", 5);
                    if (x != -1) {
                        if ((isPackageInstalled("com.xperia64.timidityae", MainActivity.this)
                                || isPackageInstalled("com.xperia64.rompatcher.donation", MainActivity.this))) {
                            prefs.edit().putInt("purchaseNag", -1);
                        } else {
                            if (x >= 5) {

                                prefs.edit().putInt("purchaseNag", 0).commit();
                                /*runOnUiThread(new Runnable() {
                                    public void run() {
                                AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this);
                                b.setTitle("Like ROM Patcher?");
                                b.setIcon(getResources().getDrawable(R.drawable.icon_pro));
                                b.setMessage(getResources().getString(R.string.nagMsg));
                                b.setCancelable(false);
                                b.setNegativeButton(getResources().getString(android.R.string.cancel), new OnClickListener(){@Override public void onClick(DialogInterface arg0, int arg1) {}});
                                b.setPositiveButton(getResources().getString(R.string.nagInfo), new OnClickListener(){
                                        
                                  @Override
                                  public void onClick(DialogInterface arg0, int arg1) {
                                     try  {
                                         startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.xperia64.rompatcher.donation")));
                                     } catch (android.content.ActivityNotFoundException anfe) {
                                         startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=com.xperia64.rompatcher.donation")));
                                     }
                                  }
                                   });
                                      b.create().show();
                                       }
                                   }); // end of UIThread*/
                            } else {
                                prefs.edit().putInt("purchaseNag", x + 1).commit();
                            }
                        }
                    }
                }

            } catch (Exception e) {
            }
        }
    }).start();
}

From source file:au.org.ala.layers.intersect.Grid.java

/**
 * buffering on top of RandomAccessFile//  w  w w .ja  v  a 2  s . com
 */
private byte getByte(RandomAccessFile raf, byte[] buffer, Long bufferOffset, long seekTo) throws IOException {
    long relativePos = seekTo - bufferOffset;
    if (relativePos < 0) {
        raf.seek(seekTo);
        bufferOffset = seekTo;
        raf.read(buffer);
        return buffer[0];
    } else if (relativePos >= 0 && relativePos < buffer.length) {
        return buffer[(int) relativePos];
    } else if (relativePos - buffer.length < buffer.length) {
        bufferOffset += buffer.length;
        raf.read(buffer);
        return buffer[(int) (relativePos - buffer.length)];
    } else {
        raf.seek(seekTo);
        bufferOffset = seekTo;
        raf.read(buffer);
        return buffer[0];
    }
}

From source file:au.org.ala.layers.intersect.Grid.java

/**
 * buffering on top of RandomAccessFile/*from  ww  w.  j  a  va2 s. co m*/
 */
private Long getBytes(RandomAccessFile raf, byte[] buffer, Long bufferOffset, long seekTo, byte[] dest)
        throws IOException {
    long relativePos = seekTo - bufferOffset;
    if (relativePos < 0) {
        if (seekTo < 0) {
            seekTo = 0;
        }
        raf.seek(seekTo);
        bufferOffset = seekTo;
        raf.read(buffer);
        System.arraycopy(buffer, 0, dest, 0, dest.length);
    } else if (relativePos >= 0 && relativePos < buffer.length) {
        System.arraycopy(buffer, (int) relativePos, dest, 0, dest.length);
    } else if (relativePos - buffer.length < buffer.length) {
        bufferOffset += buffer.length;
        raf.read(buffer);
        int offset = (int) (relativePos - buffer.length);
        System.arraycopy(buffer, offset, dest, 0, dest.length);
    } else {
        raf.seek(seekTo);
        bufferOffset = seekTo;
        raf.read(buffer);
        System.arraycopy(buffer, 0, dest, 0, dest.length);
    }

    return bufferOffset;
}