Search in sources :

Example 6 with FileSystemStorage

use of com.codename1.io.FileSystemStorage in project CodenameOne by codenameone.

the class FileSystemTests method runTest.

@Override
public boolean runTest() throws Exception {
    FileSystemStorage fs = FileSystemStorage.getInstance();
    String homePath = fs.getAppHomePath();
    this.assertTrue(homePath.startsWith("file://"), "App Home Path should start with file:// but was " + homePath);
    String testFileContents = "Hello World";
    String testFilePath = homePath + fs.getFileSystemSeparator() + "testfile.txt";
    try (OutputStream os = fs.openOutputStream(testFilePath)) {
        os.write(testFileContents.getBytes("UTF-8"));
    }
    this.assertTrue(fs.exists(testFilePath), "Created file " + testFilePath + " but fs says it doesn't exist");
    String readContents = null;
    try (InputStream is = fs.openInputStream(testFilePath)) {
        byte[] buf = testFileContents.getBytes("UTF-8");
        for (int i = 0; i < buf.length; i++) {
            buf[i] = (byte) 0;
        }
        int len = is.read(buf);
        this.assertEqual(buf.length, len, "Bytes read didn't match expected");
        readContents = new String(buf, "UTF-8");
    }
    this.assertEqual(testFileContents, readContents, "Contents of file doesn't match expected contents after write and read");
    return true;
}
Also used : FileSystemStorage(com.codename1.io.FileSystemStorage) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream)

Example 7 with FileSystemStorage

use of com.codename1.io.FileSystemStorage in project CodenameOne by codenameone.

the class ConnectionRequest method downloadImage.

private void downloadImage(final SuccessCallback<Image> onSuccess, final FailureCallback<Image> onFail, boolean useCache) {
    setReadResponseForErrors(false);
    if (useCache) {
        Display.getInstance().scheduleBackgroundTask(new Runnable() {

            public void run() {
                if (getDestinationFile() != null) {
                    String file = getDestinationFile();
                    FileSystemStorage fs = FileSystemStorage.getInstance();
                    if (fs.exists(file)) {
                        try {
                            EncodedImage img = EncodedImage.create(fs.openInputStream(file), (int) fs.getLength(file));
                            if (img == null) {
                                throw new IOException("Failed to load image at " + file);
                            }
                            CallbackDispatcher.dispatchSuccess(onSuccess, img);
                        } catch (Exception ex) {
                            CallbackDispatcher.dispatchError(onFail, ex);
                        }
                    } else {
                        downloadImage(onSuccess, onFail, false);
                    }
                } else if (getDestinationStorage() != null) {
                    String file = getDestinationStorage();
                    Storage fs = Storage.getInstance();
                    if (fs.exists(file)) {
                        try {
                            EncodedImage img = EncodedImage.create(fs.createInputStream(file), fs.entrySize(file));
                            if (img == null) {
                                throw new IOException("Failed to load image at " + file);
                            }
                            CallbackDispatcher.dispatchSuccess(onSuccess, img);
                        } catch (Exception ex) {
                            CallbackDispatcher.dispatchError(onFail, ex);
                        }
                    } else {
                        downloadImage(onSuccess, onFail, false);
                    }
                }
            }
        });
    } else {
        final ActionListener onDownload = new ActionListener<NetworkEvent>() {

            public void actionPerformed(NetworkEvent nevt) {
                int rc = nevt.getResponseCode();
                if (rc == 200 || rc == 201) {
                    downloadImage(onSuccess, onFail, true);
                } else {
                    if (nevt.getError() == null) {
                        nevt.setError(new IOException("Failed to get image:  Code was " + nevt.getResponseCode()));
                    }
                    CallbackDispatcher.dispatchError(onFail, nevt.getError());
                }
                removeResponseListener(this);
            }
        };
        addResponseListener(onDownload);
        NetworkManager.getInstance().addToQueue(this);
    }
}
Also used : ActionListener(com.codename1.ui.events.ActionListener) IOException(java.io.IOException) EncodedImage(com.codename1.ui.EncodedImage) IOException(java.io.IOException) ParseException(com.codename1.l10n.ParseException)

Example 8 with FileSystemStorage

use of com.codename1.io.FileSystemStorage in project CodenameOne by codenameone.

the class TarEntry method extractTarHeader.

/**
 * Extract header from File
 *
 * @param entryName
 */
public void extractTarHeader(String entryName) {
    String name = entryName;
    FileSystemStorage fileSystem = FileSystemStorage.getInstance();
    name = name.replace(fileSystem.getFileSystemSeparator(), '/');
    if (name.startsWith("/"))
        name = name.substring(1);
    header.linkName = new StringBuffer("");
    header.name = new StringBuffer(name);
    if (fileSystem.isDirectory(file)) {
        header.mode = 040755;
        header.linkFlag = TarHeader.LF_DIR;
        if (header.name.charAt(header.name.length() - 1) != '/') {
            header.name.append("/");
        }
        header.size = 0;
    } else {
        header.size = fileSystem.getLength(file);
        header.mode = 0100644;
        header.linkFlag = TarHeader.LF_NORMAL;
    }
    // header.modTime = file.lastModified() / 1000;
    header.modTime = 0;
    header.checkSum = 0;
    header.devMajor = 0;
    header.devMinor = 0;
}
Also used : FileSystemStorage(com.codename1.io.FileSystemStorage)

Example 9 with FileSystemStorage

use of com.codename1.io.FileSystemStorage in project CodenameOne by codenameone.

the class URLImage method createCachedImage.

/**
 * Creates an image that will be downloaded on the fly as necessary.  On platforms that support a native
 * image cache (e.g. Javascript), the image will be loaded directly from the native cache (i.e. it defers to the
 * platform to handle all caching considerations.  On platforms that don't have a native image cache but
 * do have a caches directory {@link FileSystemStorage#hasCachesDir()}, this will call {@link #createToFileSystem(com.codename1.ui.EncodedImage, java.lang.String, java.lang.String, com.codename1.ui.URLImage.ImageAdapter) }
 * with a file location in the caches directory.  In all other cases, this will call {@link #createToStorage(com.codename1.ui.EncodedImage, java.lang.String, java.lang.String) }.
 *
 * @param imageName The name of the image.
 * @param url the URL from which the image is fetched
 * @param placeholder the image placeholder is shown as the image is loading/downloading
 * and serves as the guideline to the size of the downloaded image.
 * @param resizeRule One of {@link #FLAG_RESIZE_FAIL}, {@link #FLAG_RESIZE_SCALE}, or {@link #FLAG_RESIZE_SCALE_TO_FILL}.
 * @return a Image that will initially just delegate to the placeholder
 */
public static Image createCachedImage(String imageName, String url, Image placeholder, int resizeRule) {
    if (Display.getInstance().supportsNativeImageCache()) {
        CachedImage im = new CachedImage(placeholder, url, resizeRule);
        im.setImageName(imageName);
        return im;
    } else {
        ImageAdapter adapter = null;
        switch(resizeRule) {
            case FLAG_RESIZE_FAIL:
                adapter = RESIZE_FAIL;
                break;
            case FLAG_RESIZE_SCALE:
                adapter = RESIZE_SCALE;
                break;
            case FLAG_RESIZE_SCALE_TO_FILL:
                adapter = RESIZE_SCALE_TO_FILL;
                break;
            default:
                adapter = RESIZE_SCALE_TO_FILL;
                break;
        }
        FileSystemStorage fs = FileSystemStorage.getInstance();
        if (fs.hasCachesDir()) {
            String name = "cn1_image_cache[" + url + "]";
            name = StringUtil.replaceAll(name, "/", "_");
            name = StringUtil.replaceAll(name, "\\", "_");
            name = StringUtil.replaceAll(name, "%", "_");
            name = StringUtil.replaceAll(name, "?", "_");
            name = StringUtil.replaceAll(name, "*", "_");
            name = StringUtil.replaceAll(name, ":", "_");
            name = StringUtil.replaceAll(name, "=", "_");
            String filePath = fs.getCachesDir() + fs.getFileSystemSeparator() + name;
            // System.out.println("Creating to file system "+filePath);
            URLImage im = createToFileSystem(EncodedImage.createFromImage(placeholder, false), filePath, url, adapter);
            im.setImageName(imageName);
            return im;
        } else {
            // System.out.println("Creating to storage ");
            URLImage im = createToStorage(EncodedImage.createFromImage(placeholder, false), "cn1_image_cache[" + url + "@" + placeholder.getWidth() + "x" + placeholder.getHeight(), url, adapter);
            im.setImageName(imageName);
            return im;
        }
    }
}
Also used : FileSystemStorage(com.codename1.io.FileSystemStorage)

Aggregations

FileSystemStorage (com.codename1.io.FileSystemStorage)7 OutputStream (java.io.OutputStream)3 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 Paint (android.graphics.Paint)1 BufferedInputStream (com.codename1.io.BufferedInputStream)1 BufferedOutputStream (com.codename1.io.BufferedOutputStream)1 TarEntry (com.codename1.io.tar.TarEntry)1 TarInputStream (com.codename1.io.tar.TarInputStream)1 ParseException (com.codename1.l10n.ParseException)1 EncodedImage (com.codename1.ui.EncodedImage)1 ActionListener (com.codename1.ui.events.ActionListener)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1