com.android.utils.SdkUtils Java Examples

The following examples show how to use com.android.utils.SdkUtils. 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: SingleResourceFile.java    From NBANDROID-V2 with 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 File: ResourceFolder.java    From NBANDROID-V2 with 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 #3
Source File: ApkInfoParser.java    From javaide with 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 File: SingleResourceFile.java    From javaide with 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 #5
Source File: SingleResourceFile.java    From java-n-IDE-for-Android with 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 File: Reporter.java    From javaide with 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 #7
Source File: AbstractDetectorTest.java    From linette with 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 #8
Source File: AbstractDetectorTest.java    From Android-Lint-Checks with 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 #9
Source File: AbstractDetectorTest.java    From Android-Lint-Checks with 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 #10
Source File: MTLintDetectorTest.java    From MeituanLintDemo with 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 #11
Source File: FmGetConfigurationNameMethod.java    From NBANDROID-V2 with 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 #12
Source File: XmlPrettyPrinter.java    From javaide with 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 #13
Source File: XmlPrettyPrinter.java    From javaide with 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 #14
Source File: FileResourceNameValidator.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
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 #15
Source File: TextReporter.java    From javaide with 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 #16
Source File: XmlPrettyPrinter.java    From java-n-IDE-for-Android with 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 #17
Source File: XmlPrettyPrinter.java    From java-n-IDE-for-Android with 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 #18
Source File: LintDetectorTest.java    From javaide with 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 #19
Source File: ManifestMerger.java    From java-n-IDE-for-Android with 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 #20
Source File: XmlPrettyPrinter.java    From java-n-IDE-for-Android with 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 #21
Source File: GradleDependencyFetcher.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private static boolean isWindows() {
  return SdkUtils.startsWithIgnoreCase(System.getProperty("os.name"), "windows");
}
 
Example #22
Source File: GradleDependencyFetcher.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private static boolean isWindows() {
  return SdkUtils.startsWithIgnoreCase(System.getProperty("os.name"), "windows");
}
 
Example #23
Source File: ManifestMerger2.java    From java-n-IDE-for-Android with Apache License 2.0 4 votes vote down vote up
public String toCamelCase() {
    return SdkUtils.constantNameToCamelCase(name());
}
 
Example #24
Source File: ManifestModel.java    From java-n-IDE-for-Android with 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 #25
Source File: XmlPrettyPrinter.java    From javaide with 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 #26
Source File: ManifestMerger2.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
public String toCamelCase() {
    return SdkUtils.constantNameToCamelCase(name());
}
 
Example #27
Source File: ManifestModel.java    From javaide with 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 #28
Source File: ManifestMerger.java    From javaide with 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 #29
Source File: Main.java    From javaide with 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 #30
Source File: ManifestModel.java    From java-n-IDE-for-Android with 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;
    }
}