Example usage for java.io FileInputStream getFD

List of usage examples for java.io FileInputStream getFD

Introduction

In this page you can find the example usage for java.io FileInputStream getFD.

Prototype

public final FileDescriptor getFD() throws IOException 

Source Link

Document

Returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream.

Usage

From source file:org.apache.hadoop.io.nativeio.TestSharedFileDescriptorFactory.java

@Test(timeout = 10000)
public void testReadAndWrite() throws Exception {
    File path = new File(TEST_BASE, "testReadAndWrite");
    path.mkdirs();/*from   w  ww  . j  a va 2s . c  om*/
    SharedFileDescriptorFactory factory = SharedFileDescriptorFactory.create("woot_",
            new String[] { path.getAbsolutePath() });
    FileInputStream inStream = factory.createDescriptor("testReadAndWrite", 4096);
    FileOutputStream outStream = new FileOutputStream(inStream.getFD());
    outStream.write(101);
    inStream.getChannel().position(0);
    Assert.assertEquals(101, inStream.read());
    inStream.close();
    outStream.close();
    FileUtil.fullyDelete(path);
}

From source file:com.sebible.cordova.videosnapshot.VideoSnapshot.java

/**
 * Take snapshots of a video file/*from w  w  w. jav  a  2s  .  com*/
 *
 * @param source path of the file
 * @param count of snapshots that are gonna be taken
 */
private void snapshot(final JSONObject options) {
    final CallbackContext context = this.callbackContext;
    this.cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            try {
                int count = options.optInt("count", 1);
                int countPerMinute = options.optInt("countPerMinute", 0);
                int quality = options.optInt("quality", 90);
                String source = options.optString("source", "");
                Boolean timestamp = options.optBoolean("timeStamp", true);
                String prefix = options.optString("prefix", "");
                int textSize = options.optInt("textSize", 48);

                if (source.isEmpty()) {
                    throw new Exception("No source provided");
                }

                JSONObject obj = new JSONObject();
                obj.put("result", false);
                JSONArray results = new JSONArray();

                Log.i("snapshot", "Got source: " + source);
                Uri p = Uri.parse(source);
                String filename = p.getLastPathSegment();

                FileInputStream in = new FileInputStream(new File(p.getPath()));
                retriever.setDataSource(in.getFD());
                String tmp = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                long duration = Long.parseLong(tmp);
                if (countPerMinute > 0) {
                    count = (int) (countPerMinute * duration / (60 * 1000));
                }
                if (count < 1) {
                    count = 1;
                }
                long delta = duration / (count + 1); // Start at duration * 1 and ends at duration * count
                if (delta < 1000) { // min 1s
                    delta = 1000;
                }

                Log.i("snapshot", "duration:" + duration + " delta:" + delta);

                File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                for (int i = 1; delta * i < duration && i <= count; i++) {
                    String filename2 = filename.replace('.', '_') + "-snapshot" + i + ".jpg";
                    File dest = new File(storage, filename2);
                    if (!storage.exists() && !storage.mkdirs()) {
                        throw new Exception("Unable to access storage:" + storage.getPath());
                    }
                    FileOutputStream out = new FileOutputStream(dest);
                    Bitmap bm = retriever.getFrameAtTime(i * delta * 1000);
                    if (timestamp) {
                        drawTimestamp(bm, prefix, delta * i, textSize);
                    }
                    bm.compress(Bitmap.CompressFormat.JPEG, quality, out);
                    out.flush();
                    out.close();
                    results.put(dest.getAbsolutePath());
                }

                obj.put("result", true);
                obj.put("snapshots", results);
                context.success(obj);
            } catch (Exception ex) {
                ex.printStackTrace();
                Log.e("snapshot", "Exception:", ex);
                fail("Exception: " + ex.toString());
            } finally {
                try {
                    retriever.release();
                } catch (RuntimeException ex) {
                }
            }
        }
    });
}

From source file:com.google.android.gms.samples.vision.face.facetracker.FaceGraphic.java

public void audioPlayer(String fileName) {
    //set up MediaPlayer
    if (!setupDone) {

        try {//from  ww w  . jav  a 2 s  .  c o  m
            File downloadDir = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                            .getAbsolutePath() + File.separator + fileName);

            File[] downloadDirs = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                    .listFiles();

            //File exdir = Environment.getExternalStorageDirectory();
            //System.out.println("EXDIR!!!!!!!!!: " + exdir);

            for (File tmpf : downloadDirs) {
                System.out.println("FILE: " + tmpf.getAbsolutePath());
            }

            File file = new File("/storage/emulated/0/downloads" + File.separator + fileName);
            FileInputStream inputStream = new FileInputStream(downloadDir);
            mp.setDataSource(inputStream.getFD());
            mp.prepare();
            setupDone = true;

        } catch (Exception e) {
            System.out.println("ERROR READING MUSIC: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

From source file:com.redoceanred.unity.android.RORAudioPlayer.java

public boolean setDataSource(byte[] data) {
    try {// w  ww  .jav  a2  s . c  o m
        createMediaPlayer();

        File temp = File.createTempFile("tmp_voice", "m4a",
                mActivity.get().getApplicationContext().getCacheDir());
        temp.deleteOnExit();
        FileOutputStream fos = new FileOutputStream(temp);
        fos.write(data);
        fos.close();

        FileInputStream fis = new FileInputStream(temp);
        mMediaPlayer.setDataSource(fis.getFD());
        fis.close();
        return true;
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return false;
}

From source file:com.redoceanred.unity.android.RORAudioPlayer.java

public boolean setDataSource(String inPath) {
    try {// w w w.j a  va2s  .c  o m
        createMediaPlayer();

        FileInputStream fis = new FileInputStream(new File(inPath));
        mMediaPlayer.setDataSource(fis.getFD());
        fis.close();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:edu.ucsb.nceas.mdqengine.solr.SolrIndex.java

/**
 * Generate the index for the given information
 * @param id//from  w w w . j  a  va  2  s .  c  om
 * @param systemMetadata
 * @param objectPath
 * @return
 * @throws IOException
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws XPathExpressionException
 * @throws MarshallingException
 * @throws SolrServerException
 * @throws EncoderException
 * @throws UnsupportedType
 * @throws NotFound
 * @throws NotImplemented
 */
private Map<String, SolrDoc> process(String id, SystemMetadata systemMetadata, String objectPath)
        throws IOException, SAXException, MarshallingException, SolrServerException {
    log.debug("SolrIndex.process - trying to generate the solr doc object for the pid " + id);
    // Load the System Metadata document
    ByteArrayOutputStream systemMetadataOutputStream = new ByteArrayOutputStream();
    TypeMarshaller.marshalTypeToOutputStream(systemMetadata, systemMetadataOutputStream);
    ByteArrayInputStream systemMetadataStream = new ByteArrayInputStream(
            systemMetadataOutputStream.toByteArray());
    Document sysMetaDoc = generateXmlDocument(systemMetadataStream);
    if (sysMetaDoc == null) {
        log.error("Could not load System metadata for ID: " + id);
        return null;
    }

    // Extract the field values from the System Metadata
    List<SolrElementField> sysSolrFields = processSysmetaFields(sysMetaDoc, id);
    SolrDoc indexDocument = new SolrDoc(sysSolrFields);
    Map<String, SolrDoc> docs = new HashMap<String, SolrDoc>();
    docs.put(id, indexDocument);

    // get the format id for this object
    String formatId = indexDocument.getFirstFieldValue(SolrElementField.FIELD_OBJECTFORMAT);
    log.debug("SolrIndex.process - the object format id for the pid " + id + " is " + formatId);
    // Determine if subprocessors are available for this ID
    if (subprocessors != null) {
        // for each subprocessor loaded from the spring config
        for (IDocumentSubprocessor subprocessor : subprocessors) {
            // Does this subprocessor apply?
            log.debug("SolrIndex.process - trying subprocessor " + subprocessor.getClass().getName());
            if (subprocessor.canProcess(formatId)) {
                log.debug("SolrIndex.process - using subprocessor " + subprocessor.getClass().getName());
                // if so, then extract the additional information from the
                // document.
                try {
                    // docObject = the resource map document or science
                    // metadata document.
                    // note that resource map processing touches all objects
                    // referenced by the resource map.
                    FileInputStream dataStream = new FileInputStream(objectPath);
                    if (!dataStream.getFD().valid()) {
                        log.error("SolrIndex.process - subprocessor " + subprocessor.getClass().getName()
                                + " couldn't process since it could not load OBJECT file for ID,Path=" + id
                                + ", " + objectPath);
                        //throw new Exception("Could not load OBJECT for ID " + id );
                    } else {
                        log.debug("SolrIndex.process - subprocessor " + subprocessor.getClass().getName()
                                + " generating solr doc for id " + id);
                        docs = subprocessor.processDocument(id, docs, dataStream);
                        log.debug("SolrIndex.process - subprocessor " + subprocessor.getClass().getName()
                                + " generated solr doc for id " + id);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error(e.getMessage(), e);
                    throw new SolrServerException(e.getMessage());
                }
            }
        }
    } else {
        log.debug("Subproccor list is null");
    }

    return docs;
}

From source file:com.aimfire.gallery.service.MovieProcessor.java

@Override
protected void onHandleIntent(Intent intent) {
    /*/* w w  w .j  a  va  2s .c o m*/
     * Obtain the FirebaseAnalytics instance.
     */
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

    boolean[] result = new boolean[] { false, false };
    String previewPath = null;
    String thumbPath = null;
    String configPath = null;
    String convertFilePath = null;

    String exportL = MainConsts.MEDIA_3D_RAW_PATH + "L.png";
    String exportR = MainConsts.MEDIA_3D_RAW_PATH + "R.png";

    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    Bundle extras = intent.getExtras();
    if (extras == null) {
        if (BuildConfig.DEBUG)
            Log.e(TAG, "onHandleIntent: error, wrong parameter");
        FirebaseCrash.report(new Exception("onHandleIntent: error, wrong parameter"));
        return;
    }

    String filePathL = extras.getString("lname");
    String filePathR = extras.getString("rname");
    String cvrNameNoExt = MediaScanner.getProcessedCvrName((new File(filePathL)).getName());

    if (BuildConfig.DEBUG)
        Log.d(TAG, "onHandleIntent:left file=" + filePathL + ", right file=" + filePathR);

    String creatorName = extras.getString("creator");
    String creatorPhotoUrl = extras.getString("photo");

    float scale = extras.getFloat(MainConsts.EXTRA_SCALE);

    /*
     * if left/right videos were taken using front facing camera,
     * they need to be swapped when generating sbs 
     */
    int facing = extras.getInt(MainConsts.EXTRA_FACING);
    boolean isFrontCamera = (facing == Camera.CameraInfo.CAMERA_FACING_FRONT) ? true : false;

    MediaMetadataRetriever retriever = new MediaMetadataRetriever();

    Bitmap bitmapL = null;
    Bitmap bitmapR = null;

    long frameTime = FIRST_KEYFRAME_TIME_US;
    if (BuildConfig.DEBUG)
        Log.d(TAG, "extract frame from left at " + frameTime / 1000 + "ms");

    try {
        long startUs = SystemClock.elapsedRealtimeNanos() / 1000;

        FileInputStream inputStreamL = new FileInputStream(filePathL);
        retriever.setDataSource(inputStreamL.getFD());
        inputStreamL.close();

        bitmapL = retriever.getFrameAtTime(frameTime, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);

        FileInputStream inputStreamR = new FileInputStream(filePathR);
        retriever.setDataSource(inputStreamR.getFD());
        inputStreamR.close();

        bitmapR = retriever.getFrameAtTime(frameTime, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);

        retriever.release();

        long stopUs = SystemClock.elapsedRealtimeNanos() / 1000;
        if (BuildConfig.DEBUG)
            Log.d(TAG, "retrieving preview frames took " + (stopUs - startUs) / 1000 + "ms");

        if ((bitmapL != null) && (bitmapR != null)) {
            saveFrame(bitmapL, exportL);
            saveFrame(bitmapR, exportR);
        } else {
            reportError(MediaScanner.getProcessedCvrPath((new File(filePathL)).getName()),
                    ERROR_EXTRACT_SYNC_FRAME_ERROR);
            return;
        }

        previewPath = MainConsts.MEDIA_3D_THUMB_PATH + cvrNameNoExt + ".jpeg";

        result = p.getInstance().f1(exportL, exportR, previewPath, scale, isFrontCamera);
    } catch (Exception ex) {
        retriever.release();
        reportError(MediaScanner.getProcessedCvrPath((new File(filePathL)).getName()),
                ERROR_EXTRACT_SYNC_FRAME_EXCEPTION);
        return;
    }

    if (!result[0]) {
        reportError(MediaScanner.getProcessedCvrPath((new File(filePathL)).getName()),
                ERROR_EXTRACT_SIMILARITY_MATRIX);

        File leftFrom = (new File(filePathL));
        File rightFrom = (new File(filePathR));
        File leftExportFrom = (new File(exportL));
        File rightExportFrom = (new File(exportR));

        if (!BuildConfig.DEBUG) {
            leftFrom.delete();
            rightFrom.delete();

            leftExportFrom.delete();
            rightExportFrom.delete();
        } else {
            File leftTo = new File(MainConsts.MEDIA_3D_DEBUG_PATH + leftFrom.getName());
            File rightTo = new File(MainConsts.MEDIA_3D_DEBUG_PATH + rightFrom.getName());

            leftFrom.renameTo(leftTo);
            rightFrom.renameTo(rightTo);

            File leftExportTo = new File(MainConsts.MEDIA_3D_DEBUG_PATH + leftExportFrom.getName());
            File rightExportTo = new File(MainConsts.MEDIA_3D_DEBUG_PATH + rightExportFrom.getName());

            leftExportFrom.renameTo(leftExportTo);
            rightExportFrom.renameTo(rightExportTo);
        }
    } else {
        double[] similarityMat = p.getInstance().g();

        String configData = similarityMat[0] + " " + similarityMat[1] + " " + similarityMat[2] + " "
                + similarityMat[3] + " " + similarityMat[4] + " " + similarityMat[5];

        if (result[1]) {
            convertFilePath = filePathR;
        } else {
            convertFilePath = filePathL;
        }

        configPath = createConfigFile(convertFilePath, configData);

        /*
         * save the thumbnail
         */
        if (bitmapL != null) {
            thumbPath = MainConsts.MEDIA_3D_THUMB_PATH + cvrNameNoExt + ".jpg";
            saveThumbnail(bitmapL, thumbPath);

            MediaScanner.insertExifInfo(thumbPath, "name=" + creatorName + "photourl=" + creatorPhotoUrl);
        }

        createZipFile(filePathL, filePathR, configPath, thumbPath, previewPath);

        /*
         * let CamcorderActivity know we are done.
         */
        reportResult(MediaScanner.getProcessedCvrPath((new File(filePathL)).getName()));
    }

    /*
     * paranoia
     */
    if (bitmapL != null) {
        bitmapL.recycle();
    }
    if (bitmapR != null) {
        bitmapR.recycle();
    }

    (new File(exportL)).delete();
    (new File(exportR)).delete();
}

From source file:net.ustyugov.jtalk.activity.vcard.SetVcardActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == IMAGE && data != null) {
            Uri uri = Uri.parse(data.getDataString());
            if (uri != null) {
                try {
                    FileInputStream fileInput = getContentResolver().openAssetFileDescriptor(uri, "r")
                            .createInputStream();
                    bytes = new byte[fileInput.available()];
                    fileInput.read(bytes);
                    Bitmap bm = Bitmap.createScaledBitmap(BitmapFactory.decodeFileDescriptor(fileInput.getFD()),
                            240, 240, true);
                    av.setImageBitmap(bm);
                    fileInput.close();/*ww w  .j a  va2  s. c  om*/
                } catch (FileNotFoundException e) {
                } catch (IOException e) {
                }
            }
        }
    }
}

From source file:com.datafibers.kafka.connect.SchemaedFileSourceTask.java

private void openFileStream()
        throws ConnectException, InterruptedException, FileNotFoundException, IOException {
    try {//from w w w .j  a  va2  s.  c om
        FileInputStream fstream = new FileInputStream(filename);
        String fdes = fstream.getFD().valid() ? fstream.getFD().toString() : "unknown";

        stream = fstream;
        log.trace("FileInputStream created for {}; fd={}", filename, fdes);
        Map<String, Object> topicOffset = context.offsetStorageReader().offset(offsetKey(filename));
        if (topicOffset != null) {
            Object lastRecordedOffset = topicOffset.get(TASK_OFFSET_VALUE);
            if (lastRecordedOffset != null) {
                if (!(lastRecordedOffset instanceof Long)) {
                    throw new ConnectException("Offset position is the incorrect type");
                }

                if (streamOffset != null) {
                    if (streamOffset > (Long) lastRecordedOffset) {
                        log.trace("streamOffset ({}) is greater than lastRecordedOffset ({})",
                                streamOffset.toString(), lastRecordedOffset.toString());
                        lastRecordedOffset = streamOffset;
                    }
                } else {
                    if (config.getReplishAllData()) {
                        log.trace("Ignoring committed offset ({}) to allow republication of existing data",
                                lastRecordedOffset);
                        lastRecordedOffset = 0L;
                    }
                }
                long skipLeft = (Long) lastRecordedOffset;
                while (skipLeft > 0) {
                    try {
                        long skipped = stream.skip(skipLeft);
                        skipLeft -= skipped;
                    } catch (IOException e) {
                        log.error("Error while trying to seek to previous offset in file: ", e);
                        throw new ConnectException(e);
                    }
                }
                log.debug("Skipped to offset {}", lastRecordedOffset);
            }
            if (streamOffset == null) {
                streamOffset = (lastRecordedOffset != null) ? (Long) lastRecordedOffset : 0L;
            } else if (lastRecordedOffset != null) {
                streamOffset = java.lang.Math.max(streamOffset, (Long) lastRecordedOffset);
            }
        } else {
            if (streamOffset == null) {
                // first time through
                streamOffset = 0L;
            } else {
                // re-opening file ... make sure we skip over stuff we've read
                fstream.getChannel().position(streamOffset);
            }
        }
        log.debug("Opened {} for reading; current offset {}", logFilename(), streamOffset);
    } catch (FileNotFoundException e) {
        log.warn("Couldn't find file {} for SchemaedFileSourceTask, sleeping to wait for it to be created",
                logFilename());
        synchronized (this) {
            this.wait(1000);
        }
        throw e;
    } catch (IOException e) {
        log.warn("Unexpected IOException: {}", e.toString());
        synchronized (this) {
            this.wait(1000);
        }
        throw e;
    }
}

From source file:com.intel.xdk.audio.Audio.java

public void startPlaying(String url) {
    if (mediaPlayer != null) {
        try {/*from w  w  w .  j  a va2 s  .c  o  m*/
            if (mediaPlayer.isPlaying()) {
                injectJS(
                        "javascript:var ev = document.createEvent('Events');ev.initEvent('intel.xdk.audio.play.busy',true,true);document.dispatchEvent(ev);");
                return;
            }
        } catch (Exception e) {
        }
        mediaPlayer.release();
        mediaPlayer = null;
    }
    String path = fileFromUrl(url);
    File file = new File(path);
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(file);
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    }
    try {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnErrorListener(soundOnError);
        mediaPlayer.setOnCompletionListener(soundOnComplete);
        mediaPlayer.setDataSource(fis.getFD());
        mediaPlayer.prepare();
        mediaPlayer.start();
    } catch (Exception e) {
        injectJS(
                "javascript:var ev = document.createEvent('Events');ev.initEvent('intel.xdk.audio.play.error',true,true);document.dispatchEvent(ev);");
        return;
    }
    injectJS(
            "javascript:var ev = document.createEvent('Events');ev.initEvent('intel.xdk.audio.play.start',true,true);document.dispatchEvent(ev);");
}