Java Code Examples for com.android.utils.SdkUtils

The following examples show how to use com.android.utils.SdkUtils. These examples are extracted from open source projects. 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 Project: java-n-IDE-for-Android   Source File: SingleResourceFile.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Validates the associated resource file to make sure the attribute references are valid
 *
 * @return true if parsing succeeds and false if it fails
 */
private boolean validateAttributes(ScanningContext context) {
    // We only need to check if it's a non-framework file (and an XML file; skip .png's)
    if (!isFramework() && SdkUtils.endsWith(getFile().getName(), DOT_XML)) {
        ValidatingResourceParser parser = new ValidatingResourceParser(context, false);
        try {
            IAbstractFile file = getFile();
            return parser.parse(file.getOsLocation(), file.getContents());
        } catch (Exception e) {
            context.needsFullAapt();
        }

        return false;
    }

    return true;
}
 
Example 2
Source Project: javaide   Source File: SingleResourceFile.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Validates the associated resource file to make sure the attribute references are valid
 *
 * @return true if parsing succeeds and false if it fails
 */
private boolean validateAttributes(ScanningContext context) {
    // We only need to check if it's a non-framework file (and an XML file; skip .png's)
    if (!isFramework() && SdkUtils.endsWith(getFile().getName(), DOT_XML)) {
        ValidatingResourceParser parser = new ValidatingResourceParser(context, false);
        try {
            IAbstractFile file = getFile();
            return parser.parse(file.getOsLocation(), file.getContents());
        } catch (Exception e) {
            context.needsFullAapt();
        }

        return false;
    }

    return true;
}
 
Example 3
Source Project: javaide   Source File: ApkInfoParser.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns the aapt output.
 *
 * @param apkFile the apk file to call aapt on.
 * @return the output as a list of files.
 * @throws ProcessException
 */
@NonNull
private List<String> getAaptOutput(@NonNull File apkFile)
        throws ProcessException {
    ProcessInfoBuilder builder = new ProcessInfoBuilder();

    builder.setExecutable(mAaptFile);
    builder.addArgs("dump", "badging", apkFile.getPath());

    CachedProcessOutputHandler processOutputHandler = new CachedProcessOutputHandler();

    mProcessExecutor.execute(
            builder.createProcess(), processOutputHandler)
            .rethrowFailure().assertNormalExitValue();

    BaseProcessOutputHandler.BaseProcessOutput output = processOutputHandler.getProcessOutput();

    return Splitter.on(SdkUtils.getLineSeparator()).splitToList(output.getStandardOutputAsString());
}
 
Example 4
Source Project: NBANDROID-V2   Source File: ResourceFolder.java    License: Apache License 2.0 6 votes vote down vote up
private ResourceFile createResourceFile(IAbstractFile file) {
    // check if that's a single or multi resource type folder. We have a special case
    // for ID generating resource types (layout/menu, and XML drawables, etc.).
    // MultiResourceFile handles the case when several resource types come from a single file
    // (values files).

    ResourceFile resFile;
    if (mType != ResourceFolderType.VALUES) {
        if (FolderTypeRelationship.isIdGeneratingFolderType(mType) &&
            SdkUtils.endsWithIgnoreCase(file.getName(), SdkConstants.DOT_XML)) {
            List<ResourceType> types = FolderTypeRelationship.getRelatedResourceTypes(mType);
            ResourceType primaryType = types.get(0);
            resFile = new IdGeneratingResourceFile(file, this, primaryType);
        } else {
            resFile = new SingleResourceFile(file, this);
        }
    } else {
        resFile = new MultiResourceFile(file, this, namespace);
    }
    return resFile;
}
 
Example 5
Source Project: NBANDROID-V2   Source File: SingleResourceFile.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Validates the associated resource file to make sure the attribute references are valid
 *
 * @return true if parsing succeeds and false if it fails
 */
private boolean validateAttributes(ScanningContext context) {
    // We only need to check if it's a non-framework file (and an XML file; skip .png's)
    if (!isFramework() && SdkUtils.endsWith(getFile().getName(), DOT_XML)) {
        ValidatingResourceParser parser = new ValidatingResourceParser(context, false);
        try {
            IAbstractFile file = getFile();
            return parser.parse(file.getOsLocation(), file.getContents());
        } catch (Exception e) {
            context.needsFullAapt();
        }

        return false;
    }

    return true;
}
 
Example 6
Source Project: java-n-IDE-for-Android   Source File: XmlPrettyPrinter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link XmlPrettyPrinter}
 *
 * @param prefs the preferences to format with
 * @param style the style to format with
 * @param lineSeparator the line separator to use, such as "\n" (can be null, in which
 *            case the system default is looked up via the line.separator property)
 */
public XmlPrettyPrinter(XmlFormatPreferences prefs, XmlFormatStyle style,
        String lineSeparator) {
    mPrefs = prefs;
    mStyle = style;
    if (lineSeparator == null) {
        lineSeparator = SdkUtils.getLineSeparator();
    }
    mLineSeparator = lineSeparator;
}
 
Example 7
Source Project: java-n-IDE-for-Android   Source File: XmlPrettyPrinter.java    License: Apache License 2.0 5 votes vote down vote up
private boolean hasBlankLineAbove() {
    if (mOut.length() < 2 * mLineSeparator.length()) {
        return false;
    }

    return SdkUtils.endsWith(mOut, mLineSeparator) &&
            SdkUtils.endsWith(mOut, mOut.length() - mLineSeparator.length(), mLineSeparator);
}
 
Example 8
Source Project: javaide   Source File: LintDetectorTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns the Android source tree root dir.
 * @return the root dir or null if it couldn't be computed.
 */
protected File getRootDir() {
    CodeSource source = getClass().getProtectionDomain().getCodeSource();
    if (source != null) {
        URL location = source.getLocation();
        try {
            File dir = SdkUtils.urlToFile(location);
            assertTrue(dir.getPath(), dir.exists());
            while (dir != null) {
                File settingsGradle = new File(dir, "settings.gradle"); //$NON-NLS-1$
                if (settingsGradle.exists()) {
                    return dir.getParentFile().getParentFile();
                }
                File lint = new File(dir, "lint");  //$NON-NLS-1$
                if (lint.exists() && new File(lint, "cli").exists()) { //$NON-NLS-1$
                    return dir.getParentFile().getParentFile();
                }
                dir = dir.getParentFile();
            }

            return null;
        } catch (MalformedURLException e) {
            fail(e.getLocalizedMessage());
        }
    }

    return null;
}
 
Example 9
Source Project: javaide   Source File: TextReporter.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void explainIssue(@NonNull StringBuilder output, @Nullable Issue issue)
        throws IOException {
    if (issue == null || !mFlags.isExplainIssues() || issue == IssueRegistry.LINT_ERROR) {
        return;
    }

    String explanation = issue.getExplanation(TextFormat.TEXT);
    if (explanation.trim().isEmpty()) {
        return;
    }

    String indent = "   ";
    String formatted = SdkUtils.wrap(explanation, Main.MAX_LINE_WIDTH - indent.length(), null);
    output.append('\n');
    output.append(indent);
    output.append("Explanation for issues of type \"").append(issue.getId()).append("\":\n");
    for (String line : Splitter.on('\n').split(formatted)) {
        if (!line.isEmpty()) {
            output.append(indent);
            output.append(line);
        }
        output.append('\n');
    }
    List<String> moreInfo = issue.getMoreInfo();
    if (!moreInfo.isEmpty()) {
        for (String url : moreInfo) {
            if (formatted.contains(url)) {
                continue;
            }
            output.append(indent);
            output.append(url);
            output.append('\n');
        }
        output.append('\n');
    }
}
 
Example 10
Source Project: javaide   Source File: Reporter.java    License: GNU General Public License v3.0 5 votes vote down vote up
String getUrl(File file) {
    if (mBundleResources && !mSimpleFormat) {
        String url = getRelativeResourceUrl(file);
        if (url != null) {
            return url;
        }
    }

    if (mUrlMap != null) {
        String path = file.getAbsolutePath();
        // Perform the comparison using URLs such that we properly escape spaces etc.
        String pathUrl = encodeUrl(path);
        for (Map.Entry<String, String> entry : mUrlMap.entrySet()) {
            String prefix = entry.getKey();
            String prefixUrl = encodeUrl(prefix);
            if (pathUrl.startsWith(prefixUrl)) {
                String relative = pathUrl.substring(prefixUrl.length());
                return entry.getValue() + relative;
            }
        }
    }

    if (file.isAbsolute()) {
        String relativePath = getRelativePath(mOutput.getParentFile(), file);
        if (relativePath != null) {
            relativePath = relativePath.replace(separatorChar, '/');
            return encodeUrl(relativePath);
        }
    }

    try {
        return SdkUtils.fileToUrlString(file);
    } catch (MalformedURLException e) {
        return null;
    }
}
 
Example 11
private static boolean oneOfStartsWithIgnoreCase(List<String> strings, String prefix) {
    boolean matches = false;
    for (String allowedString : strings) {
        if (SdkUtils.startsWithIgnoreCase(allowedString, prefix)) {
            matches = true;
            break;
        }
    }
    return matches;
}
 
Example 12
Source Project: javaide   Source File: XmlPrettyPrinter.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a new {@link XmlPrettyPrinter}
 *
 * @param prefs the preferences to format with
 * @param style the style to format with
 * @param lineSeparator the line separator to use, such as "\n" (can be null, in which
 *            case the system default is looked up via the line.separator property)
 */
public XmlPrettyPrinter(XmlFormatPreferences prefs, XmlFormatStyle style,
        String lineSeparator) {
    mPrefs = prefs;
    mStyle = style;
    if (lineSeparator == null) {
        lineSeparator = SdkUtils.getLineSeparator();
    }
    mLineSeparator = lineSeparator;
}
 
Example 13
Source Project: javaide   Source File: XmlPrettyPrinter.java    License: GNU General Public License v3.0 5 votes vote down vote up
private boolean hasBlankLineAbove() {
    if (mOut.length() < 2 * mLineSeparator.length()) {
        return false;
    }

    return SdkUtils.endsWith(mOut, mLineSeparator) &&
            SdkUtils.endsWith(mOut, mOut.length() - mLineSeparator.length(), mLineSeparator);
}
 
Example 14
Source Project: NBANDROID-V2   Source File: FmGetConfigurationNameMethod.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Replaces the given suffix in the string, preserving the case in the
 * string, e.g. replacing "foo" with "bar" will result in "bar", and
 * replacing "myFoo" with "bar" will result in "myBar". (This is not a
 * general purpose method; it assumes that the only non-lowercase letter is
 * the first letter of the suffix.)
 */
private static String replaceSuffixWithCase(String s, String suffix, String newSuffix) {
    if (SdkUtils.endsWithIgnoreCase(s, suffix)) {
        int suffixBegin = s.length() - suffix.length();
        if (Character.isUpperCase(s.charAt(suffixBegin))) {
            return s.substring(0, suffixBegin) + Character.toUpperCase(newSuffix.charAt(0)) + newSuffix.substring(1);
        } else if (suffixBegin == 0) {
            return newSuffix;
        } else {
            return s.substring(0, suffixBegin) + suffix;
        }
    }

    return s;
}
 
Example 15
Source Project: MeituanLintDemo   Source File: MTLintDetectorTest.java    License: Apache License 2.0 5 votes vote down vote up
private File getTestDataRootDir() {
    CodeSource source = getClass().getProtectionDomain().getCodeSource();
    if (source != null) {
        URL location = source.getLocation();
        try {
            File classesDir = SdkUtils.urlToFile(location);
            return classesDir.getParentFile().getAbsoluteFile().getParentFile().getParentFile();
        } catch (MalformedURLException e) {
            fail(e.getLocalizedMessage());
        }
    }
    return null;
}
 
Example 16
Source Project: Android-Lint-Checks   Source File: AbstractDetectorTest.java    License: Apache License 2.0 5 votes vote down vote up
private File getTestDataRootDir() {
    CodeSource source = getClass().getProtectionDomain().getCodeSource();
    if (source != null) {
        URL location = source.getLocation();
        try {
            File classesDir = SdkUtils.urlToFile(location);
            return classesDir.getParentFile().getAbsoluteFile().getParentFile().getParentFile();
        } catch (MalformedURLException e) {
            fail(e.getLocalizedMessage());
        }
    }
    return null;
}
 
Example 17
Source Project: Android-Lint-Checks   Source File: AbstractDetectorTest.java    License: Apache License 2.0 5 votes vote down vote up
private File getTestDataRootDir() {
    CodeSource source = getClass().getProtectionDomain().getCodeSource();
    if (source != null) {
        URL location = source.getLocation();
        try {
            File classesDir = SdkUtils.urlToFile(location);
            return classesDir.getParentFile().getAbsoluteFile().getParentFile().getParentFile();
        } catch (MalformedURLException e) {
            fail(e.getLocalizedMessage());
        }
    }
    return null;
}
 
Example 18
Source Project: linette   Source File: AbstractDetectorTest.java    License: Apache License 2.0 5 votes vote down vote up
private File getTestDataRootDir() {
    CodeSource source = getClass().getProtectionDomain().getCodeSource();
    if (source != null) {
        URL location = source.getLocation();
        try {
            File classesDir = SdkUtils.urlToFile(location);
            return classesDir.getParentFile().getAbsoluteFile().getParentFile().getParentFile();
        } catch (MalformedURLException e) {
            fail(e.getLocalizedMessage());
        }
    }
    return null;
}
 
Example 19
Source Project: java-n-IDE-for-Android   Source File: XmlPrettyPrinter.java    License: Apache License 2.0 4 votes vote down vote up
private static void formatFile(@NonNull XmlFormatPreferences prefs, File file,
        boolean stdout) {
    if (file.isDirectory()) {
        File[] files = file.listFiles();
        if (files != null) {
            for (File child : files) {
                formatFile(prefs, child, stdout);
            }
        }
    } else if (file.isFile() && SdkUtils.endsWithIgnoreCase(file.getName(), DOT_XML)) {
        XmlFormatStyle style = null;
        if (file.getName().equals(SdkConstants.ANDROID_MANIFEST_XML)) {
            style = XmlFormatStyle.MANIFEST;
        } else {
            File parent = file.getParentFile();
            if (parent != null) {
                String parentName = parent.getName();
                ResourceFolderType folderType = ResourceFolderType.getFolderType(parentName);
                if (folderType == ResourceFolderType.LAYOUT) {
                    style = XmlFormatStyle.LAYOUT;
                } else if (folderType == ResourceFolderType.VALUES) {
                    style = XmlFormatStyle.RESOURCE;
                }
            }
        }

        try {
            String xml = Files.toString(file, Charsets.UTF_8);
            Document document = XmlUtils.parseDocumentSilently(xml, true);
            if (document == null) {
                System.err.println("Could not parse " + file);
                System.exit(1);
                return;
            }

            if (style == null) {
                style = XmlFormatStyle.get(document);
            }
            boolean endWithNewline = xml.endsWith("\n");
            int firstNewLine = xml.indexOf('\n');
            String lineSeparator = firstNewLine > 0 && xml.charAt(firstNewLine - 1) == '\r' ?
                    "\r\n" : "\n";
            String formatted = XmlPrettyPrinter.prettyPrint(document, prefs, style,
                    lineSeparator, endWithNewline);
            if (stdout) {
                System.out.println(formatted);
            } else {
                Files.write(formatted, file, Charsets.UTF_8);
            }
        } catch (IOException e) {
            System.err.println("Could not read " + file);
            System.exit(1);
        }
    }
}
 
Example 20
Source Project: java-n-IDE-for-Android   Source File: ManifestMerger2.java    License: Apache License 2.0 4 votes vote down vote up
public String toCamelCase() {
    return SdkUtils.constantNameToCamelCase(name());
}
 
Example 21
Source Project: java-n-IDE-for-Android   Source File: ManifestModel.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Returns the Xml name for this node type
 */
String toXmlName() {
    return SdkUtils.constantNameToXmlName(this.name());
}
 
Example 22
Source Project: java-n-IDE-for-Android   Source File: ManifestMerger.java    License: Apache License 2.0 4 votes vote down vote up
private static int insertSourceMarker(@NonNull Node parent, @NonNull Node node,
        @NonNull File file, boolean after) {
    int insertCount = 0;
    Document doc = parent.getNodeType() ==
            Node.DOCUMENT_NODE ? (Document) parent : parent.getOwnerDocument();

    String comment;
    try {
        comment = SdkUtils.createPathComment(file, true);
    } catch (MalformedURLException e) {
        return insertCount;
    }

    Node prev = node.getPreviousSibling();
    String newline;
    if (prev != null && prev.getNodeType() == Node.TEXT_NODE) {
        // Duplicate indentation from previous line. Once we switch the merger
        // over to using the XmlPrettyPrinter, we won't need this.
        newline = prev.getNodeValue();
        int index = newline.lastIndexOf('\n');
        if (index != -1) {
            newline = newline.substring(index);
        }
    } else {
        newline = "\n";
    }

    if (after) {
        node = node.getNextSibling();
    }

    parent.insertBefore(doc.createComment(comment), node);
    insertCount++;

    // Can't add text nodes at the document level in Xerces, even though
    // it will happily parse these
    if (parent.getNodeType() != Node.DOCUMENT_NODE) {
        parent.insertBefore(doc.createTextNode(newline), node);
        insertCount++;
    }

    return insertCount;
}
 
Example 23
Source Project: javaide   Source File: ManifestMerger2.java    License: GNU General Public License v3.0 4 votes vote down vote up
public String toCamelCase() {
    return SdkUtils.constantNameToCamelCase(name());
}
 
Example 24
Source Project: javaide   Source File: ManifestModel.java    License: GNU General Public License v3.0 4 votes vote down vote up
/**
 * Returns the Xml name for this node type
 */
String toXmlName() {
    return SdkUtils.constantNameToXmlName(this.name());
}
 
Example 25
Source Project: javaide   Source File: ManifestMerger.java    License: GNU General Public License v3.0 4 votes vote down vote up
private static int insertSourceMarker(@NonNull Node parent, @NonNull Node node,
        @NonNull File file, boolean after) {
    int insertCount = 0;
    Document doc = parent.getNodeType() ==
            Node.DOCUMENT_NODE ? (Document) parent : parent.getOwnerDocument();

    String comment;
    try {
        comment = SdkUtils.createPathComment(file, true);
    } catch (MalformedURLException e) {
        return insertCount;
    }

    Node prev = node.getPreviousSibling();
    String newline;
    if (prev != null && prev.getNodeType() == Node.TEXT_NODE) {
        // Duplicate indentation from previous line. Once we switch the merger
        // over to using the XmlPrettyPrinter, we won't need this.
        newline = prev.getNodeValue();
        int index = newline.lastIndexOf('\n');
        if (index != -1) {
            newline = newline.substring(index);
        }
    } else {
        newline = "\n";
    }

    if (after) {
        node = node.getNextSibling();
    }

    parent.insertBefore(doc.createComment(comment), node);
    insertCount++;

    // Can't add text nodes at the document level in Xerces, even though
    // it will happily parse these
    if (parent.getNodeType() != Node.DOCUMENT_NODE) {
        parent.insertBefore(doc.createTextNode(newline), node);
        insertCount++;
    }

    return insertCount;
}
 
Example 26
Source Project: javaide   Source File: Main.java    License: GNU General Public License v3.0 4 votes vote down vote up
static String wrap(String explanation, int lineWidth, String hangingIndent) {
    return SdkUtils.wrap(explanation, lineWidth, hangingIndent);
}
 
Example 27
Source Project: javaide   Source File: XmlPrettyPrinter.java    License: GNU General Public License v3.0 4 votes vote down vote up
private static void formatFile(@NonNull XmlFormatPreferences prefs, File file,
        boolean stdout) {
    if (file.isDirectory()) {
        File[] files = file.listFiles();
        if (files != null) {
            for (File child : files) {
                formatFile(prefs, child, stdout);
            }
        }
    } else if (file.isFile() && SdkUtils.endsWithIgnoreCase(file.getName(), DOT_XML)) {
        XmlFormatStyle style = null;
        if (file.getName().equals(SdkConstants.ANDROID_MANIFEST_XML)) {
            style = XmlFormatStyle.MANIFEST;
        } else {
            File parent = file.getParentFile();
            if (parent != null) {
                String parentName = parent.getName();
                ResourceFolderType folderType = ResourceFolderType.getFolderType(parentName);
                if (folderType == ResourceFolderType.LAYOUT) {
                    style = XmlFormatStyle.LAYOUT;
                } else if (folderType == ResourceFolderType.VALUES) {
                    style = XmlFormatStyle.RESOURCE;
                }
            }
        }

        try {
            String xml = Files.toString(file, Charsets.UTF_8);
            Document document = XmlUtils.parseDocumentSilently(xml, true);
            if (document == null) {
                System.err.println("Could not parse " + file);
                System.exit(1);
                return;
            }

            if (style == null) {
                style = XmlFormatStyle.get(document);
            }
            boolean endWithNewline = xml.endsWith("\n");
            int firstNewLine = xml.indexOf('\n');
            String lineSeparator = firstNewLine > 0 && xml.charAt(firstNewLine - 1) == '\r' ?
                    "\r\n" : "\n";
            String formatted = XmlPrettyPrinter.prettyPrint(document, prefs, style,
                    lineSeparator, endWithNewline);
            if (stdout) {
                System.out.println(formatted);
            } else {
                Files.write(formatted, file, Charsets.UTF_8);
            }
        } catch (IOException e) {
            System.err.println("Could not read " + file);
            System.exit(1);
        }
    }
}
 
Example 28
private static boolean isWindows() {
  return SdkUtils.startsWithIgnoreCase(System.getProperty("os.name"), "windows");
}
 
Example 29
private static boolean isWindows() {
  return SdkUtils.startsWithIgnoreCase(System.getProperty("os.name"), "windows");
}
 
Example 30
Source Project: java-n-IDE-for-Android   Source File: ManifestModel.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Returns the {@link NodeTypes} instance from an xml element name (without namespace
 * decoration). For instance, an xml element
 * <pre>
 *     {@code
 *     <activity android:name="foo">
 *         ...
 *     </activity>}
 * </pre>
 * has a xml simple name of "activity" which will resolve to {@link NodeTypes#ACTIVITY} value.
 *
 * Note : a runtime exception will be generated if no mapping from the simple name to a
 * {@link NodeTypes} exists.
 *
 * @param xmlSimpleName the xml (lower-hyphen separated words) simple name.
 * @return the {@link NodeTypes} associated with that element name.
 */
static NodeTypes fromXmlSimpleName(String xmlSimpleName) {
    String constantName = SdkUtils.xmlNameToConstantName(xmlSimpleName);

    try {
        return NodeTypes.valueOf(constantName);
    } catch (IllegalArgumentException e) {
        // if this element name is not a known tag, we categorize it as 'custom' which will
        // be simply merged. It will prevent us from catching simple spelling mistakes but
        // extensibility is a must have feature.
        return NodeTypes.CUSTOM;
    }
}