Search in sources :

Example 31 with File

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

the class InstallCn1libsMojo method mergeProjectAppendedProperties.

/**
 * Merges the lib's appended properties with the project properties. Does not persist to file system.
 * @param artifact
 * @return True if changes were made to the project properties.s
 * @throws IOException
 */
private boolean mergeProjectAppendedProperties(Artifact artifact) throws IOException {
    Properties projectProps = getProjectProperties();
    Properties libProps = getLibraryAppendedProperties(artifact);
    Properties merged = projectProps;
    // merged.putAll(projectProps);
    Enumeration keys = libProps.propertyNames();
    boolean changed = false;
    while (keys.hasMoreElements()) {
        String key = (String) keys.nextElement();
        if (!merged.containsKey(key)) {
            merged.put(key, libProps.getProperty(key));
            changed = true;
        } else {
            String val = merged.getProperty(key);
            String libval = libProps.getProperty(key);
            if (!val.contains(libval)) {
                // append libval to the property
                merged.put(key, val + libval);
                changed = true;
            }
        }
    }
    return changed;
}
Also used : Enumeration(java.util.Enumeration) Properties(java.util.Properties) SortedProperties(com.codename1.ant.SortedProperties)

Example 32 with File

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

the class InstallCn1libsMojo method getLibraryRequiredProperties.

/**
 * Required properties for library.
 * @param artifact
 * @return
 * @throws IOException
 */
private SortedProperties getLibraryRequiredProperties(Artifact artifact) throws IOException {
    SortedProperties out = new SortedProperties();
    File file = getLibraryRequiredPropertiesFile(artifact);
    if (file.exists()) {
        try (FileInputStream fis = new FileInputStream(file)) {
            out.load(fis);
        }
    }
    return out;
}
Also used : SortedProperties(com.codename1.ant.SortedProperties) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 33 with File

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

the class HTTPUtil method update.

public static boolean update(URL u, File destFile, File tempDir, boolean requireHttps, boolean requireFingerprintMatch, boolean forceCheck) throws IOException, HttpsRequiredException, FingerprintChangedException {
    if (destFile.exists() && "github.com".equals(u.getHost()) && u.getPath().contains("/releases/download/")) {
        logger.fine("Github release assets should not require updating.");
        return false;
    }
    if (!forceCheck && getExpiryDate(destFile) > System.currentTimeMillis()) {
        return false;
    }
    File etagFile = new File(destFile.getParentFile(), destFile.getName() + ".etag");
    if (destFile.exists() && etagFile.exists()) {
        String etag;
        try (InputStream is = new FileInputStream(etagFile)) {
            etag = readToString(is).trim();
        }
        DownloadResponse resp = new DownloadResponse();
        if (doesETagMatch(resp, u, etag)) {
            saveExpires(resp, destFile);
            return false;
        }
        saveExpires(resp, destFile);
    }
    File sha1File = new File(destFile.getParentFile(), destFile.getName() + ".sha1");
    File tempFile = File.createTempFile(destFile.getName(), "progress", tempDir);
    Fingerprints.clear();
    DownloadResponse resp = new DownloadResponse();
    download(resp, u, tempFile, requireHttps);
    if (u.getProtocol() == "https") {
        String newFingerprint = Fingerprints.get(u.getHost());
        if (newFingerprint != null) {
            if (requireFingerprintMatch && sha1File.exists()) {
                String lastFingerprint = FileUtil.readFileToString(sha1File).trim();
                if (!lastFingerprint.equals(newFingerprint)) {
                    throw new FingerprintChangedException(u, destFile);
                }
            } else {
                if (sha1File.exists()) {
                    String existingFingerprint = FileUtil.readFileToString(sha1File).trim();
                    if (!existingFingerprint.equals(newFingerprint)) {
                        FileUtil.writeStringToFile(newFingerprint, sha1File);
                    }
                } else {
                    FileUtil.writeStringToFile(newFingerprint, sha1File);
                }
            }
        } else {
            if (requireFingerprintMatch) {
                throw new FingerprintChangedException(u, destFile);
            }
        }
    }
    String etag0 = ETags.get(u.toString());
    if (etag0 != null) {
        FileUtil.writeStringToFile(etag0, new File(destFile.getParentFile(), destFile.getName() + ".etag"));
    }
    saveExpires(resp, destFile);
    FileUtil.writeStringToFile(u.toString(), new File(destFile.getParentFile(), destFile.getName() + ".src"));
    Files.move(tempFile.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    return true;
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOUtil.readToString(com.codename1.samples.IOUtil.readToString) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 34 with File

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

the class HTTPUtil method download.

public static File download(DownloadResponse resp, URL u, File f, boolean requireHttps) throws IOException, HttpsRequiredException {
    URLConnection conn = u.openConnection();
    if (Boolean.getBoolean("client4j.disableHttpCache")) {
        conn.setUseCaches(false);
    }
    if (conn instanceof HttpURLConnection) {
        HttpURLConnection http = (HttpURLConnection) conn;
        http.setInstanceFollowRedirects(true);
        if (resp != null) {
            resp.setConnection(http);
        }
        int responseCode = http.getResponseCode();
        if (responseCode < 200 && responseCode >= 300) {
            throw new IOException("Failed to downlod url " + u + " to file " + f + ".  HTTP response code was " + responseCode + " and response message was " + http.getResponseMessage());
        }
        String etag = http.getHeaderField("ETag");
        if (etag != null) {
            ETags.add(u.toString(), etag);
        }
    }
    if (conn instanceof HttpsURLConnection) {
        try {
            Certificate cert = ((HttpsURLConnection) conn).getServerCertificates()[0];
            if (cert instanceof X509Certificate) {
                try {
                    String newFingerprint = getSHA1Fingerprint((X509Certificate) cert).trim();
                    Fingerprints.add(u.getHost(), newFingerprint);
                } catch (CertificateEncodingException ex) {
                    Logger.getLogger(HTTPUtil.class.getName()).log(Level.SEVERE, null, ex);
                    throw new IOException(ex);
                }
            } else {
                throw new IOException("Unsupported certificate type: " + cert.getClass().getName());
            }
        } catch (SSLPeerUnverifiedException ex) {
            throw new IOException(ex);
        }
    } else if (requireHttps) {
        throw new HttpsRequiredException(u, f);
    }
    try (InputStream input = conn.getInputStream()) {
        try (FileOutputStream output = new FileOutputStream(f)) {
            byte[] buf = new byte[128 * 1024];
            long total = conn.getContentLengthLong();
            long read = 0l;
            int len;
            while ((len = input.read(buf)) >= 0) {
                read += len;
                output.write(buf, 0, len);
                updateProgress(u, read, total);
            }
        }
    }
    return f;
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) IOUtil.readToString(com.codename1.samples.IOUtil.readToString) HttpURLConnection(java.net.HttpURLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) URLConnection(java.net.URLConnection) CertificateUtil.getSHA1Fingerprint(com.codename1.samples.CertificateUtil.getSHA1Fingerprint) X509Certificate(java.security.cert.X509Certificate) HttpURLConnection(java.net.HttpURLConnection) FileOutputStream(java.io.FileOutputStream) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 35 with File

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

the class Capture method capturePhoto.

/**
 * <p>Invokes the camera and takes a photo synchronously while blocking the EDT, the sample below
 * demonstrates a simple usage and applying a mask to the result</p>
 * <script src="https://gist.github.com/codenameone/b18c37dfcc7de752e0e6.js"></script>
 * <img src="https://www.codenameone.com/img/developer-guide/graphics-image-masking.png" alt="Picture after the capture was complete and the resulted image was rounded. The background was set to red so the rounding effect will be more noticeable" />
 *
 * @param width the target width for the image if possible, some platforms don't support scaling. To maintain aspect ratio set to -1
 * @param height the target height for the image if possible, some platforms don't support scaling. To maintain aspect ratio set to -1
 * @return the photo file location or null if the user canceled
 */
public static String capturePhoto(int width, int height) {
    CallBack c = new CallBack();
    if ("ios".equals(Display.getInstance().getPlatformName()) && (width != -1 || height != -1)) {
        // workaround for threading issues in iOS https://github.com/codenameone/CodenameOne/issues/2246
        capturePhoto(c);
        Display.getInstance().invokeAndBlock(c);
        if (c.url == null) {
            return null;
        }
        ImageIO scale = Display.getInstance().getImageIO();
        if (scale != null) {
            try {
                String path = c.url.substring(0, c.url.indexOf(".")) + "s" + c.url.substring(c.url.indexOf("."));
                OutputStream os = FileSystemStorage.getInstance().openOutputStream(path);
                scale.save(c.url, os, ImageIO.FORMAT_JPEG, width, height, 1);
                Util.cleanup(os);
                FileSystemStorage.getInstance().delete(c.url);
                return path;
            } catch (IOException ex) {
                Log.e(ex);
            }
        }
    } else {
        c.targetWidth = width;
        c.targetHeight = height;
        capturePhoto(c);
        Display.getInstance().invokeAndBlock(c);
    }
    return c.url;
}
Also used : OutputStream(java.io.OutputStream) IOException(java.io.IOException) ImageIO(com.codename1.ui.util.ImageIO)

Aggregations

IOException (java.io.IOException)76 File (java.io.File)61 FileInputStream (java.io.FileInputStream)43 InputStream (java.io.InputStream)33 EncodedImage (com.codename1.ui.EncodedImage)23 FileOutputStream (java.io.FileOutputStream)23 OutputStream (java.io.OutputStream)22 SortedProperties (com.codename1.ant.SortedProperties)18 FileSystemStorage (com.codename1.io.FileSystemStorage)17 BufferedInputStream (com.codename1.io.BufferedInputStream)15 Image (com.codename1.ui.Image)15 ByteArrayInputStream (java.io.ByteArrayInputStream)15 ActionEvent (com.codename1.ui.events.ActionEvent)14 RandomAccessFile (java.io.RandomAccessFile)14 ArrayList (java.util.ArrayList)14 EditableResources (com.codename1.ui.util.EditableResources)13 InvocationTargetException (java.lang.reflect.InvocationTargetException)13 Properties (java.util.Properties)12 File (com.codename1.io.File)11 BufferedImage (java.awt.image.BufferedImage)11