Example usage for java.io FileNotFoundException toString

List of usage examples for java.io FileNotFoundException toString

Introduction

In this page you can find the example usage for java.io FileNotFoundException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:com.qcloud.PicCloud.java

public ArrayList<PornDetectInfo> pornDetectFile(String[] pornFile) {
    // create sign
    long expired = System.currentTimeMillis() / 1000 + 3600 * 24;
    String sign = getProcessSign(expired);
    if (null == sign) {
        setError(-1, "create app sign failed");
        return null;
    }// w  ww .  j a va  2 s  .co  m

    HashMap<String, String> header = new HashMap<String, String>();
    header.put("Authorization", sign);
    header.put("Host", PROCESS_DOMAIN);
    HashMap<String, Object> body = new HashMap<String, Object>();
    body.put("appid", mAppId);
    body.put("bucket", mBucket);

    byte[][] data = new byte[pornFile.length][];
    for (int i = 0; i < pornFile.length; i++) {
        String fileName = pornFile[i];
        if ("".equals(fileName)) {
            setError(-1, "invalid file name");
            return null;
        }
        FileInputStream fileStream = null;
        try {
            fileStream = new FileInputStream(fileName);
        } catch (FileNotFoundException ex) {
            setError(-1, fileName + " not found");
            return null;
        }
        try {
            data[i] = new byte[fileStream.available()];
            fileStream.read(data[i]);
            fileStream.close();
        } catch (Exception ex) {
            setError(-1, "io exception, e=" + ex.toString());
            return null;
        }
    }
    String reqUrl = "http://" + PROCESS_DOMAIN + "/detection/pornDetect";
    JSONObject rspData;
    try {
        String rsp = mClient.postfiles(reqUrl, header, body, data, pornFile);
        //rspData = getResponse(rsp);
        if ("".equals(rsp)) {
            setError(-1, "empty rsp");
            return null;
        }
        rspData = new JSONObject(rsp);
    } catch (Exception e) {
        setError(-1, "url exception, e=" + e.toString());
        return null;
    }
    if (!rspData.has("result_list")) {
        System.out.println("code = " + rspData.getInt("code"));
        System.out.println("message = " + rspData.getString("message"));
        if (rspData.has("data")) {
            System.out.println("data = " + rspData.getString("data"));
        }
        return null;
    }

    ArrayList<PornDetectInfo> info = new ArrayList<PornDetectInfo>();
    try {
        JSONArray rl;
        rl = rspData.getJSONArray("result_list");

        for (int i = 0; i < rl.length(); i++) {
            PornDetectInfo tmpinfo = new PornDetectInfo();
            JSONObject res = rl.getJSONObject(i);
            tmpinfo.code = res.getInt("code");
            tmpinfo.message = res.getString("message");
            tmpinfo.name = res.getString("filename");
            if (res.has("data")) {
                JSONObject resData = res.getJSONObject("data");
                tmpinfo.data.result = resData.getInt("result");
                tmpinfo.data.confidence = resData.getDouble("confidence");
                tmpinfo.data.pornScore = resData.getDouble("porn_score");
                tmpinfo.data.normalScore = resData.getDouble("normal_score");
                tmpinfo.data.hotScore = resData.getDouble("hot_score");
                tmpinfo.data.forbidStatus = resData.getInt("forbid_status");
            }
            info.add(tmpinfo);
        }
    } catch (JSONException e) {
        setError(-2, "json exception, e=" + e.toString());
        return null;
    }
    setError(0, "success");
    return info;
}

From source file:ffx.ui.KeywordPanel.java

/**
 * <p>/*ww  w  . ja va 2 s  .c o m*/
 * saveKeywords</p>
 *
 * @param keyFile a {@link java.io.File} object.
 * @param keywordHashMap a {@link java.util.LinkedHashMap} object.
 * @param comments a {@link java.lang.StringBuilder} object.
 * @return a boolean.
 */
public boolean saveKeywords(File keyFile, LinkedHashMap<String, KeywordComponent> keywordHashMap,
        StringBuilder comments) {
    synchronized (this) {
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fw = new FileWriter(keyFile);
            bw = new BufferedWriter(fw);
            boolean writegroup = false;
            String pgroup = null;
            // Write out keywords in groups
            for (KeywordComponent keyword : keywordHashMap.values()) {
                String group = keyword.getKeywordGroup();
                if (pgroup == null || !group.equalsIgnoreCase(pgroup)) {
                    writegroup = true;
                    pgroup = group;
                }
                String line = keyword.toString();
                if (line != null) {
                    if (writegroup == true) {
                        bw.newLine();
                        bw.write("# " + group);
                        bw.newLine();
                        writegroup = false;
                    }
                    bw.write(line);
                    bw.newLine();
                }
            }
            bw.newLine();
            String s = comments.toString();
            if (s != null && !s.trim().equals("")) {
                bw.write(s.trim());
            }
            bw.newLine();
            bw.flush();
            KeywordComponent.setKeywordModified(false);
        } catch (FileNotFoundException e) {
            logger.warning(e.toString());
            return false;
        } catch (IOException e) {
            logger.warning(e.toString());
            return false;
        } finally {
            try {
                if (bw != null) {
                    bw.close();
                }
                if (fw != null) {
                    fw.close();
                }
            } catch (Exception e) {
                logger.warning(e.toString());
            }
        }
        return true;
    }
}

From source file:de.arcus.playmusiclib.PlayMusicManager.java

/**
 * Exports a track to the sd card/*w w w. j a v a  2  s. com*/
 * @param musicTrack The music track you want to export
 * @param uri The document tree
 * @return Returns whether the export was successful
 */
public boolean exportMusicTrack(MusicTrack musicTrack, Uri uri, String path) {

    // Check for null
    if (musicTrack == null)
        return false;

    String srcFile = musicTrack.getSourceFile();

    // Could not find the source file
    if (srcFile == null)
        return false;

    String fileTmp = getTempPath() + "/tmp.mp3";

    // Copy to temp path failed
    if (!SuperUserTools.fileCopy(srcFile, fileTmp))
        return false;

    // Encrypt the file
    if (musicTrack.isEncoded()) {
        String fileTmpCrypt = getTempPath() + "/crypt.mp3";

        // Encrypts the file
        if (trackEncrypt(musicTrack, fileTmp, fileTmpCrypt)) {
            // Remove the old tmp file
            FileTools.fileDelete(fileTmp);

            // New tmp file
            fileTmp = fileTmpCrypt;
        } else {
            Logger.getInstance().logWarning("ExportMusicTrack",
                    "Encrypting failed! Continue with decrypted file.");
        }
    }

    String dest;
    Uri copyUri = null;
    if (uri.toString().startsWith("file://")) {
        // Build the full path
        dest = uri.buildUpon().appendPath(path).build().getPath();

        String parentDirectory = new File(dest).getParent();
        FileTools.directoryCreate(parentDirectory);
    } else {
        // Complex uri (Lollipop)
        dest = getTempPath() + "/final.mp3";

        // The root
        DocumentFile document = DocumentFile.fromTreeUri(mContext, uri);

        // Creates the subdirectories
        String[] directories = path.split("\\/");
        for (int i = 0; i < directories.length - 1; i++) {
            String directoryName = directories[i];
            boolean found = false;

            // Search all sub elements
            for (DocumentFile subDocument : document.listFiles()) {
                // Directory exists
                if (subDocument.isDirectory() && subDocument.getName().equals(directoryName)) {
                    document = subDocument;
                    found = true;
                    break;
                }
            }

            if (!found) {
                // Create the directory
                document = document.createDirectory(directoryName);
            }
        }

        // Gets the filename
        String filename = directories[directories.length - 1];

        for (DocumentFile subDocument : document.listFiles()) {
            // Directory exists
            if (subDocument.isFile() && subDocument.getName().equals(filename)) {
                // Delete the file
                subDocument.delete();
                break;
            }
        }

        // Create the mp3 file
        document = document.createFile("music/mp3", filename);

        // Create the directories
        copyUri = document.getUri();
    }

    // We want to export the ID3 tags
    if (mID3Enable) {
        // Adds the meta data
        if (!trackWriteID3(musicTrack, fileTmp, dest)) {
            Logger.getInstance().logWarning("ExportMusicTrack",
                    "ID3 writer failed! Continue without ID3 tags.");

            // Failed, moving without meta data
            if (!FileTools.fileMove(fileTmp, dest)) {
                Logger.getInstance().logError("ExportMusicTrack", "Moving the raw file failed!");

                // Could not copy the file
                return false;
            }
        }
    } else {
        // Moving the file
        if (!FileTools.fileMove(fileTmp, dest)) {
            Logger.getInstance().logError("ExportMusicTrack", "Moving the raw file failed!");

            // Could not copy the file
            return false;
        }
    }

    // We need to copy the file to a uri
    if (copyUri != null) {
        // Lollipop only
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                // Gets the file descriptor
                ParcelFileDescriptor parcelFileDescriptor = mContext.getContentResolver()
                        .openFileDescriptor(copyUri, "w");

                // Gets the output stream
                FileOutputStream fileOutputStream = new FileOutputStream(
                        parcelFileDescriptor.getFileDescriptor());

                // Gets the input stream
                FileInputStream fileInputStream = new FileInputStream(dest);

                // Copy the stream
                FileTools.fileCopy(fileInputStream, fileOutputStream);

                // Close all streams
                fileOutputStream.close();
                fileInputStream.close();
                parcelFileDescriptor.close();

            } catch (FileNotFoundException e) {
                Logger.getInstance().logError("ExportMusicTrack", "File not found!");

                // Could not copy the file
                return false;
            } catch (IOException e) {
                Logger.getInstance().logError("ExportMusicTrack",
                        "Failed to write the document: " + e.toString());

                // Could not copy the file
                return false;
            }
        }
    }

    // Delete temp files
    cleanUp();

    // Adds the file to the media system
    //new MediaScanner(mContext, dest);

    // Done
    return true;
}

From source file:android.com.example.contactslist.ui.ContactsListFragment.java

/**
 * Decodes and scales a contact's image from a file pointed to by a Uri in the contact's data,
 * and returns the result as a Bitmap. The column that contains the Uri varies according to the
 * platform version./*from w  w  w .  j  av  a  2s  .  c  o m*/
 *
 * @param photoData For platforms prior to Android 3.0, provide the Contact._ID column value.
 *                  For Android 3.0 and later, provide the Contact.PHOTO_THUMBNAIL_URI value.
 * @param imageSize The desired target width and height of the output image in pixels.
 * @return A Bitmap containing the contact's image, resized to fit the provided image size. If
 * no thumbnail exists, returns null.
 */
private Bitmap loadContactPhotoThumbnail(String photoData, int imageSize) {

    // Ensures the Fragment is still added to an activity. As this method is called in a
    // background thread, there's the possibility the Fragment is no longer attached and
    // added to an activity. If so, no need to spend resources loading the contact photo.
    if (!isAdded() || getActivity() == null) {
        return null;
    }

    // Instantiates an AssetFileDescriptor. Given a content Uri pointing to an image file, the
    // ContentResolver can return an AssetFileDescriptor for the file.
    AssetFileDescriptor afd = null;

    // This "try" block catches an Exception if the file descriptor returned from the Contacts
    // Provider doesn't point to an existing file.
    try {
        Uri thumbUri;
        // If Android 3.0 or later, converts the Uri passed as a string to a Uri object.
        if (Utils.hasHoneycomb()) {
            thumbUri = Uri.parse(photoData);
        } else {
            // For versions prior to Android 3.0, appends the string argument to the content
            // Uri for the Contacts table.
            final Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_URI, photoData);

            // Appends the content Uri for the Contacts.Photo table to the previously
            // constructed contact Uri to yield a content URI for the thumbnail image
            thumbUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY);
        }
        // Retrieves a file descriptor from the Contacts Provider. To learn more about this
        // feature, read the reference documentation for
        // ContentResolver#openAssetFileDescriptor.
        afd = getActivity().getContentResolver().openAssetFileDescriptor(thumbUri, "r");

        // Gets a FileDescriptor from the AssetFileDescriptor. A BitmapFactory object can
        // decode the contents of a file pointed to by a FileDescriptor into a Bitmap.
        FileDescriptor fileDescriptor = afd.getFileDescriptor();

        if (fileDescriptor != null) {
            // Decodes a Bitmap from the image pointed to by the FileDescriptor, and scales it
            // to the specified width and height
            return ImageLoader.decodeSampledBitmapFromDescriptor(fileDescriptor, imageSize, imageSize);
        }
    } catch (FileNotFoundException e) {
        // If the file pointed to by the thumbnail URI doesn't exist, or the file can't be
        // opened in "read" mode, ContentResolver.openAssetFileDescriptor throws a
        // FileNotFoundException.
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Contact photo thumbnail not found for contact " + photoData + ": " + e.toString());
        }
    } finally {
        // If an AssetFileDescriptor was returned, try to close it
        if (afd != null) {
            try {
                afd.close();
            } catch (IOException e) {
                // Closing a file descriptor might cause an IOException if the file is
                // already closed. Nothing extra is needed to handle this.
            }
        }
    }

    // If the decoding failed, returns null
    return null;
}

From source file:com.forktech.cmerge.ui.ContactsListFragment.java

/**
 * Decodes and scales a contact's image from a file pointed to by a Uri in
 * the contact's data, and returns the result as a Bitmap. The column that
 * contains the Uri varies according to the platform version.
 *
 * @param photoData//from w w w .  j a  v a 2 s.c  o m
 *            For platforms prior to Android 3.0, provide the Contact._ID
 *            column value. For Android 3.0 and later, provide the
 *            Contact.PHOTO_THUMBNAIL_URI value.
 * @param imageSize
 *            The desired target width and height of the output image in
 *            pixels.
 * @return A Bitmap containing the contact's image, resized to fit the
 *         provided image size. If no thumbnail exists, returns null.
 */
private Bitmap loadContactPhotoThumbnail(String photoData, int imageSize) {

    // Ensures the Fragment is still added to an activity. As this method is
    // called in a
    // background thread, there's the possibility the Fragment is no longer
    // attached and
    // added to an activity. If so, no need to spend resources loading the
    // contact photo.
    if (!isAdded() || getActivity() == null) {
        return null;
    }

    // Instantiates an AssetFileDescriptor. Given a content Uri pointing to
    // an image file, the
    // ContentResolver can return an AssetFileDescriptor for the file.
    AssetFileDescriptor afd = null;

    // This "try" block catches an Exception if the file descriptor returned
    // from the Contacts
    // Provider doesn't point to an existing file.
    try {
        Uri thumbUri;
        // If Android 3.0 or later, converts the Uri passed as a string to a
        // Uri object.
        if (Utils.hasHoneycomb()) {
            thumbUri = Uri.parse(photoData);
        } else {
            // For versions prior to Android 3.0, appends the string
            // argument to the content
            // Uri for the Contacts table.
            final Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_URI, photoData);

            // Appends the content Uri for the Contacts.Photo table to the
            // previously
            // constructed contact Uri to yield a content URI for the
            // thumbnail image
            thumbUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY);
        }
        // Retrieves a file descriptor from the Contacts Provider. To learn
        // more about this
        // feature, read the reference documentation for
        // ContentResolver#openAssetFileDescriptor.
        afd = getActivity().getContentResolver().openAssetFileDescriptor(thumbUri, "r");

        // Gets a FileDescriptor from the AssetFileDescriptor. A
        // BitmapFactory object can
        // decode the contents of a file pointed to by a FileDescriptor into
        // a Bitmap.
        FileDescriptor fileDescriptor = afd.getFileDescriptor();

        if (fileDescriptor != null) {
            // Decodes a Bitmap from the image pointed to by the
            // FileDescriptor, and scales it
            // to the specified width and height
            return ImageLoader.decodeSampledBitmapFromDescriptor(fileDescriptor, imageSize, imageSize);
        }
    } catch (FileNotFoundException e) {
        // If the file pointed to by the thumbnail URI doesn't exist, or the
        // file can't be
        // opened in "read" mode, ContentResolver.openAssetFileDescriptor
        // throws a
        // FileNotFoundException.
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Contact photo thumbnail not found for contact " + photoData + ": " + e.toString());
        }
    } finally {
        // If an AssetFileDescriptor was returned, try to close it
        if (afd != null) {
            try {
                afd.close();
            } catch (IOException e) {
                // Closing a file descriptor might cause an IOException if
                // the file is
                // already closed. Nothing extra is needed to handle this.
            }
        }
    }

    // If the decoding failed, returns null
    return null;
}

From source file:co.tinode.tindroid.ContactsFragment.java

/**
 * Decodes and scales a contact's image from a file pointed to by a Uri in the contact's data,
 * and returns the result as a Bitmap. The column that contains the Uri varies according to the
 * platform version./*  w w  w. j a  v  a2s.  c om*/
 *
 * @param photoData For platforms prior to Android 3.0, provide the Contact._ID column value.
 *                  For Android 3.0 and later, provide the Contact.PHOTO_THUMBNAIL_URI value.
 * @param imageSize The desired target width and height of the output image in pixels.
 * @return A Bitmap containing the contact's image, resized to fit the provided image size. If
 * no thumbnail exists, returns null.
 */
private Bitmap loadContactPhotoThumbnail(String photoData, int imageSize) {

    // Ensures the Fragment is still added to an activity. As this method is called in a
    // background thread, there's the possibility the Fragment is no longer attached and
    // added to an activity. If so, no need to spend resources loading the contact photo.
    if (!isAdded() || getActivity() == null) {
        return null;
    }

    // Instantiates an AssetFileDescriptor. Given a content Uri pointing to an image file, the
    // ContentResolver can return an AssetFileDescriptor for the file.
    AssetFileDescriptor afd = null;

    // This "try" block catches an Exception if the file descriptor returned from the Contacts
    // Provider doesn't point to an existing file.
    try {
        Uri thumbUri = Uri.parse(photoData);

        // Retrieves a file descriptor from the Contacts Provider. To learn more about this
        // feature, read the reference documentation for
        // ContentResolver#openAssetFileDescriptor.
        afd = getActivity().getContentResolver().openAssetFileDescriptor(thumbUri, "r");

        // Gets a FileDescriptor from the AssetFileDescriptor. A BitmapFactory object can
        // decode the contents of a file pointed to by a FileDescriptor into a Bitmap.
        FileDescriptor fileDescriptor = afd.getFileDescriptor();
        if (fileDescriptor != null) {
            // Decodes a Bitmap from the image pointed to by the FileDescriptor, and scales it
            // to the specified width and height
            return ImageLoader.decodeSampledBitmapFromDescriptor(fileDescriptor, imageSize, imageSize);
        }
    } catch (FileNotFoundException e) {
        // If the file pointed to by the thumbnail URI doesn't exist, or the file can't be
        // opened in "read" mode, ContentResolver.openAssetFileDescriptor throws a
        // FileNotFoundException.
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Contact photo thumbnail not found for contact " + photoData + ": " + e.toString());
        }
    } finally {
        // If an AssetFileDescriptor was returned, try to close it
        if (afd != null) {
            try {
                afd.close();
            } catch (IOException unused) {
                // Closing a file descriptor might cause an IOException if the file is
                // already closed. Nothing extra is needed to handle this.
            }
        }
    }

    // If the decoding failed, returns null
    return null;
}

From source file:br.com.mybaby.contatos.ContactsListFragment.java

/**
 * Decodes and scales a contact's image from a file pointed to by a Uri in the contact's data,
 * and returns the result as a Bitmap. The column that contains the Uri varies according to the
 * platform version.// ww w. j  a  va 2  s .c  o  m
 *
 * @param photoData For platforms prior to Android 3.0, provide the Contact._ID column value.
 *                  For Android 3.0 and later, provide the Contact.PHOTO_THUMBNAIL_URI value.
 * @param imageSize The desired target width and height of the output image in pixels.
 * @return A Bitmap containing the contact's image, resized to fit the provided image size. If
 * no thumbnail exists, returns null.
 */
private Bitmap loadContactPhotoThumbnail(String photoData, int imageSize) {

    // Ensures the Fragment is still added to an activity. As this method is called in a
    // background thread, there's the possibility the Fragment is no longer attached and
    // added to an activity. If so, no need to spend resources loading the contact photo.
    if (!isAdded() || getActivity() == null) {
        return null;
    }

    // Instantiates an AssetFileDescriptor. Given a content Uri pointing to an image file, the
    // ContentResolver can return an AssetFileDescriptor for the file.
    AssetFileDescriptor afd = null;

    // This "try" block catches an Exception if the file descriptor returned from the Contacts
    // Provider doesn't point to an existing file.
    try {
        Uri thumbUri;
        // If Android 3.0 or later, converts the Uri passed as a string to a Uri object.
        if (Util.hasHoneycomb()) {
            thumbUri = Uri.parse(photoData);
        } else {
            // For versions prior to Android 3.0, appends the string argument to the content
            // Uri for the Contacts table.
            final Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_URI, photoData);

            // Appends the content Uri for the Contacts.Photo table to the previously
            // constructed contact Uri to yield a content URI for the thumbnail image
            thumbUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY);
        }
        // Retrieves a file descriptor from the Contacts Provider. To learn more about this
        // feature, read the reference documentation for
        // ContentResolver#openAssetFileDescriptor.
        afd = getActivity().getContentResolver().openAssetFileDescriptor(thumbUri, "r");

        // Gets a FileDescriptor from the AssetFileDescriptor. A BitmapFactory object can
        // decode the contents of a file pointed to by a FileDescriptor into a Bitmap.
        FileDescriptor fileDescriptor = afd.getFileDescriptor();

        if (fileDescriptor != null) {
            // Decodes a Bitmap from the image pointed to by the FileDescriptor, and scales it
            // to the specified width and height
            return ImageLoader.decodeSampledBitmapFromDescriptor(fileDescriptor, imageSize, imageSize);
        }
    } catch (FileNotFoundException e) {
        // If the file pointed to by the thumbnail URI doesn't exist, or the file can't be
        // opened in "read" mode, ContentResolver.openAssetFileDescriptor throws a
        // FileNotFoundException.
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Contact photo thumbnail not found for contact " + photoData + ": " + e.toString());
        }
    } finally {
        // If an AssetFileDescriptor was returned, try to close it
        if (afd != null) {
            try {
                afd.close();
            } catch (IOException e) {
                // Closing a file descriptor might cause an IOException if the file is
                // already closed. Nothing extra is needed to handle this.
            }
        }
    }

    // If the decoding failed, returns null
    return null;
}

From source file:br.com.mybaby.contatos.ContactDetailFragment.java

/**
 * Decodes and returns the contact's thumbnail image.
 * @param contactUri The Uri of the contact containing the image.
 * @param imageSize The desired target width and height of the output image in pixels.
 * @return If a thumbnail image exists for the contact, a Bitmap image, otherwise null.
 *//*  w ww  . j a v a  2s.  co m*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private Bitmap loadContactPhoto(Uri contactUri, int imageSize) {

    // Ensures the Fragment is still added to an activity. As this method is called in a
    // background thread, there's the possibility the Fragment is no longer attached and
    // added to an activity. If so, no need to spend resources loading the contact photo.
    if (!isAdded() || getActivity() == null) {
        return null;
    }

    // Instantiates a ContentResolver for retrieving the Uri of the image
    final ContentResolver contentResolver = getActivity().getContentResolver();

    // Instantiates an AssetFileDescriptor. Given a content Uri pointing to an image file, the
    // ContentResolver can return an AssetFileDescriptor for the file.
    AssetFileDescriptor afd = null;

    if (Util.hasICS()) {
        // On platforms running Android 4.0 (API version 14) and later, a high resolution image
        // is available from Photo.DISPLAY_PHOTO.
        try {
            // Constructs the content Uri for the image
            Uri displayImageUri = Uri.withAppendedPath(contactUri, Photo.DISPLAY_PHOTO);

            // Retrieves an AssetFileDescriptor from the Contacts Provider, using the
            // constructed Uri
            afd = contentResolver.openAssetFileDescriptor(displayImageUri, "r");
            // If the file exists
            if (afd != null) {
                // Reads and decodes the file to a Bitmap and scales it to the desired size
                return ImageLoader.decodeSampledBitmapFromDescriptor(afd.getFileDescriptor(), imageSize,
                        imageSize);
            }
        } catch (FileNotFoundException e) {
            // Catches file not found exceptions
            if (BuildConfig.DEBUG) {
                // Log debug message, this is not an error message as this exception is thrown
                // when a contact is legitimately missing a contact photo (which will be quite
                // frequently in a long contacts list).
                Log.d(TAG,
                        "Contact photo not found for contact " + contactUri.toString() + ": " + e.toString());
            }
        } finally {
            // Once the decode is complete, this closes the file. You must do this each time
            // you access an AssetFileDescriptor; otherwise, every image load you do will open
            // a new descriptor.
            if (afd != null) {
                try {
                    afd.close();
                } catch (IOException e) {
                    // Closing a file descriptor might cause an IOException if the file is
                    // already closed. Nothing extra is needed to handle this.
                }
            }
        }
    }

    // If the platform version is less than Android 4.0 (API Level 14), use the only available
    // image URI, which points to a normal-sized image.
    try {
        // Constructs the image Uri from the contact Uri and the directory twig from the
        // Contacts.Photo table
        Uri imageUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY);

        // Retrieves an AssetFileDescriptor from the Contacts Provider, using the constructed
        // Uri
        afd = getActivity().getContentResolver().openAssetFileDescriptor(imageUri, "r");

        // If the file exists
        if (afd != null) {
            // Reads the image from the file, decodes it, and scales it to the available screen
            // area
            return ImageLoader.decodeSampledBitmapFromDescriptor(afd.getFileDescriptor(), imageSize, imageSize);
        }
    } catch (FileNotFoundException e) {
        // Catches file not found exceptions
        if (BuildConfig.DEBUG) {
            // Log debug message, this is not an error message as this exception is thrown
            // when a contact is legitimately missing a contact photo (which will be quite
            // frequently in a long contacts list).
            Log.d(TAG, "Contact photo not found for contact " + contactUri.toString() + ": " + e.toString());
        }
    } finally {
        // Once the decode is complete, this closes the file. You must do this each time you
        // access an AssetFileDescriptor; otherwise, every image load you do will open a new
        // descriptor.
        if (afd != null) {
            try {
                afd.close();
            } catch (IOException e) {
                // Closing a file descriptor might cause an IOException if the file is
                // already closed. Ignore this.
            }
        }
    }

    // If none of the case selectors match, returns null.
    return null;
}

From source file:org.openhab.ui.cometvisu.servlet.CometVisuServlet.java

/**
 * Service.//  ww w . j a v a2  s.co  m
 */
private final void phpService(File file, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Env env = null;
    WriteStream ws = null;

    QuercusHttpServletRequest req = new QuercusHttpServletRequestImpl(request);
    QuercusHttpServletResponse res = new QuercusHttpServletResponseImpl(response);

    try {
        Path path = getPath(file, req);
        logger.info("phpService path: " + path);

        QuercusPage page;

        try {
            page = engine.getQuercus().parse(path);
        } catch (FileNotFoundException e) {
            // php/2001
            logger.debug(e.toString(), e);

            response.sendError(HttpServletResponse.SC_NOT_FOUND);

            return;
        }

        ws = openWrite(response);

        // php/2002
        // for non-Resin containers
        // for servlet filters that do post-request work after Quercus
        ws.setDisableCloseSource(true);

        // php/6006
        ws.setNewlineString("\n");

        QuercusContext quercus = engine.getQuercus();

        env = quercus.createEnv(page, ws, req, res);

        // php/815d
        env.setPwd(path.getParent());
        logger.info("setting user dir to " + path.getParent().getNativePath());
        System.setProperty("user.dir", path.getParent().getNativePath());
        quercus.setServletContext(new QuercusServletContextImpl(_servletContext));

        try {
            env.start();

            // php/2030, php/2032, php/2033
            // Jetty hides server classes from web-app
            // http://docs.codehaus.org/display/JETTY/Classloading
            //
            // env.setGlobalValue("request", env.wrapJava(request));
            // env.setGlobalValue("response", env.wrapJava(response));
            // env.setGlobalValue("servletContext",
            // env.wrapJava(_servletContext));

            StringValue prepend = quercus.getIniValue("auto_prepend_file").toStringValue(env);
            if (prepend.length() > 0) {
                Path prependPath = env.lookup(prepend);

                if (prependPath == null)
                    env.error(L.l("auto_prepend_file '{0}' not found.", prepend));
                else {
                    QuercusPage prependPage = engine.getQuercus().parse(prependPath);
                    prependPage.executeTop(env);
                }
            }

            env.executeTop();

            StringValue append = quercus.getIniValue("auto_append_file").toStringValue(env);
            if (append.length() > 0) {
                Path appendPath = env.lookup(append);

                if (appendPath == null)
                    env.error(L.l("auto_append_file '{0}' not found.", append));
                else {
                    QuercusPage appendPage = engine.getQuercus().parse(appendPath);
                    appendPage.executeTop(env);
                }
            }
            // return;
        } catch (QuercusExitException e) {
            throw e;
        } catch (QuercusErrorException e) {
            throw e;
        } catch (QuercusLineRuntimeException e) {
            logger.debug(e.toString(), e);

            ws.println(e.getMessage());
            // return;
        } catch (QuercusValueException e) {
            logger.debug(e.toString(), e);

            ws.println(e.toString());

            // return;
        } catch (StackOverflowError e) {
            RuntimeException myException = new RuntimeException(
                    L.l("StackOverflowError at {0}", env.getLocation()), e);

            throw myException;
        } catch (Throwable e) {
            if (response.isCommitted())
                e.printStackTrace(ws.getPrintWriter());

            ws = null;

            throw e;
        } finally {
            if (env != null)
                env.close();

            // don't want a flush for an exception
            if (ws != null && env != null && env.getDuplex() == null)
                ws.close();

            System.setProperty("user.dir", defaultUserDir);
        }
    } catch (QuercusDieException e) {
        // normal exit
        logger.trace(e.getMessage(), e);
    } catch (QuercusExitException e) {
        // normal exit
        logger.trace(e.getMessage(), e);
    } catch (QuercusErrorException e) {
        // error exit
        logger.error(e.getMessage(), e);
    } catch (RuntimeException e) {
        throw e;
    } catch (Throwable e) {
        handleThrowable(response, e);
    }
}

From source file:edu.utexas.cs.tactex.servercustomers.factoredcustomer.TimeseriesGenerator.java

private void initArima101x101RefSeries() {
    InputStream refStream;/*from  w  ww.ja v a  2s. c o m*/
    String seriesName = tsStructure.refSeriesName;
    switch (tsStructure.refSeriesSource) {
    case BUILTIN:
        throw new Error("Unknown builtin series name: " + seriesName);
        // break;
    case CLASSPATH:
        refStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(seriesName);
        break;
    case FILEPATH:
        try {
            refStream = new FileInputStream(seriesName);
        } catch (FileNotFoundException e) {
            throw new Error("Could not find file to initialize reference timeseries: " + seriesName);
        }
        break;
    default:
        throw new Error("Unexpected reference timeseries source type: " + tsStructure.refSeriesSource);
    }
    if (refStream == null)
        throw new Error("Reference timeseries input stream is uninitialized!");

    try {
        @SuppressWarnings("unchecked")
        List<String> series = (List<String>) IOUtils.readLines(refStream);
        for (String line : series) {
            Double element = Double.parseDouble(line);
            refSeries.add(element);
        }
    } catch (java.io.EOFException e) {
        final int MIN_TIMESERIES_LENGTH = 26;
        if (refSeries.size() < MIN_TIMESERIES_LENGTH) {
            throw new Error("Insufficient data in reference series; expected " + MIN_TIMESERIES_LENGTH
                    + " elements, found only " + genSeries.size());
        }
    } catch (java.io.IOException e) {
        throw new Error("Error reading timeseries data from file: " + seriesName + "; caught IOException: "
                + e.toString());
    }
}