Home | History | Annotate | Download | only in browser
      1 /*
      2  * Copyright (C) 2010 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 package com.android.browser;
     17 
     18 import java.net.MalformedURLException;
     19 
     20 import libcore.io.Base64;
     21 
     22 /**
     23  * Class extracts the mime type and data from a data uri.
     24  * A data URI is of the form:
     25  * <pre>
     26  * data:[&lt;MIME-type&gt;][;charset=&lt;encoding&gt;][;base64],&lt;data&gt;
     27  * </pre>
     28  */
     29 public class DataUri {
     30     private static final String DATA_URI_PREFIX = "data:";
     31     private static final String BASE_64_ENCODING = ";base64";
     32 
     33     private String mMimeType;
     34     private byte[] mData;
     35 
     36     public DataUri(String uri) throws MalformedURLException {
     37         if (!isDataUri(uri)) {
     38             throw new MalformedURLException("Not a data URI");
     39         }
     40 
     41         int commaIndex = uri.indexOf(',', DATA_URI_PREFIX.length());
     42         if (commaIndex < 0) {
     43             throw new MalformedURLException("Comma expected in data URI");
     44         }
     45         String contentType = uri.substring(DATA_URI_PREFIX.length(),
     46                 commaIndex);
     47         mData = uri.substring(commaIndex + 1).getBytes();
     48         if (contentType.contains(BASE_64_ENCODING)) {
     49             mData = Base64.decode(mData);
     50         }
     51         int semiIndex = contentType.indexOf(';');
     52         if (semiIndex > 0) {
     53             mMimeType = contentType.substring(0, semiIndex);
     54         } else {
     55             mMimeType = contentType;
     56         }
     57     }
     58 
     59     /**
     60      * Returns true if the text passed in appears to be a data URI.
     61      */
     62     public static boolean isDataUri(String text)
     63     {
     64         return text.startsWith(DATA_URI_PREFIX);
     65     }
     66 
     67     public String getMimeType() {
     68         return mMimeType;
     69     }
     70 
     71     public byte[] getData() {
     72         return mData;
     73     }
     74 }
     75