com.android.annotations.VisibleForTesting Java Examples

The following examples show how to use com.android.annotations.VisibleForTesting. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UpdaterData.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the {@link SdkManager} and the {@link AvdManager}.
 * Extracted so that we can override this in unit tests.
 */
@VisibleForTesting(visibility=Visibility.PRIVATE)
protected void initSdk() {
    setSdkManager(SdkManager.createManager(mOsSdkRoot, mSdkLog));
    try {
      mAvdManager = null;
      mAvdManager = AvdManager.getInstance(mSdkManager.getLocalSdk(), mSdkLog);
    } catch (AndroidLocationException e) {
        mSdkLog.error(e, "Unable to read AVDs: " + e.getMessage());  //$NON-NLS-1$

        // Note: we used to continue here, but the thing is that
        // mAvdManager==null so nothing is really going to work as
        // expected. Let's just display an error later in checkIfInitFailed()
        // and abort right there. This step is just too early in the SWT
        // setup process to display a message box yet.

        mAvdManagerInitError = e;
    }

    // notify listeners.
    broadcastOnSdkReload();
}
 
Example #2
Source File: AddonsListFetcher.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Takes an XML document as a string as parameter and returns a DOM for it.
 *
 * On error, returns null and prints a (hopefully) useful message on the monitor.
 */
@VisibleForTesting(visibility=Visibility.PRIVATE)
protected Document getDocument(InputStream xml, ITaskMonitor monitor) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);
        factory.setNamespaceAware(true);

        DocumentBuilder builder = factory.newDocumentBuilder();
        assert xml.markSupported();
        xml.reset();
        Document doc = builder.parse(new InputSource(xml));

        return doc;
    } catch (ParserConfigurationException e) {
        monitor.logError("Failed to create XML document builder");

    } catch (SAXException e) {
        monitor.logError("Failed to parse XML document");

    } catch (IOException e) {
        monitor.logError("Failed to read XML document");
    }

    return null;
}
 
Example #3
Source File: PlatformToolPackage.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting(visibility=Visibility.PRIVATE)
protected PlatformToolPackage(
            SdkSource source,
            Properties props,
            int revision,
            String license,
            String description,
            String descUrl,
            String archiveOsPath) {
    super(source,
            props,
            revision,
            license,
            description,
            descUrl,
            archiveOsPath);

    mPkgDesc = PkgDesc.Builder
            .newPlatformTool(getRevision())
            .setDescriptions(this)
            .create();
}
 
Example #4
Source File: UpdaterData.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Initializes the {@link SettingsController}
 * Extracted so that we can override this in unit tests.
 */
@VisibleForTesting(visibility=Visibility.PRIVATE)
protected SettingsController initSettingsController() {
    SettingsController settingsController = new SettingsController(mSdkLog);
    settingsController.registerOnChangedListener(new OnChangedListener() {
        @Override
        public void onSettingsChanged(
                SettingsController controller,
                SettingsController.Settings oldSettings) {

            // Reset the download cache if it doesn't match the right strategy.
            // The cache instance gets lazily recreated later in getDownloadCache().
            if (mDownloadCache != null) {
                if (controller.getSettings().getUseDownloadCache() &&
                        mDownloadCache.getStrategy() != DownloadCache.Strategy.FRESH_CACHE) {
                    mDownloadCache = null;
                } else if (!controller.getSettings().getUseDownloadCache() &&
                        mDownloadCache.getStrategy() != DownloadCache.Strategy.DIRECT) {
                    mDownloadCache = null;
                }
            }
        }
    });
    return settingsController;
}
 
Example #5
Source File: SdkSource.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Takes an XML document as a string as parameter and returns a DOM for it.
 *
 * On error, returns null and prints a (hopefully) useful message on the monitor.
 */
@VisibleForTesting(visibility=Visibility.PRIVATE)
protected Document getDocument(InputStream xml, ITaskMonitor monitor) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);
        factory.setNamespaceAware(true);

        DocumentBuilder builder = factory.newDocumentBuilder();
        assert xml.markSupported();
        xml.reset();
        Document doc = builder.parse(new InputSource(xml));

        return doc;
    } catch (ParserConfigurationException e) {
        monitor.logError("Failed to create XML document builder");

    } catch (SAXException e) {
        monitor.logError("Failed to parse XML document");

    } catch (IOException e) {
        monitor.logError("Failed to read XML document");
    }

    return null;
}
 
Example #6
Source File: UpdaterData.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the {@link SettingsController}
 * Extracted so that we can override this in unit tests.
 */
@VisibleForTesting(visibility=Visibility.PRIVATE)
protected SettingsController initSettingsController() {
    SettingsController settingsController = new SettingsController(mSdkLog);
    settingsController.registerOnChangedListener(new OnChangedListener() {
        @Override
        public void onSettingsChanged(
                SettingsController controller,
                SettingsController.Settings oldSettings) {

            // Reset the download cache if it doesn't match the right strategy.
            // The cache instance gets lazily recreated later in getDownloadCache().
            if (mDownloadCache != null) {
                if (controller.getSettings().getUseDownloadCache() &&
                        mDownloadCache.getStrategy() != DownloadCache.Strategy.FRESH_CACHE) {
                    mDownloadCache = null;
                } else if (!controller.getSettings().getUseDownloadCache() &&
                        mDownloadCache.getStrategy() != DownloadCache.Strategy.DIRECT) {
                    mDownloadCache = null;
                }
            }
        }
    });
    return settingsController;
}
 
Example #7
Source File: LayoutInflationDetector.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@VisibleForTesting
static boolean hasLayoutParams(@NonNull Reader reader)
        throws XmlPullParserException, IOException {
    KXmlParser parser = new KXmlParser();
    parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
    parser.setInput(reader);

    while (true) {
        int event = parser.next();
        if (event == XmlPullParser.START_TAG) {
            for (int i = 0; i < parser.getAttributeCount(); i++) {
                if (parser.getAttributeName(i).startsWith(ATTR_LAYOUT_RESOURCE_PREFIX)) {
                    String prefix = parser.getAttributePrefix(i);
                    if (prefix != null && !prefix.isEmpty() &&
                            ANDROID_URI.equals(parser.getNamespace(prefix))) {
                        return true;
                    }
                }
            }

            return false;
        } else if (event == XmlPullParser.END_DOCUMENT) {
            return false;
        }
    }
}
 
Example #8
Source File: SdkSource.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Takes an XML document as a string as parameter and returns a DOM for it.
 *
 * On error, returns null and prints a (hopefully) useful message on the monitor.
 */
@VisibleForTesting(visibility=Visibility.PRIVATE)
protected Document getDocument(InputStream xml, ITaskMonitor monitor) {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);
        factory.setNamespaceAware(true);

        DocumentBuilder builder = factory.newDocumentBuilder();
        assert xml.markSupported();
        xml.reset();
        Document doc = builder.parse(new InputSource(xml));

        return doc;
    } catch (ParserConfigurationException e) {
        monitor.logError("Failed to create XML document builder");

    } catch (SAXException e) {
        monitor.logError("Failed to parse XML document");

    } catch (IOException e) {
        monitor.logError("Failed to read XML document");
    }

    return null;
}
 
Example #9
Source File: BuildToolPackage.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting(visibility=Visibility.PRIVATE)
protected BuildToolPackage(
            SdkSource source,
            Properties props,
            int revision,
            String license,
            String description,
            String descUrl,
            String archiveOsPath) {
    super(source,
            props,
            revision,
            license,
            description,
            descUrl,
            archiveOsPath);

    mPkgDesc = PkgDesc.Builder
            .newBuildTool(getRevision())
            .setDescriptions(this)
            .create();
}
 
Example #10
Source File: BuildToolPackage.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@VisibleForTesting(visibility=Visibility.PRIVATE)
protected BuildToolPackage(
            SdkSource source,
            Properties props,
            int revision,
            String license,
            String description,
            String descUrl,
            String archiveOsPath) {
    super(source,
            props,
            revision,
            license,
            description,
            descUrl,
            archiveOsPath);

    mPkgDesc = setDescriptions(PkgDesc.Builder.newBuildTool(getRevision())).create();
}
 
Example #11
Source File: PlatformPackage.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting(visibility=Visibility.PRIVATE)
protected PlatformPackage(@Nullable SdkSource source,
                          @NonNull IAndroidTarget target,
                          @Nullable Properties props) {
    super(  source,                     //source
            props,                      //properties
            target.getRevision(),       //revision
            null,                       //license
            target.getDescription(),    //description
            null,                       //descUrl
            target.getLocation()        //archiveOsPath
            );

    mVersion = target.getVersion();
    mVersionName  = target.getVersionName();
    mLayoutlibVersion = new LayoutlibVersionMixin(props);
    mIncludedAbi = props == null ? null : props.getProperty(PkgProps.PLATFORM_INCLUDED_ABI);

    mPkgDesc = PkgDesc.Builder
            .newPlatform(mVersion,
                         (MajorRevision) getRevision(),
                         getMinToolsRevision())
            .setDescriptions(this)
            .create();
}
 
Example #12
Source File: ValueXmlHelper.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if the character at the given offset in the string is escaped
 * (the previous character is a \, and that character isn't itself an escaped \)
 *
 * @param s the string
 * @param index the index of the character in the string to check
 * @return true if the character is escaped
 */
@VisibleForTesting
static boolean isEscaped(String s, int index) {
    if (index == 0 || index == s.length()) {
        return false;
    }
    int prevPos = index - 1;
    char prev = s.charAt(prevPos);
    if (prev != '\\') {
        return false;
    }
    // The character *may* be escaped; not sure if the \ we ran into is
    // an escape character, or an escaped backslash; we have to search backwards
    // to be certain.
    int j = prevPos - 1;
    while (j >= 0) {
        if (s.charAt(j) != '\\') {
            break;
        }
        j--;
    }
    // If we passed an odd number of \'s, the space is escaped
    return (prevPos - j) % 2 == 1;
}
 
Example #13
Source File: MergerXmlUtils.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Parses the given XML string as a DOM document.
 * The parser does not validate the DTD nor any kind of schema.
 * It is namespace aware.
 *
 * @param xml The XML string to parse. Must not be null.
 * @param log An {@link ILogger} for reporting errors. Must not be null.
 * @return A new DOM {@link Document}, or null.
 */
@VisibleForTesting
@Nullable
static Document parseDocument(@NonNull String xml,
        @NonNull IMergerLog log,
        @NonNull FileAndLine errorContext) {
    try {
        Document doc = XmlUtils.parseDocument(xml, true);
        findLineNumbers(doc, 1);
        if (errorContext.getFileName() != null) {
            setSource(doc, new File(errorContext.getFileName()));
        }
        return doc;
    } catch (Exception e) {
        log.error(Severity.ERROR, errorContext, "Failed to parse XML string");
    }

    return null;
}
 
Example #14
Source File: Merger.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@VisibleForTesting
protected File checkPath(String path) throws FileNotFoundException {
    File file = new File(path);
    if (!file.exists()) {
        System.err.println(path + " does not exist");
        throw new FileNotFoundException(path);
    }
    return file;
}
 
Example #15
Source File: Device.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE)
static String getScreenRecorderCommand(@NonNull String remoteFilePath,
        @NonNull ScreenRecorderOptions options) {
    StringBuilder sb = new StringBuilder();

    sb.append("screenrecord");
    sb.append(' ');

    if (options.width > 0 && options.height > 0) {
        sb.append("--size ");
        sb.append(options.width);
        sb.append('x');
        sb.append(options.height);
        sb.append(' ');
    }

    if (options.bitrateMbps > 0) {
        sb.append("--bit-rate ");
        sb.append(options.bitrateMbps * 1000000);
        sb.append(' ');
    }

    if (options.timeLimit > 0) {
        sb.append("--time-limit ");
        long seconds = TimeUnit.SECONDS.convert(options.timeLimit, options.timeLimitUnits);
        if (seconds > 180) {
            seconds = 180;
        }
        sb.append(seconds);
        sb.append(' ');
    }

    sb.append(remoteFilePath);

    return sb.toString();
}
 
Example #16
Source File: Merger.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
protected File checkPath(String path) throws FileNotFoundException {
    File file = new File(path);
    if (!file.exists()) {
        System.err.println(path + " does not exist");
        throw new FileNotFoundException(path);
    }
    return file;
}
 
Example #17
Source File: SourcePackage.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@VisibleForTesting(visibility=Visibility.PRIVATE)
protected SourcePackage(
        AndroidVersion platformVersion,
        int revision,
        Properties props,
        String localOsPath) {
    this(null /*source*/, platformVersion, revision, props, localOsPath);
}
 
Example #18
Source File: Archive.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a new local archive.
 * This is typically called when inflating a local-package info by reading a local
 * source.properties file. In this case a few properties like the URL, checksum and
 * size are not defined.
 *
 * @param pkg The package that contains this archive. Cannot be null.
 * @param props A set of properties. Can be null.
 * @param localOsPath The OS path where the archive is installed if this represents a
 *            local package. Null for a remote package.
 */
@VisibleForTesting(visibility=Visibility.PACKAGE)
public Archive(@NonNull Package pkg,
               @Nullable Properties props,
               @Nullable String localOsPath) {
    mPackage = pkg;
    mArchFilter = new ArchFilter(props);
    mUrl = null;
    mLocalOsPath = localOsPath;
    mSize = 0;
    mChecksum = "";
    mIsLocal = localOsPath != null;
}
 
Example #19
Source File: ToolPackage.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting(visibility=Visibility.PRIVATE)
protected ToolPackage(
            SdkSource source,
            Properties props,
            int revision,
            String license,
            String description,
            String descUrl,
            String archiveOsPath) {
    super(source,
            props,
            revision,
            license,
            description,
            descUrl,
            archiveOsPath);

    // Setup min-platform-tool
    String revStr = getProperty(props, PkgProps.MIN_PLATFORM_TOOLS_REV, null);

    FullRevision rev = MIN_PLATFORM_TOOLS_REV_INVALID;
    if (revStr != null) {
        try {
            rev = FullRevision.parseRevision(revStr);
        } catch (NumberFormatException ignore) {}
    }

    mMinPlatformToolsRevision = rev;

    mPkgDesc = PkgDesc.Builder
            .newTool(getRevision(),
                     mMinPlatformToolsRevision)
            .setDescriptions(this)
            .create();
}
 
Example #20
Source File: MergingReport.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@VisibleForTesting
Builder addMessage(@NonNull SourceFile sourceFile,
        int line,
        int column,
        @NonNull Record.Severity severity,
        @NonNull String message) {
    // The line and column used are 1-based, but SourcePosition uses zero-based.
    return addMessage(
            new SourceFilePosition(sourceFile, new SourcePosition(line - 1, column -1, -1)),
            severity,
            message);
}
 
Example #21
Source File: ToolPackage.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@VisibleForTesting(visibility=Visibility.PRIVATE)
protected ToolPackage(
            SdkSource source,
            Properties props,
            int revision,
            String license,
            String description,
            String descUrl,
            String archiveOsPath) {
    super(source,
            props,
            revision,
            license,
            description,
            descUrl,
            archiveOsPath);

    // Setup min-platform-tool
    String revStr = getProperty(props, PkgProps.MIN_PLATFORM_TOOLS_REV, null);

    FullRevision rev = MIN_PLATFORM_TOOLS_REV_INVALID;
    if (revStr != null) {
        try {
            rev = FullRevision.parseRevision(revStr);
        } catch (NumberFormatException ignore) {}
    }

    mMinPlatformToolsRevision = rev;

    mPkgDesc = setDescriptions(PkgDesc.Builder
            .newTool(getRevision(), mMinPlatformToolsRevision))
            .create();
}
 
Example #22
Source File: ApiDatabase.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Drop generic type variables from a class name
 */
@VisibleForTesting
static String getRawClass(@NonNull String name) {
    int index = name.indexOf('<');
    if (index != -1) {
        int end = name.indexOf('>', index + 1);
        if (end == -1 || end == name.length() - 1) {
            return name.substring(0, index);
        } else {
            // e.g. test.pkg.ArrayAdapter<T>.Inner
            return name.substring(0, index) + name.substring(end + 1);
        }
    }
    return name;
}
 
Example #23
Source File: ResourceUsageAnalyzer.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@VisibleForTesting
String dumpResourceModel() {
    StringBuilder sb = new StringBuilder(1000);
    Collections.sort(mResources, new Comparator<Resource>() {
        @Override
        public int compare(Resource resource1,
                Resource resource2) {
            int delta = resource1.type.compareTo(resource2.type);
            if (delta != 0) {
                return delta;
            }
            return resource1.name.compareTo(resource2.name);
        }
    });

    for (Resource resource : mResources) {
        sb.append(resource.getUrl()).append(" : reachable=").append(resource.reachable);
        sb.append("\n");
        if (resource.references != null) {
            for (Resource referenced : resource.references) {
                sb.append("    ");
                sb.append(referenced.getUrl());
                sb.append("\n");
            }
        }
    }

    return sb.toString();
}
 
Example #24
Source File: CreatingCache.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Queries the cache for a given key. If the value is not present, this blocks until it is.
 *
 * This version allows for a listener that is notified when the state of the query is known.
 * This allows knowing the state while the method is blocked waiting for creation of the value
 * in this thread or another. This is used for testing.
 *
 * @param key the given key.
 * @param queryListener the listener.
 * @return the value, or null if the thread was interrupted while waiting for the value to be created.
 *
 * @see #get(Object)
 */
@VisibleForTesting
V get(@NonNull K key, @Nullable QueryListener queryListener) {
    ValueState<V> state = findValueState(key);

    if (queryListener != null) {
        queryListener.onQueryState(state.getState());
    }

    switch (state.getState()) {
        case EXISTING_VALUE:
            return state.getValue();
        case NEW_VALUE:
            // create the actual value content.
            V value = mValueFactory.create(key);

            // add to cache, and enable other threads to use the value.
            addNewValue(key, value, state.getLatch());

            return value;
        case PROCESSED_VALUE:
            // wait for value to become available
            try {
                state.getLatch().await();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return null;
            }
            synchronized (this) {
                // get it from the map cache.
                return mCache.get(key);
            }
        default:
            throw new IllegalStateException("unsupported ResultType: " + state.getState());
    }
}
 
Example #25
Source File: ApkInfoParser.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Parses the aapt output and returns an ApkInfo object.
 *
 * @param aaptOutput the aapt output as a list of lines.
 * @return an ApkInfo object.
 */
@VisibleForTesting
@NonNull
static ApkInfo getApkInfo(@NonNull List<String> aaptOutput) {

    String pkgName = null, versionCode = null, versionName = null;

    for (String line : aaptOutput) {
        Matcher m = PATTERN.matcher(line);
        if (m.matches()) {
            pkgName = m.group(1);
            versionCode = m.group(2);
            versionName = m.group(3);
            break;
        }
    }

    if (pkgName == null) {
        throw new RuntimeException("Failed to find apk information with aapt");
    }

    Integer intVersionCode = null;
    try {
        intVersionCode = Integer.parseInt(versionCode);
    } catch (NumberFormatException ignore) {
        // leave the version code as null.
    }

    return new ApkInfo(pkgName, intVersionCode, versionName);
}
 
Example #26
Source File: EcjParser.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Does the given compound name match the given string?
 * <p>
 * TODO: Check if ECJ already has this as a utility somewhere
 */
@VisibleForTesting
static boolean startsWithCompound(@NonNull String name, @NonNull char[][] compoundName) {
    int length = name.length();
    if (length == 0) {
        return false;
    }
    int index = 0;
    for (int i = 0, n = compoundName.length; i < n; i++) {
        char[] o = compoundName[i];
        for (int j = 0, m = o.length; j < m; j++) {
            if (index == length) {
                return false; // Don't allow prefix in a compound name
            }
            if (name.charAt(index) != o[j]) {
                return false;
            }
            index++;
        }
        if (i < n - 1) {
            if (index == length) {
                return true;
            }
            if (name.charAt(index) != '.') {
                return false;
            }
            index++;
            if (index == length) {
                return true;
            }
        }
    }

    return index == length;
}
 
Example #27
Source File: TBIncrementalVisitor.java    From atlas with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public static boolean isClassEligibleForInstantRun(@NonNull File inputFile) {

    if (inputFile.getPath().endsWith(SdkConstants.DOT_CLASS)) {
        String fileName = inputFile.getName();
        return !fileName.equals("R" + SdkConstants.DOT_CLASS) && !fileName.startsWith("R$");
    } else {
        return false;
    }
}
 
Example #28
Source File: SdkSourceProperties.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/** Empty current property list. Made accessible for testing purposes. */
@VisibleForTesting(visibility=Visibility.PRIVATE)
protected void clear() {
    synchronized (sSourcesProperties) {
        sSourcesProperties.clear();
        sModified = false;
    }
}
 
Example #29
Source File: LayoutLibrary.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE)
protected LayoutLibrary() {
    mBridge = null;
    mLegacyBridge = null;
    mClassLoader = null;
    mStatus = null;
    mLoadMessage = null;
}
 
Example #30
Source File: LocaleManager.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Guess the 3-letter region code containing the given time zone
 *
 * @param zone The timezone to look up
 * @return the corresponding 3 letter region code
 */
@SuppressWarnings("SpellCheckingInspection")
@Nullable
@VisibleForTesting
public static String getTimeZoneRegionAlpha3(@NonNull TimeZone zone) {
    int index = getTimeZoneRegionIndex(zone);
    if (index != -1) {
        return ISO_3166_2_CODES[index];
    }

    return null;
}