Oracle by Example brandingGetting Started with Storage

Ready to get started?

This tutorial shows you how to develop an application that uploads data from a mobile device to a storage collection in Oracle Mobile Cloud, Enterprise (OMCe), and then downloads that data.

You'll start from one of your existing apps, and add the code that is required for it to communicate with an OMCe backend. For purposes of demonstration, the code uploads a plain text file called Upload001.txt that contains a simple line of text. After the file is uploaded, it's then downloaded and the contents are sent to the console log.

What you need

  • Either Android studio running JDK 7 or greater, or Xcode.
  • The SDK for your mobile platform, either Android SDK or iOS SDK.
  • Access to an OMCe instance.
  • A mobile app, either Android or iOS, that you want to add storage functionality to.

section 1Create a Role and a Test User

First, create a role with the name Technician, which you'll associate with the storage collection that you create later in the tutorial. You'll also need a test user that has the Technician role.

  1. Log in to your OMCe instance and click the Hamburger menu icon menu and in the navigation panel select Mobile Apps > Roles.
  2. Click the New Role button to open the New Role dialog.
  3. In the Role Name field, enter Technician and click Create.
  4. Contact the administrator of your OMCe instance and request that a new user be created and assigned the Technician role.

    The administrator can either create a new user, or assign your own user to the Technician role. The administrator uses the Identity Cloud Service (IDCS) tool to do this.


section 2Create the Backend

A mobile backend is the server-side companion to your mobile application. It provides secure access to services like storage, notifications, user management, and custom APIs.

  1. In the navigation panel, select Backends.
  2. Click the New Backend button.
  3. In the Name field, enter IncidentReports.
  4. In the Analytics section, select None.
  5. Click Create.
  6. Select Settings and copy the following information to a convenient location on your system. You'll use this information later in the tutorial.
    • Backend ID
    • Anonymous Key
    • Base URL

    Keep the backend open because you'll be using it in the next step.


section 3Create a Storage Collection

Now you'll create a storage collection and associate the Technician role with it. A storage collection contains documents, images, and other types of files. In this tutorial, you'll upload a simple text file and then download it.

  1. In the navigation panel of the backend, click Storage.
    The storage menu item.
    Description of the illustration omce-backend-storage.png
  2. Click New Collection.
  3. In the Collection Name field, enter Incident_Reports and click Create.
  4. In the Read-Write field, select the Technician role that you created in the previous step.

OMCe is now ready to interact with your app.


section 4Configure the App

Android

Now that OMCe is set up and ready for use, set up the app. We're assuming that the upload and download code is in a single file, and that in the file, you'll create an object with the following methods: authenticate, uploadText, and downloadText.

  1. Open your app project in Android Studio
  2. In the project, locate and open oracle_mobile_cloud_config.xml and replace the following items with the information that you copied earlier:
    • YOUR_MOBILE_BACKEND_NAME: In this case, the name is IncidentReports.
    • YOUR_BASE_URL: The Base URL that you copied earlier.
    • YOUR_MOBILE_BACKEND_ID: The Backend ID that you copied earlier.
    • YOUR_ANONYMOUS_KEY: The Anonymous Key that you copied earlier.

    Also make sure that the authentication type is basic, not oauth.

  3. In your app, in the Java file where your upload code is, make sure you have the following imports:
    import oracle.cloud.mobile.authorization.AuthType;
    import oracle.cloud.mobile.authorization.AuthorizationAgent;
    import oracle.cloud.mobile.authorization.AuthorizationCallback;
    import oracle.cloud.mobile.exception.ServiceProxyException;
    import oracle.cloud.mobile.mobilebackend.MobileBackend;
    import oracle.cloud.mobile.mobilebackend.MobileManager;
    import oracle.cloud.mobile.storage.Storage;
    import oracle.cloud.mobile.storage.StorageCollection;
    import oracle.cloud.mobile.storage.StorageObject;
    
  4. Add the following method, which does the authentication. The username and password are for the user that you set up earlier.
    private void authenticate() {
    
        try {
            MobileBackend mobileBackend = MobileManager.getManager().getMobileBackend(this);
            AuthorizationAgent mAuthorization = mobileBackend.getAuthorization(AuthType.BASIC_AUTH);
            mAuthorization.authenticate(this, "username", "password", mLoginCallback);
        } catch (ServiceProxyException e) {
            e.printStackTrace();
        }
    }
    

    The call to mAuthorization.authenticate takes four parameters, the last of which is a reference to a callback object. The system calls the onCompletion method of that object when the authentication process completes. You must supply the callback code, which you do in the next step.

  5. Add the callback definition in an instance variable. This is where you put your calls to the upload and download methods.
    AuthorizationCallback mLoginCallback = new AuthorizationCallback() {
        @Override
        public void onCompletion(ServiceProxyException e) {
            Log.d("AUTH", "OnCompletion Auth Callback");
            if (e == null) {
                Log.e("AUTH", "Authorization successful");
                String fileID = uploadText("Customer_Images","Upload001.txt","Hi there!","text/plain");
                downloadText("Incident_Reports", fileID);
            } else {
                Log.e("AUTH", "Exception while receiving the Access Token", e);
            }
        }
    };
  6. Now add the uploadText method. It returns the ID of the file that it uploads so that you can save it in a variable and download the same file later. The ID is created by the OMCe storage collection, which allows more than one file with the same name and content to exist in the collection.
    private String uploadText(String collectionID, // the ID of storage collection, "Incident_Reports" for eg.
                              String displayName, // the text that's displayed in the OMCe interface
                              String payload, // the content
                              String contentType) // the MIME type, "text/plain" for eg.
    {
        StorageObject returnedInfo = null;
        try {
            Storage storage = MobileManager.getManager().getMobileBackend(this).getServiceProxy(Storage.class);
            StorageCollection collection = storage.getStorageCollection(collectionID);
            StorageObject textObject = new StorageObject(null);
            textObject.setDisplayName(displayName);
            textObject.setPayload(payload.getBytes(), contentType);
            StorageObject returnedInfo = collection.post(textObject);
            Log.d("APP1 UPLOAD", "ID = " + returnedInfo.getID());
            return returnedInfo.getID();
         } catch(Exception e) {
            e.printStackTrace();
            return "Upload Failed";
        }
    }
  7. The following method downloads the file from the collection.
    private void downloadText(String collectionName, String fileID) {
            try {
                Log.d("APP1 DOWNLOAD","Attempting to download " + fileID);
                Storage mStorage = MobileManager.getManager().getDefaultMobileBackend(this).getServiceProxy(Storage.class);
                StorageCollection collection = mStorage.getStorageCollection(collectionName);
                StorageObject object = collection.get(fileID);
                InputStream payload = object.getPayloadStream();
                String text = getStringFromInputStream(payload);
                Log.d("APP1 DOWNLOAD", text);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    

The sample code here showed you how to connect to a collection, upload some data, and how to download that data. For more information about working with mobile apps in OMCe, see the Want to Learn More? section on this page.

iOS

We're assuming that the upload and download code is in a single file, and that in the file, you'll create an object with the following methods: authenticate, uploadText, and downloadText.

  1. Open you app project in XCode.
  2. In the project, locate and open OMC.plist and update the following keys with the information that you copied earlier:
    • name: In this case, the name is IncidentReports.
    • baseURL: The Base URL that you copied earlier.
    • mobileBackendID: The Backend ID that you copied earlier.
    • anonymousKey: The Anonymous Key that you copied earlier.
    • Also make sure that the authentication type is basic, not oauth.

  3. In your app, in the Objective C file where your upload and download code is, make sure that you have the following imports:
    #import "OMCStorage.h"
    #import "OMCMobileBackend+OMC_Storage.h"
    #import "OMCMobileBackend.h"
    #import "OMCStorageCollection.h"
    #import "OMCMobileManager.h"
    
  4. Add the following method, which does the authentication. The username and password are for the user that you set up earlier.
    -(void) authenticate:(NSString)txtUsername :(NSString)txtPassword {
    
        // Get authorization object
        OMCAuthorization *auth = mbe.authorization;
    
        // Authenticate with user's username/password
        NSError* error = [auth authenticate:txtUsername
                                   password:txtPassword];
    
        if ( !error ) {
        .
        .
        .
    
    }
    
  5. Now add the uploadText method. It returns the ID of the file that it uploads so that you can save it in a variable and download the same file later. The ID is created by the OMCe storage collection, which allows more than one file with the same name and content to exist in the collection.
    - (NSString*) uploadText: (NSString*) collectionId :(NSString*) payload :(NSString*) contentType {
    
        // Get storage object
        OMCMobileBackend* mbe = [[OMCMobileManager sharedManager] mobileBackend]
        OMCStorage* storage = [mbe storage];
    
        // Get collection where you want to upload new data
        OMCStorageCollection* aCollection = [storage getCollection:collectionId];
    
        // Create new data from payload
        NSData* payloadData = [payload dataUsingEncoding:NSUTF8StringEncoding];
        OMCStorageObject* aObject = [[OMCStorageObject alloc] setPayloadFromData:payloadData
                                                                 withContentType:contentType];
    
        // Post data to collection
        OMCStorageObject* bObject = [aCollection post:aObject];
    
        // Return the file ID that was assigned by the server
        return [bObject ID];
    }
    
  6. The following method downloads the file from the collection. The collectionId parameter is the name that you gave to the collection that you created in Step 3, which in this case is Incident_Reports.
    - (NSString*) downloadText: (NSString*) collectionId :(NSString*) fileId {
    
         // Get storage object
        OMCMobileBackend* mbe = [[OMCMobileManager sharedManager] mobileBackend]
        OMCStorage* storage = [mbe storage];
    
        // Get collection where you want to upload new data
        OMCStorageCollection* aCollection = [storage getCollection:collectionId];
    
        // Get the file object from the collection
        OMCStorageObject* aObject = [aCollection get:fileId];
    
        // Get the payload data
        NSData* data = [aObject getPayloadData];
    
        // Convert the payload to a string
        NSString* text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
        // Return the string
        return text;
    }
    
  7. If you are targetting iOS 9.0 or higher, you need to account for the Application Transport Security (ATS) policy, which forces remote communications to be over HTTPS.

    For development purposes only, add the following key in the app's Info.plist file to turn off the ATS policy for the app:

    <key>NSAppTransportSecurity</key>
    <dict>
      <key>NSAllowsArbitraryLoads</key>
      <true/>
    </dict>

    Note: You shouldn't use this setting in production. To make sure you provide optimal security for your app, study Apple's documentation for NSAppTransportSecurity and follow Apple's recommendations for disabling ATS for specific domains and applying proper security reductions for those domains.

The sample code here showed you how to connect to a collection, upload some data, and how to download that data. For more information about working with mobile apps in OMCe, see the Want to Learn More? section on this page.


more informationWhat's next?

  • See Setting up Mobile Apps in the Oracle documentation, which includes authenticating in OMCe and setting up apps in Android, iOS, and Cordova.