Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2007 The Android Open Source Project
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package android.test;
 
 import  com.google.android.collect.Sets;
 
 
 import java.io.File;
 import java.util.Set;

This is a class which delegates to the given context, but performs database and file operations with a renamed database/file name (prefixes default names with a given prefix).
 
 public class RenamingDelegatingContext extends ContextWrapper {
 
     private Context mFileContext;
     private String mFilePrefix = null;
     private File mCacheDir;
     private final Object mSync = new Object();
 
     private Set<StringmDatabaseNames = Sets.newHashSet();
     private Set<StringmFileNames = Sets.newHashSet();
 
     public static <T extends ContentProvider> T providerWithRenamedContext(
             Class<T> contentProviderContext cString filePrefix)
             throws IllegalAccessExceptionInstantiationException {
         return providerWithRenamedContext(contentProvidercfilePrefixfalse);
     }
 
     public static <T extends ContentProvider> T providerWithRenamedContext(
             Class<T> contentProviderContext cString filePrefix,
             boolean allowAccessToExistingFilesAndDbs)
             throws IllegalAccessExceptionInstantiationException {
         Class<T> mProviderClass = contentProvider;
         T mProvider = mProviderClass.newInstance();
         RenamingDelegatingContext mContext = new RenamingDelegatingContext(cfilePrefix);
         if (allowAccessToExistingFilesAndDbs) {
             mContext.makeExistingFilesAndDbsAccessible();
         }
         mProvider.attachInfo(mContextnull);
         return mProvider;
     }

    
Makes accessible all files and databases whose names match the filePrefix that was passed to the constructor. Normally only files and databases that were created through this context are accessible.
 
     public void makeExistingFilesAndDbsAccessible() {
         String[] databaseList = .databaseList();
         for (String diskName : databaseList) {
             if (shouldDiskNameBeVisible(diskName)) {
                 .add(publicNameFromDiskName(diskName));
             }
         }
         String[] fileList = .fileList();
         for (String diskName : fileList) {
             if (shouldDiskNameBeVisible(diskName)) {
                 .add(publicNameFromDiskName(diskName));
             }
         }
     }

    
Returns if the given diskName starts with the given prefix or not.

Parameters:
diskName name of the database/file.
 
     boolean shouldDiskNameBeVisible(String diskName) {
         return diskName.startsWith();
     }

    
Returns the public name (everything following the prefix) of the given diskName.

Parameters:
diskName name of the database/file.
    String publicNameFromDiskName(String diskName) {
        if (!shouldDiskNameBeVisible(diskName)) {
            throw new IllegalArgumentException("disk file should not be visible: " + diskName);
        }
        return diskName.substring(.length(), diskName.length());
    }

    

Parameters:
context : the context that will be delagated.
filePrefix : a prefix with which database and file names will be prefixed.
    public RenamingDelegatingContext(Context contextString filePrefix) {
        super(context);
         = context;
         = filePrefix;
    }

    

Parameters:
context : the context that will be delagated.
fileContext : the context that file and db methods will be delgated to
filePrefix : a prefix with which database and file names will be prefixed.
    public RenamingDelegatingContext(Context contextContext fileContextString filePrefix) {
        super(context);
         = fileContext;
         = filePrefix;
    }
    public String getDatabasePrefix() {
        return ;
    }
    private String renamedFileName(String name) {
        return  + name;
    }
    @Override
            int modeSQLiteDatabase.CursorFactory factory) {
        final String internalName = renamedFileName(name);
        if (!.contains(name)) {
            .add(name);
            .deleteDatabase(internalName);
        }
        return .openOrCreateDatabase(internalNamemodefactory);
    }
    @Override
    public boolean deleteDatabase(String name) {
        if (.contains(name)) {
            .remove(name);
            return .deleteDatabase(renamedFileName(name));
        } else {
            return false;
        }
    }
    
    @Override
    public File getDatabasePath(String name) {
        return .getDatabasePath(renamedFileName(name));
    }
    @Override
    public String[] databaseList() {
        return .toArray(new String[]{});
    }
    @Override
    public FileInputStream openFileInput(String name)
            throws FileNotFoundException {
        final String internalName = renamedFileName(name);
        if (.contains(name)) {
            return .openFileInput(internalName);
        } else {
            throw new FileNotFoundException(internalName);
        }
    }
    @Override
    public FileOutputStream openFileOutput(String nameint mode)
            throws FileNotFoundException {
        .add(name);
        return .openFileOutput(renamedFileName(name), mode);
    }
    @Override
    public File getFileStreamPath(String name) {
        return .getFileStreamPath(renamedFileName(name));
    }
    @Override
    public boolean deleteFile(String name) {
        if (.contains(name)) {
            .remove(name);
            return .deleteFile(renamedFileName(name));
        } else {
            return false;
        }
    }
    @Override
    public String[] fileList() {
        return .toArray(new String[]{});
    }
    
    
In order to support calls to getCacheDir(), we create a temp cache dir (inside the real one) and return it instead. This code is basically getCacheDir(), except it uses the real cache dir as the parent directory and creates a test cache dir inside that.
    @Override
    public File getCacheDir() {
        synchronized () {
            if ( == null) {
                 = new File(.getCacheDir(), renamedFileName("cache"));
            }
            if (!.exists()) {
                if(!.mkdirs()) {
                    Log.w("RenamingDelegatingContext""Unable to create cache directory");
                    return null;
                }
                FileUtils.setPermissions(
                        .getPath(),
                        .|.|.,
                        -1, -1);
            }
        }
        return ;
    }
//    /**
//     * Given an array of files returns only those whose names indicate that they belong to this
//     * context.
//     * @param allFiles the original list of files
//     * @return the pruned list of files
//     */
//    private String[] prunedFileList(String[] allFiles) {
//        List<String> files = Lists.newArrayList();
//        for (String file : allFiles) {
//            if (file.startsWith(mFilePrefix)) {
//                files.add(file);
//            }
//        }
//        return files.toArray(new String[]{});
//    }
New to GrepCode? Check out our FAQ X