Java Code Examples for com.android.resources.ResourceType#getEnum()

The following examples show how to use com.android.resources.ResourceType#getEnum() . 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: ValueResourceParser.java    From paraphrase with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the type of the ResourceItem based on a node's attributes.
 * @param node the node
 * @return the ResourceType or null if it could not be inferred.
 */
static ResourceType getType(Node node) {
  String nodeName = node.getLocalName();
  String typeString = null;

  if (TAG_ITEM.equals(nodeName)) {
    Attr attribute = (Attr) node.getAttributes().getNamedItemNS(null, ATTR_TYPE);
    if (attribute != null) {
      typeString = attribute.getValue();
    }
  } else {
    // the type is the name of the node.
    typeString = nodeName;
  }

  if (typeString != null) {
    return ResourceType.getEnum(typeString);
  }

  return null;
}
 
Example 2
Source File: ProtoApk.java    From bazel with Apache License 2.0 6 votes vote down vote up
private void copyResourceType(
    BiPredicate<ResourceType, String> resourceFilter,
    UniqueZipBuilder dstZip,
    Package.Builder dstPkgBuilder,
    Resources.Type type)
    throws IOException {
  Type.Builder dstTypeBuilder = Resources.Type.newBuilder(type);
  dstTypeBuilder.clearEntry();

  ResourceType resourceType = ResourceType.getEnum(type.getName());
  for (Entry entry : type.getEntryList()) {
    if (resourceFilter.test(resourceType, entry.getName())) {
      copyEntry(dstZip, dstTypeBuilder, entry);
    }
  }
  final Resources.Type dstType = dstTypeBuilder.build();
  if (!dstType.getEntryList().isEmpty()) {
    dstPkgBuilder.addType(dstType);
  }
}
 
Example 3
Source File: PrivateResourceDetector.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void visitResourceReference(
        @NonNull JavaContext context,
        @Nullable AstVisitor visitor,
        @NonNull Node node,
        @NonNull String type,
        @NonNull String name,
        boolean isFramework) {
    if (context.getProject().isGradleProject() && !isFramework) {
        Project project = context.getProject();
        if (project.getGradleProjectModel() != null && project.getCurrentVariant() != null) {
            ResourceType resourceType = ResourceType.getEnum(type);
            if (resourceType != null && isPrivate(context, resourceType, name)) {
                String message = createUsageErrorMessage(context, resourceType, name);
                context.report(ISSUE, node, context.getLocation(node), message);
            }
        }
    }
}
 
Example 4
Source File: ValueResourceParser.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private static ResourceType getType(String qName, Attributes attributes) {
    String typeValue;

    // if the node is <item>, we get the type from the attribute "type"
    if (TAG_ITEM.equals(qName)) {
        typeValue = attributes.getValue(ATTR_TYPE);
    } else {
        // the type is the name of the node.
        typeValue = qName;
    }

    return ResourceType.getEnum(typeValue);
}
 
Example 5
Source File: FullyQualifiedName.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static Type createTypeFrom(String rawType) {
  ResourceType resourceType = ResourceType.getEnum(rawType);
  VirtualType virtualType = VirtualType.getEnum(rawType);
  if (resourceType != null) {
    return new ResourceTypeWrapper(resourceType);
  } else if (virtualType != null) {
    return virtualType;
  }
  return null;
}
 
Example 6
Source File: XmlResourceValues.java    From bazel with Apache License 2.0 5 votes vote down vote up
static XmlResourceValue parsePublic(
    XMLEventReader eventReader, StartElement start, Namespaces.Collector namespacesCollector)
    throws XMLStreamException {
  namespacesCollector.collectFrom(start);
  // The tag should be unary.
  if (!isEndTag(eventReader.peek(), start.getName())) {
    throw new XMLStreamException(
        String.format("<public> tag should be unary %s", start), start.getLocation());
  }
  // The tag should have a valid type attribute, and optionally an id attribute.
  ImmutableMap<String, String> attributes = ImmutableMap.copyOf(parseTagAttributes(start));
  String typeAttr = attributes.get(SdkConstants.ATTR_TYPE);
  ResourceType type;
  if (typeAttr != null) {
    type = ResourceType.getEnum(typeAttr);
    if (type == null || type == ResourceType.PUBLIC) {
      throw new XMLStreamException(
          String.format("<public> tag has invalid type attribute %s", start),
          start.getLocation());
    }
  } else {
    throw new XMLStreamException(
        String.format("<public> tag missing type attribute %s", start), start.getLocation());
  }
  String idValueAttr = attributes.get(SdkConstants.ATTR_ID);
  Optional<Integer> id = Optional.absent();
  if (idValueAttr != null) {
    try {
      id = Optional.of(Integer.decode(idValueAttr));
    } catch (NumberFormatException e) {
      throw new XMLStreamException(
          String.format("<public> has invalid id number %s", start), start.getLocation());
    }
  }
  if (attributes.size() > 2) {
    throw new XMLStreamException(
        String.format("<public> has unexpected attributes %s", start), start.getLocation());
  }
  return PublicXmlResourceValue.create(type, id);
}
 
Example 7
Source File: ResourceUsageAnalyzer.java    From bazel with Apache License 2.0 5 votes vote down vote up
/** Remove public definitions of unused resources. */
private void trimPublicResources(
    File publicXml, Set<Resource> deleted, Map<File, String> rewritten)
    throws IOException, ParserConfigurationException, SAXException {
  if (publicXml.exists()) {
    String xml = rewritten.get(publicXml);
    if (xml == null) {
      xml = Files.toString(publicXml, UTF_8);
    }
    Document document = XmlUtils.parseDocument(xml, true);
    Element root = document.getDocumentElement();
    if (root != null && TAG_RESOURCES.equals(root.getTagName())) {
      NodeList children = root.getChildNodes();
      for (int i = children.getLength() - 1; i >= 0; i--) {
        Node child = children.item(i);
        if (child.getNodeType() == Node.ELEMENT_NODE) {
          Element resourceElement = (Element) child;
          ResourceType type = ResourceType.getEnum(resourceElement.getAttribute(ATTR_TYPE));
          String name = resourceElement.getAttribute(ATTR_NAME);
          if (type != null && name != null) {
            Resource resource = model.getResource(type, name);
            if (resource != null && deleted.contains(resource)) {
              root.removeChild(child);
            }
          }
        }
      }
    }
    String formatted = XmlPrettyPrinter.prettyPrint(document, xml.endsWith("\n"));
    rewritten.put(publicXml, formatted);
  }
}
 
Example 8
Source File: ValueResourceParser.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
private static ResourceType getType(String qName, Attributes attributes) {
    String typeValue;

    // if the node is <item>, we get the type from the attribute "type"
    if (TAG_ITEM.equals(qName)) {
        typeValue = attributes.getValue(ATTR_TYPE);
    } else {
        // the type is the name of the node.
        typeValue = qName;
    }

    return ResourceType.getEnum(typeValue);
}
 
Example 9
Source File: ResourceVisibilityLookup.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a map from name to applicable resource types where the presence of the type+name
 * combination means that the corresponding resource is explicitly public.
 *
 * If the result is null, there is no {@code public.txt} definition for this library, so all
 * resources should be taken to be public.
 *
 * @return a map from name to resource type for public resources in this library
 */
@Nullable
private Multimap<String, ResourceType> computeVisibilityMap() {
    File publicResources = mLibrary.getPublicResources();
    if (!publicResources.exists()) {
        return null;
    }

    try {
        List<String> lines = Files.readLines(publicResources, Charsets.UTF_8);
        Multimap<String, ResourceType> result = ArrayListMultimap.create(lines.size(), 2);
        for (String line : lines) {
            // These files are written by code in MergedResourceWriter#postWriteAction
            // Format for each line: <type><space><name>\n
            // Therefore, we don't expect/allow variations in the format (we don't
            // worry about extra spaces needing to be trimmed etc)
            int index = line.indexOf(' ');
            if (index == -1 || line.isEmpty()) {
                continue;
            }

            String typeString = line.substring(0, index);
            ResourceType type = ResourceType.getEnum(typeString);
            if (type == null) {
                // This could in theory happen if in the future a new ResourceType is
                // introduced, and a newer version of the Gradle build system writes the
                // name of this type into the public.txt file, and an older version of
                // the IDE then attempts to read it. Just skip these symbols.
                continue;
            }
            String name = line.substring(index + 1);
            result.put(name, type);
        }
        return result;
    } catch (IOException ignore) {
    }
    return null;
}
 
Example 10
Source File: ResourceItem.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
@Nullable
private ResourceType getType(String qName, NamedNodeMap attributes) {
    String typeValue;

    // if the node is <item>, we get the type from the attribute "type"
    if (SdkConstants.TAG_ITEM.equals(qName)) {
        typeValue = getAttributeValue(attributes, ATTR_TYPE);
    } else {
        // the type is the name of the node.
        typeValue = qName;
    }

    return ResourceType.getEnum(typeValue);
}
 
Example 11
Source File: ValueResourceParser2.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns the type of the ResourceItem based on a node's attributes.
 * @param node the node
 * @return the ResourceType or null if it could not be inferred.
 */
static ResourceType getType(@NonNull Node node, @Nullable File from) throws MergingException {
    String nodeName = node.getLocalName();
    String typeString = null;

    if (TAG_ITEM.equals(nodeName)) {
        Attr attribute = (Attr) node.getAttributes().getNamedItemNS(null, ATTR_TYPE);
        if (attribute != null) {
            typeString = attribute.getValue();
        }
    } else if (TAG_EAT_COMMENT.equals(nodeName) || TAG_SKIP.equals(nodeName)) {
        return null;
    } else {
        // the type is the name of the node.
        typeString = nodeName;
    }

    if (typeString != null) {
        ResourceType type = ResourceType.getEnum(typeString);
        if (type != null) {
            return type;
        }
        throw MergingException.withMessage("Unsupported type '%s'", typeString).withFile(from)
                .build();
    }

    throw MergingException.withMessage("Unsupported node '%s'", nodeName).withFile(from).build();
}
 
Example 12
Source File: ResourceItem.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
private ResourceType getType(String qName, NamedNodeMap attributes) {
    String typeValue;

    // if the node is <item>, we get the type from the attribute "type"
    if (SdkConstants.TAG_ITEM.equals(qName)) {
        typeValue = getAttributeValue(attributes, ATTR_TYPE);
    } else {
        // the type is the name of the node.
        typeValue = qName;
    }

    return ResourceType.getEnum(typeValue);
}
 
Example 13
Source File: ProtoResourceUsageAnalyzer.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static Resource parse(ResourceUsageModel model, String resourceTypeAndName) {
  final Iterator<String> iterator = Splitter.on('/').split(resourceTypeAndName).iterator();
  Preconditions.checkArgument(
      iterator.hasNext(), "%s invalid resource name", resourceTypeAndName);
  ResourceType resourceType = ResourceType.getEnum(iterator.next());
  Preconditions.checkArgument(
      iterator.hasNext(), "%s invalid resource name", resourceTypeAndName);
  return model.getResource(resourceType, iterator.next());
}
 
Example 14
Source File: ProtoXmlUtils.java    From bazel with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static Optional<Reference> parseResourceReference(String value) {
  if (value.startsWith("@") || value.startsWith("?")) {
    boolean isPrivate = false;
    int startIndex = 1;

    if (value.length() <= startIndex) {
      return Optional.empty();
    }
    if (value.charAt(startIndex) == '+') {
      startIndex++;
    } else if (value.charAt(startIndex) == '*') {
      startIndex++;
      isPrivate = true;
    }
    if (value.length() <= startIndex) {
      return Optional.empty();
    }

    int slashIndex = value.indexOf('/', startIndex);
    if (slashIndex == -1) {
      return Optional.empty();
    }

    int colonIndex = value.lastIndexOf(':', slashIndex);
    int typeBegin = colonIndex == -1 ? startIndex : colonIndex + 1;
    if (ResourceType.getEnum(value.substring(typeBegin, slashIndex)) == null) {
      // aapt2 will treat something like "@x/foo" as a string instead of throwing an error.
      return Optional.empty();
    }

    return Optional.of(
        Reference.newBuilder()
            .setType(value.startsWith("@") ? Reference.Type.REFERENCE : Reference.Type.ATTRIBUTE)
            .setPrivate(isPrivate)
            .setName(value.substring(startIndex))
            .build());
  }
  return Optional.empty();
}
 
Example 15
Source File: ValueResourceParser.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
private ResourceType getType(String qName, Attributes attributes) {
    String typeValue;

    // if the node is <item>, we get the type from the attribute "type"
    if (NODE_ITEM.equals(qName)) {
        typeValue = attributes.getValue(ATTR_TYPE);
    } else {
        // the type is the name of the node.
        typeValue = qName;
    }

    ResourceType type = ResourceType.getEnum(typeValue);
    return type;
}
 
Example 16
Source File: ValueResourceParser2.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the type of the ResourceItem based on a node's attributes.
 * @param node the node
 * @return the ResourceType or null if it could not be inferred.
 */
static ResourceType getType(@NonNull Node node, @Nullable File from) {
    String nodeName = node.getLocalName();
    String typeString = null;

    if (TAG_ITEM.equals(nodeName)) {
        Attr attribute = (Attr) node.getAttributes().getNamedItemNS(null, ATTR_TYPE);
        if (attribute != null) {
            typeString = attribute.getValue();
        }
    } else if (TAG_EAT_COMMENT.equals(nodeName) || TAG_SKIP.equals(nodeName)) {
        return null;
    } else {
        // the type is the name of the node.
        typeString = nodeName;
    }

    if (typeString != null) {
        ResourceType type = ResourceType.getEnum(typeString);
        if (type != null) {
            return type;
        }

        if (from != null) {
            throw new RuntimeException(String.format("Unsupported type '%s' in file %s", typeString, from));
        }
        throw new RuntimeException(String.format("Unsupported type '%s'", typeString));
    }

    if (from != null) {
        throw new RuntimeException(String.format("Unsupported node '%s' in file %s", nodeName, from));
    }
    throw new RuntimeException(String.format("Unsupported node '%s'", nodeName));
}
 
Example 17
Source File: ResourceVisibilityLookup.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Returns a map from name to resource types for all resources known to this library. This
 * is used to make sure that when the {@link #isPrivate(ResourceType, String)} query method
 * is called, it can tell the difference between a resource implicitly private by not being
 * declared as public and a resource unknown to this library (e.g. defined by a different
 * library or the user's own project resources.)
 *
 * @return a map from name to resource type for all resources in this library
 */
@Nullable
private Multimap<String, ResourceType> computeAllMap() {
    // getSymbolFile() is not defined in AndroidLibrary, only in the subclass LibraryBundle
    File symbolFile = new File(mLibrary.getPublicResources().getParentFile(),
            FN_RESOURCE_TEXT);
    if (!symbolFile.exists()) {
        return null;
    }

    try {
        List<String> lines = Files.readLines(symbolFile, Charsets.UTF_8);
        Multimap<String, ResourceType> result = ArrayListMultimap.create(lines.size(), 2);

        ResourceType previousType = null;
        String previousTypeString = "";
        int lineIndex = 1;
        final int count = lines.size();
        for (; lineIndex <= count; lineIndex++) {
            String line = lines.get(lineIndex - 1);

            if (line.startsWith("int ")) { // not int[] definitions for styleables
                // format is "int <type> <class> <name> <value>"
                int typeStart = 4;
                int typeEnd = line.indexOf(' ', typeStart);

                // Items are sorted by type, so we can avoid looping over types in
                // ResourceType.getEnum() for each line by sharing type in each section
                String typeString = line.substring(typeStart, typeEnd);
                ResourceType type;
                if (typeString.equals(previousTypeString)) {
                    type = previousType;
                } else {
                    type = ResourceType.getEnum(typeString);
                    previousTypeString = typeString;
                    previousType = type;
                }
                if (type == null) { // some newly introduced type
                    continue;
                }

                int nameStart = typeEnd + 1;
                int nameEnd = line.indexOf(' ', nameStart);
                String name = line.substring(nameStart, nameEnd);
                result.put(name, type);
            }
        }
        return result;
    } catch (IOException ignore) {
    }
    return null;
}
 
Example 18
Source File: DataResourceXml.java    From bazel with Apache License 2.0 4 votes vote down vote up
private static ResourceType getResourceType(StartElement start) {
  if (XmlResourceValues.isItem(start)) {
    return ResourceType.getEnum(XmlResourceValues.getElementType(start));
  }
  return ResourceType.getEnum(start.getName().getLocalPart());
}
 
Example 19
Source File: SupportAnnotationDetector.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
private void checkParameterAnnotation(
        @NonNull JavaContext context,
        @NonNull Node argument,
        @NonNull Node call,
        @NonNull ResolvedMethod method,
        @NonNull ResolvedAnnotation annotation,
        @NonNull Iterable<ResolvedAnnotation> allAnnotations) {
    String signature = annotation.getSignature();

    if (COLOR_INT_ANNOTATION.equals(signature)) {
        checkColor(context, argument);
    } else if (signature.equals(INT_RANGE_ANNOTATION)) {
        checkIntRange(context, annotation, argument, allAnnotations);
    } else if (signature.equals(FLOAT_RANGE_ANNOTATION)) {
        checkFloatRange(context, annotation, argument);
    } else if (signature.equals(SIZE_ANNOTATION)) {
        checkSize(context, annotation, argument);
    } else if (signature.startsWith(PERMISSION_ANNOTATION)) {
        // PERMISSION_ANNOTATION, PERMISSION_ANNOTATION_READ, PERMISSION_ANNOTATION_WRITE
        // When specified on a parameter, that indicates that we're dealing with
        // a permission requirement on this *method* which depends on the value
        // supplied by this parameter
        checkParameterPermission(context, signature, call, method, argument);
    } else {
        // We only run @IntDef, @StringDef and @<Type>Res checks if we're not
        // running inside Android Studio / IntelliJ where there are already inspections
        // covering the same warnings (using IntelliJ's own data flow analysis); we
        // don't want to (a) create redundant warnings or (b) work harder than we
        // have to
        if (signature.equals(INT_DEF_ANNOTATION)) {
            boolean flag = annotation.getValue(TYPE_DEF_FLAG_ATTRIBUTE) == Boolean.TRUE;
            checkTypeDefConstant(context, annotation, argument, null, flag, allAnnotations);
        } else if (signature.equals(STRING_DEF_ANNOTATION)) {
            checkTypeDefConstant(context, annotation, argument, null, false, allAnnotations);
        } else if (signature.endsWith(RES_SUFFIX)) {
            String typeString = signature.substring(SUPPORT_ANNOTATIONS_PREFIX.length(),
                    signature.length() - RES_SUFFIX.length()).toLowerCase(Locale.US);
            ResourceType type = ResourceType.getEnum(typeString);
            if (type != null) {
                checkResourceType(context, argument, type);
            } else if (typeString.equals("any")) { // @AnyRes
                checkResourceType(context, argument, null);
            }
        }
    }
}
 
Example 20
Source File: AndroidCompiledDataDeserializer.java    From bazel with Apache License 2.0 4 votes vote down vote up
private static void consumeResourceTable(
    DependencyInfo dependencyInfo,
    KeyValueConsumers consumers,
    ResourceTable resourceTable,
    VisibilityRegistry registry)
    throws UnsupportedEncodingException, InvalidProtocolBufferException {
  List<String> sourcePool =
      decodeSourcePool(resourceTable.getSourcePool().getData().toByteArray());
  ReferenceResolver resolver = ReferenceResolver.asRoot();

  for (Package resourceTablePackage : resourceTable.getPackageList()) {
    ReferenceResolver packageResolver =
        resolver.resolveFor(resourceTablePackage.getPackageName());
    String packageName = resourceTablePackage.getPackageName();

    for (Resources.Type resourceFormatType : resourceTablePackage.getTypeList()) {
      ResourceType resourceType = ResourceType.getEnum(resourceFormatType.getName());

      for (Resources.Entry resource : resourceFormatType.getEntryList()) {
        if (!"android".equals(packageName)) {
          // This means this resource is not in the android sdk, add it to the set.
          for (ConfigValue configValue : resource.getConfigValueList()) {
            FullyQualifiedName fqn =
                createAndRecordFqn(
                    packageResolver,
                    packageName,
                    resourceType,
                    resource,
                    convertToQualifiers(configValue.getConfig()));
            Visibility visibility =
                registry.getVisibility(
                    ResourceName.create(packageName, resourceType, resource.getName()));

            int sourceIndex = configValue.getValue().getSource().getPathIdx();
            String source = sourcePool.get(sourceIndex);
            DataSource dataSource = DataSource.of(dependencyInfo, Paths.get(source));

            Value resourceValue = configValue.getValue();
            DataResource dataResource =
                resourceValue.getItem().hasFile()
                    ? DataValueFile.of(
                        visibility, dataSource, /*fingerprint=*/ null, /*rootXmlNode=*/ null)
                    : DataResourceXml.from(
                        resourceValue, visibility, dataSource, resourceType, packageResolver);

            if (!fqn.isOverwritable()) {
              consumers.combiningConsumer.accept(fqn, dataResource);
            } else {
              consumers.overwritingConsumer.accept(fqn, dataResource);
            }
          }
        } else {
          // In the sdk, just add the fqn for styleables
          createAndRecordFqn(
              packageResolver, packageName, resourceType, resource, ImmutableList.of());
        }
      }
    }
  }
}