Search in sources :

Example 76 with File

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

the class AndroidImplementation method installNotificationActionCategories.

/**
 * Action categories are defined on the Main class by implementing the PushActionsProvider, however
 * the main class may not be available to the push receiver, so we need to save these categories
 * to the file system when the app is installed, then the push receiver can load these actions
 * when it sends a push while the app isn't running.
 * @param provider A reference to the App's main class
 * @throws IOException
 */
public static void installNotificationActionCategories(PushActionsProvider provider) throws IOException {
    // Assume that CN1 is running... this will run when the app starts
    // up
    Context context = getContext();
    boolean requiresUpdate = false;
    File categoriesFile = new File(activity.getFilesDir().getAbsolutePath() + "/" + FILE_NAME_NOTIFICATION_CATEGORIES);
    if (!categoriesFile.exists()) {
        requiresUpdate = true;
    }
    if (!requiresUpdate) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getApplicationContext().getPackageName(), PackageManager.GET_PERMISSIONS);
            if (packageInfo.lastUpdateTime > categoriesFile.lastModified()) {
                requiresUpdate = true;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    if (!requiresUpdate) {
        return;
    }
    OutputStream os = getContext().openFileOutput(FILE_NAME_NOTIFICATION_CATEGORIES, 0);
    PushActionCategory[] categories = provider.getPushActionCategories();
    javax.xml.parsers.DocumentBuilderFactory docFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    javax.xml.parsers.DocumentBuilder docBuilder;
    try {
        docBuilder = docFactory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
        throw new IOException("Faield to create document builder for creating notification categories XML document", ex);
    }
    // root elements
    org.w3c.dom.Document doc = docBuilder.newDocument();
    org.w3c.dom.Element root = (org.w3c.dom.Element) doc.createElement("categories");
    doc.appendChild(root);
    for (PushActionCategory category : categories) {
        org.w3c.dom.Element categoryEl = (org.w3c.dom.Element) doc.createElement("category");
        org.w3c.dom.Attr idAttr = doc.createAttribute("id");
        idAttr.setValue(category.getId());
        categoryEl.setAttributeNode(idAttr);
        for (PushAction action : category.getActions()) {
            org.w3c.dom.Element actionEl = (org.w3c.dom.Element) doc.createElement("action");
            org.w3c.dom.Attr actionIdAttr = doc.createAttribute("id");
            actionIdAttr.setValue(action.getId());
            actionEl.setAttributeNode(actionIdAttr);
            org.w3c.dom.Attr actionTitleAttr = doc.createAttribute("title");
            if (action.getTitle() != null) {
                actionTitleAttr.setValue(action.getTitle());
            } else {
                actionTitleAttr.setValue(action.getId());
            }
            actionEl.setAttributeNode(actionTitleAttr);
            if (action.getIcon() != null) {
                org.w3c.dom.Attr actionIconAttr = doc.createAttribute("icon");
                String iconVal = action.getIcon();
                try {
                    // We'll store the resource IDs for the icon
                    // rather than the icon name because that is what
                    // the push notifications require.
                    iconVal = "" + context.getResources().getIdentifier(iconVal, "drawable", context.getPackageName());
                    actionIconAttr.setValue(iconVal);
                    actionEl.setAttributeNode(actionIconAttr);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (action.getTextInputPlaceholder() != null) {
                org.w3c.dom.Attr textInputPlaceholderAttr = doc.createAttribute("textInputPlaceholder");
                textInputPlaceholderAttr.setValue(action.getTextInputPlaceholder());
                actionEl.setAttributeNode(textInputPlaceholderAttr);
            }
            if (action.getTextInputButtonText() != null) {
                org.w3c.dom.Attr textInputButtonTextAttr = doc.createAttribute("textInputButtonText");
                textInputButtonTextAttr.setValue(action.getTextInputButtonText());
                actionEl.setAttributeNode(textInputButtonTextAttr);
            }
            categoryEl.appendChild(actionEl);
        }
        root.appendChild(categoryEl);
    }
    try {
        javax.xml.transform.TransformerFactory transformerFactory = javax.xml.transform.TransformerFactory.newInstance();
        javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
        javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource(doc);
        javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(os);
        transformer.transform(source, result);
    } catch (Exception ex) {
        throw new IOException("Failed to save notification categories as XML.", ex);
    }
}
Also used : BufferedOutputStream(com.codename1.io.BufferedOutputStream) FileOutputStream(java.io.FileOutputStream) OutputStream(java.io.OutputStream) Element(android.renderscript.Element) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) PushActionCategory(com.codename1.push.PushActionCategory) IOException(java.io.IOException) PushAction(com.codename1.push.PushAction) JSONException(org.json.JSONException) InvocationTargetException(java.lang.reflect.InvocationTargetException) RemoteException(android.os.RemoteException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) MediaException(com.codename1.media.AsyncMedia.MediaException) ParseException(java.text.ParseException) SAXException(org.xml.sax.SAXException) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 77 with File

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

the class AndroidImplementation method getAppArg.

@Override
public String getAppArg() {
    if (super.getAppArg() != null) {
        // behaviour the existed when AppArg was just another Display property.
        return super.getAppArg();
    }
    if (getActivity() == null) {
        return null;
    }
    android.content.Intent intent = getActivity().getIntent();
    if (intent != null) {
        String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
        intent.removeExtra(Intent.EXTRA_TEXT);
        Uri u = intent.getData();
        String scheme = intent.getScheme();
        if (u == null && intent.getExtras() != null) {
            if (intent.getExtras().keySet().contains("android.intent.extra.STREAM")) {
                try {
                    u = (Uri) intent.getParcelableExtra("android.intent.extra.STREAM");
                    scheme = u.getScheme();
                    System.out.println("u=" + u);
                } catch (Exception ex) {
                    Log.d("Codename One", "Failed to load parcelable extra from intent: " + ex.getMessage());
                }
            }
        }
        if (u != null) {
            // String scheme = intent.getScheme();
            intent.setData(null);
            if ("content".equals(scheme)) {
                try {
                    InputStream attachment = getActivity().getContentResolver().openInputStream(u);
                    if (attachment != null) {
                        String name = getContentName(getActivity().getContentResolver(), u);
                        if (name != null) {
                            String filePath = getAppHomePath() + getFileSystemSeparator() + name;
                            if (filePath.startsWith("file:")) {
                                filePath = filePath.substring(5);
                            }
                            File f = new File(filePath);
                            OutputStream tmp = createFileOuputStream(f);
                            byte[] buffer = new byte[1024];
                            int read = -1;
                            while ((read = attachment.read(buffer)) > -1) {
                                tmp.write(buffer, 0, read);
                            }
                            tmp.close();
                            attachment.close();
                            setAppArg(addFile(filePath));
                            return addFile(filePath);
                        }
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    return null;
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            } else {
                /*
                    // Why do we need this special case?  u.toString()
                    // will include the full URL including query string.
                    // This special case causes urls like myscheme://part1/part2
                    // to only return "/part2" which is obviously problematic and
                    // is inconsistent with iOS.  Is this special case necessary
                    // in some versions of Android?
                    String encodedPath = u.getEncodedPath();
                    if (encodedPath != null && encodedPath.length() > 0) {
                        String query = u.getQuery();
                        if(query != null && query.length() > 0){
                            encodedPath += "?" + query;
                        }
                        setAppArg(encodedPath);
                        return encodedPath;
                    }
                    */
                if (sharedText != null) {
                    setAppArg(sharedText);
                    return sharedText;
                } else {
                    setAppArg(u.toString());
                    return u.toString();
                }
            }
        } else if (sharedText != null) {
            setAppArg(sharedText);
            return sharedText;
        }
    }
    return null;
}
Also used : BufferedInputStream(com.codename1.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) BufferedOutputStream(com.codename1.io.BufferedOutputStream) FileOutputStream(java.io.FileOutputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) Uri(android.net.Uri) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) android.content(android.content) JSONException(org.json.JSONException) InvocationTargetException(java.lang.reflect.InvocationTargetException) RemoteException(android.os.RemoteException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) MediaException(com.codename1.media.AsyncMedia.MediaException) ParseException(java.text.ParseException) SAXException(org.xml.sax.SAXException) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Paint(android.graphics.Paint)

Example 78 with File

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

the class AndroidImplementation method fixAttachmentPath.

private String fixAttachmentPath(String attachment) {
    com.codename1.io.File cn1File = new com.codename1.io.File(attachment);
    File mediaStorageDir = new File(new File(getContext().getCacheDir(), "intent_files"), "Attachment");
    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(Display.getInstance().getProperty("AppName", "CodenameOne"), "failed to create directory");
            return null;
        }
    }
    File newFile = new File(mediaStorageDir.getPath() + File.separator + cn1File.getName());
    if (newFile.exists()) {
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        newFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + "_" + cn1File.getName());
    }
    // Uri fileUri = Uri.fromFile(newFile);
    newFile.getParentFile().mkdirs();
    // Uri imageUri = Uri.fromFile(newFile);
    Uri fileUri = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".provider", newFile);
    try {
        InputStream is = FileSystemStorage.getInstance().openInputStream(attachment);
        OutputStream os = new FileOutputStream(newFile);
        byte[] buf = new byte[1024];
        int len;
        while ((len = is.read(buf)) > -1) {
            os.write(buf, 0, len);
        }
        is.close();
        os.close();
    } catch (IOException ex) {
        Logger.getLogger(AndroidImplementation.class.getName()).log(Level.SEVERE, null, ex);
    }
    return fileUri.toString();
}
Also used : Audio(com.codename1.media.Audio) java.io(java.io) com.codename1.io(com.codename1.io) BufferedInputStream(com.codename1.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) BufferedOutputStream(com.codename1.io.BufferedOutputStream) FileOutputStream(java.io.FileOutputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) Uri(android.net.Uri) Date(java.util.Date) Paint(android.graphics.Paint) FileOutputStream(java.io.FileOutputStream) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat)

Example 79 with File

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

the class AndroidImplementation method createMedia.

/**
 * @inheritDoc
 */
@Override
public Media createMedia(InputStream stream, String mimeType, final Runnable onCompletion) throws IOException {
    if (getActivity() == null) {
        return null;
    }
    /*if(!checkForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, "This is required to play media")){
            return null;
        }*/
    boolean isVideo = mimeType.contains("video");
    if (!isVideo && stream instanceof FileInputStream) {
        MediaPlayer player = new MediaPlayer();
        player.setDataSource(((FileInputStream) stream).getFD());
        player.prepare();
        return new Audio(getActivity(), player, stream, onCompletion);
    }
    String extension = MimeTypeMap.getFileExtensionFromUrl(mimeType);
    final File temp = File.createTempFile("mtmp", extension == null ? "dat" : extension);
    temp.deleteOnExit();
    OutputStream out = createFileOuputStream(temp);
    byte[] buf = new byte[256];
    int len = 0;
    while ((len = stream.read(buf, 0, buf.length)) > -1) {
        out.write(buf, 0, len);
    }
    out.close();
    stream.close();
    final Runnable finish = new Runnable() {

        @Override
        public void run() {
            if (onCompletion != null) {
                Display.getInstance().callSerially(onCompletion);
                // makes sure the file is only deleted after the onCompletion was invoked
                Display.getInstance().callSerially(new Runnable() {

                    @Override
                    public void run() {
                        temp.delete();
                    }
                });
                return;
            }
            temp.delete();
        }
    };
    if (isVideo) {
        final AndroidImplementation.Video[] retVal = new AndroidImplementation.Video[1];
        final boolean[] flag = new boolean[1];
        getActivity().runOnUiThread(new Runnable() {

            @Override
            public void run() {
                VideoView v = new VideoView(getActivity());
                v.setZOrderMediaOverlay(true);
                v.setVideoURI(Uri.fromFile(temp));
                retVal[0] = new AndroidImplementation.Video(v, getActivity(), finish);
                flag[0] = true;
                synchronized (flag) {
                    flag.notify();
                }
            }
        });
        while (!flag[0]) {
            synchronized (flag) {
                try {
                    flag.wait(100);
                } catch (InterruptedException ex) {
                }
            }
        }
        return retVal[0];
    } else {
        return createMedia(createFileInputStream(temp), mimeType, finish);
    }
}
Also used : BufferedOutputStream(com.codename1.io.BufferedOutputStream) FileOutputStream(java.io.FileOutputStream) OutputStream(java.io.OutputStream) FileInputStream(java.io.FileInputStream) Paint(android.graphics.Paint) Audio(com.codename1.media.Audio) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) MediaPlayer(android.media.MediaPlayer)

Example 80 with File

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

the class GoogleImpl method nativeLoginImpl.

private void nativeLoginImpl(final GoogleApiClient client) {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(client);
    AndroidNativeUtil.startActivityForResult(signInIntent, RC_SIGN_IN, new IntentResultListener() {

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
            if (requestCode == RC_SIGN_IN) {
                final GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
                if (result.isSuccess()) {
                    // Signed in successfully, show authenticated UI.
                    GoogleSignInAccount acct = result.getSignInAccount();
                    String displayName = acct.getDisplayName();
                    String acctId = acct.getId();
                    String email = acct.getEmail();
                    String requestIdToken = acct.getIdToken();
                    Set<Scope> grantedScopes = acct.getGrantedScopes();
                    String code = acct.getServerAuthCode();
                    String scopeStr = scope;
                    System.out.println("Token is " + acct.getIdToken());
                    if (acct.getIdToken() == null && clientId != null && clientSecret != null) {
                        Log.p("Received null ID token even though clientId and clientSecret are set.");
                    }
                    // otherwise we'll set the token to null.
                    if (clientId != null && clientSecret != null && requestIdToken != null && code != null) {
                        ConnectionRequest req = new ConnectionRequest() {

                            @Override
                            protected void readResponse(InputStream input) throws IOException {
                                Map<String, Object> json = new JSONParser().parseJSON(new InputStreamReader(input, "UTF-8"));
                                if (json.containsKey("access_token")) {
                                    setAccessToken(new AccessToken((String) json.get("access_token"), (String) null));
                                    Display.getInstance().callSerially(new Runnable() {

                                        @Override
                                        public void run() {
                                            callback.loginSuccessful();
                                        }
                                    });
                                } else {
                                    setAccessToken(new AccessToken());
                                    Log.p("Failed to retrieve the access token from the google auth server.  Login succeeded, but access token is null, so you won't be able to use it to retrieve additional information.");
                                    Log.p("Response was " + json);
                                    Display.getInstance().callSerially(new Runnable() {

                                        @Override
                                        public void run() {
                                            callback.loginSuccessful();
                                        }
                                    });
                                }
                            }
                        };
                        req.setUrl("https://www.googleapis.com/oauth2/v4/token");
                        req.addArgument("grant_type", "authorization_code");
                        // req.addArgument("client_id", "555462747934-iujpd5saj4pjpibo7c6r9tbjfef22rh1.apps.googleusercontent.com");
                        req.addArgument("client_id", clientId);
                        // req.addArgument("client_secret", "650YqplrnAI0KXb9LMUnVNnx");
                        req.addArgument("client_secret", clientSecret);
                        req.addArgument("redirect_uri", "");
                        req.addArgument("code", code);
                        req.addArgument("id_token", requestIdToken);
                        req.setPost(true);
                        req.setReadResponseForErrors(true);
                        NetworkManager.getInstance().addToQueue(req);
                    } else {
                        setAccessToken(new AccessToken());
                        Log.p("The access token was set to null because one of clientId, clientSecret, requestIdToken, or auth were null");
                        Log.p("The login succeeded, but you won't be able to make any requests to Google's REST apis using the login token.");
                        Log.p("In order to obtain a token that can be used with Google's REST APIs, you need to set the clientId, and clientSecret of" + "the GoogleConnect instance to valid OAuth2.0 Client IDs for Web Clients.");
                        Log.p("See https://console.developers.google.com/apis/credentials");
                        Log.p("You can get the OAuth2.0 client ID for this project in your google-services.json file in the oauth_client section");
                        Display.getInstance().callSerially(new Runnable() {

                            @Override
                            public void run() {
                                callback.loginSuccessful();
                            }
                        });
                    }
                } else {
                    if (callback != null) {
                        if (callback != null) {
                            Display.getInstance().callSerially(new Runnable() {

                                @Override
                                public void run() {
                                    callback.loginFailed(GooglePlayServicesUtil.getErrorString(result.getStatus().getStatusCode()));
                                }
                            });
                        }
                    }
                }
            }
        }
    });
}
Also used : Set(java.util.Set) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Intent(android.content.Intent) IOException(java.io.IOException) GoogleSignInResult(com.google.android.gms.auth.api.signin.GoogleSignInResult) ConnectionRequest(com.codename1.io.ConnectionRequest) GoogleSignInAccount(com.google.android.gms.auth.api.signin.GoogleSignInAccount) IntentResultListener(com.codename1.impl.android.IntentResultListener) AccessToken(com.codename1.io.AccessToken) JSONParser(com.codename1.io.JSONParser) Map(java.util.Map)

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