Java Code Examples for com.android.utils.Pair#of()

The following examples show how to use com.android.utils.Pair#of() . 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: LayoutlibVersionMixin.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Parses an XML node to process the {@code <layoutlib>} element.
 *
 * The layoutlib element is new in the XSD rev 4, so we need to cope with it missing
 * in earlier XMLs.
 */
public LayoutlibVersionMixin(Node pkgNode) {

    int api = LAYOUTLIB_API_NOT_SPECIFIED;
    int rev = LAYOUTLIB_REV_NOT_SPECIFIED;

    Node layoutlibNode =
        PackageParserUtils.findChildElement(pkgNode, RepoConstants.NODE_LAYOUT_LIB);

    if (layoutlibNode != null) {
        api = PackageParserUtils.getXmlInt(layoutlibNode, RepoConstants.NODE_API, 0);
        rev = PackageParserUtils.getXmlInt(layoutlibNode, RepoConstants.NODE_REVISION, 0);
    }

    mLayoutlibVersion = Pair.of(api, rev);
}
 
Example 2
Source File: LintGradleProject.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a {@link LintGradleProject} from
 * the given {@link com.android.builder.model.AndroidProject} definition for
 * a given {@link com.android.builder.model.Variant}, and returns it along with
 * a set of lint custom rule jars applicable for the given model project.
 *
 * @param client        the client
 * @param project       the model project
 * @param variant       the variant
 * @param gradleProject the gradle project
 * @return a pair of new project and list of custom rule jars
 */
@NonNull
public static Pair<LintGradleProject, List<File>> create(
        @NonNull LintGradleClient client,
        @NonNull AndroidProject project,
        @NonNull Variant variant,
        @NonNull org.gradle.api.Project gradleProject) {
    File dir = gradleProject.getProjectDir();
    AppGradleProject lintProject = new AppGradleProject(client, dir,
            dir, project, variant);

    List<File> customRules = Lists.newArrayList();
    File appLintJar = new File(gradleProject.getBuildDir(),
            "lint" + separatorChar + "lint.jar");
    if (appLintJar.exists()) {
        customRules.add(appLintJar);
    }

    Set<AndroidLibrary> libraries = Sets.newHashSet();
    Dependencies dependencies = variant.getMainArtifact().getDependencies();
    for (AndroidLibrary library : dependencies.getLibraries()) {
        lintProject.addDirectLibrary(createLibrary(client, library, libraries, customRules));
    }

    return Pair.<LintGradleProject, List<File>>of(lintProject, customRules);
}
 
Example 3
Source File: LayoutlibVersionMixin.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Parses an XML node to process the {@code <layoutlib>} element.
 *
 * The layoutlib element is new in the XSD rev 4, so we need to cope with it missing
 * in earlier XMLs.
 */
public LayoutlibVersionMixin(Node pkgNode) {

    int api = LAYOUTLIB_API_NOT_SPECIFIED;
    int rev = LAYOUTLIB_REV_NOT_SPECIFIED;

    Node layoutlibNode =
        PackageParserUtils.findChildElement(pkgNode, RepoConstants.NODE_LAYOUT_LIB);

    if (layoutlibNode != null) {
        api = PackageParserUtils.getXmlInt(layoutlibNode, RepoConstants.NODE_API, 0);
        rev = PackageParserUtils.getXmlInt(layoutlibNode, RepoConstants.NODE_REVISION, 0);
    }

    mLayoutlibVersion = Pair.of(api, rev);
}
 
Example 4
Source File: LayoutlibVersionMixin.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the layoutlib version optionally available in the given {@link Properties}.
 */
public LayoutlibVersionMixin(Properties props) {
    int layoutlibApi = Package.getPropertyInt(props, PkgProps.LAYOUTLIB_API,
                                                     LAYOUTLIB_API_NOT_SPECIFIED);
    int layoutlibRev = Package.getPropertyInt(props, PkgProps.LAYOUTLIB_REV,
                                                     LAYOUTLIB_REV_NOT_SPECIFIED);
    mLayoutlibVersion = Pair.of(layoutlibApi, layoutlibRev);
}
 
Example 5
Source File: ClientCellRenderer.java    From logviewer with Apache License 2.0 5 votes vote down vote up
/**
 * Split the name if possible as package and app name
 */
private Pair<String, String> splitApplicationName(String name) {
    int index = name.lastIndexOf('.');
    if (index != -1) {
        return Pair.of(name.substring(0, index + 1), name.substring(index + 1));
    } else {
        return Pair.of("", name);
    }
}
 
Example 6
Source File: ExtractAnnotationsDriver.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@NonNull
private static Pair<Collection<CompilationUnitDeclaration>, INameEnvironment> parseSources(
        @NonNull List<File> sourcePaths,
        @NonNull List<String> classpath,
        @NonNull String encoding,
        long languageLevel)
        throws IOException {
    List<ICompilationUnit> sourceUnits = Lists.newArrayListWithExpectedSize(100);

    for (File source : gatherJavaSources(sourcePaths)) {
        char[] contents = Util.getFileCharContent(source, encoding);
        ICompilationUnit unit = new CompilationUnit(contents, source.getPath(), encoding);
        sourceUnits.add(unit);
    }

    Map<ICompilationUnit, CompilationUnitDeclaration> outputMap = Maps.newHashMapWithExpectedSize(
            sourceUnits.size());

    CompilerOptions options = EcjParser.createCompilerOptions();
    options.docCommentSupport = true; // So I can find @hide

    // Note: We can *not* set options.ignoreMethodBodies=true because it disables
    // type attribution!

    options.sourceLevel = languageLevel;
    options.complianceLevel = options.sourceLevel;
    // We don't generate code, but just in case the parser consults this flag
    // and makes sure that it's not greater than the source level:
    options.targetJDK = options.sourceLevel;
    options.originalComplianceLevel = options.sourceLevel;
    options.originalSourceLevel = options.sourceLevel;
    options.inlineJsrBytecode = true; // >= 1.5

    INameEnvironment environment = EcjParser.parse(options, sourceUnits, classpath,
            outputMap, null);
    Collection<CompilationUnitDeclaration> parsedUnits = outputMap.values();
    return Pair.of(parsedUnits, environment);
}
 
Example 7
Source File: LayoutlibVersionMixin.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Parses the layoutlib version optionally available in the given {@link Properties}.
 */
public LayoutlibVersionMixin(Properties props) {
    int layoutlibApi = Package.getPropertyInt(props, PkgProps.LAYOUTLIB_API,
                                                     LAYOUTLIB_API_NOT_SPECIFIED);
    int layoutlibRev = Package.getPropertyInt(props, PkgProps.LAYOUTLIB_REV,
                                                     LAYOUTLIB_REV_NOT_SPECIFIED);
    mLayoutlibVersion = Pair.of(layoutlibApi, layoutlibRev);
}
 
Example 8
Source File: ApkUtils.java    From NBANDROID-V2 with Apache License 2.0 5 votes vote down vote up
private static Pair<PrivateKey, X509Certificate> generateKeyAndCertificate(String asymmetric, String sign, int validityYears, String dn) throws NoSuchAlgorithmException, OperatorCreationException, CertificateException {
    Preconditions.checkArgument(validityYears > 0, "validityYears <= 0");
    KeyPair keyPair = KeyPairGenerator.getInstance(asymmetric).generateKeyPair();
    Date notBefore = new Date(System.currentTimeMillis());
    Date notAfter = new Date(System.currentTimeMillis() + validityYears * 31536000000l);
    X500Name issuer = new X500Name(new X500Principal(dn).getName());
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    X509v1CertificateBuilder builder = new X509v1CertificateBuilder(issuer, BigInteger.ONE, notBefore, notAfter, issuer, publicKeyInfo);
    ContentSigner signer = new JcaContentSignerBuilder(sign).setProvider(new BouncyCastleProvider()).build(keyPair.getPrivate());
    X509CertificateHolder holder = builder.build(signer);
    JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider());
    X509Certificate certificate = converter.getCertificate(holder);
    return Pair.of(keyPair.getPrivate(), certificate);
}
 
Example 9
Source File: DownloadCache.java    From java-n-IDE-for-Android with Apache License 2.0 4 votes vote down vote up
/**
 * This is a simplified convenience method that calls
 * {@link #openDirectUrl(String, Header[], ITaskMonitor)}
 * without passing any specific HTTP headers  and returns the resulting input stream
 * and the HTTP status code.
 * See the original method's description for details on its behavior.
 * <p/>
 * {@link #openDirectUrl(String, Header[], ITaskMonitor)} can accept customized
 * HTTP headers to send with the requests and also returns the full HTTP
 * response -- status line with code and protocol and all headers.
 * <p/>
 * The resulting input stream may not support mark/reset.
 *
 * @param urlString the URL string to be opened.
 * @param monitor {@link ITaskMonitor} which is related to this URL
 *                 fetching.
 * @return Returns a pair with a {@link InputStream} and an HTTP status code.
 *              The pair is never null.
 *              The input stream can be null in case of error, although in general the
 *              method will probably throw an exception instead.
 *              The caller should look at the response code's status and only accept the
 *              input stream if it's the desired code (e.g. 200 or 206).
 * @throws IOException Exception thrown when there are problems retrieving
 *                 the URL or its content.
 * @throws CanceledByUserException Exception thrown if the user cancels the
 *              authentication dialog.
 * @see #openDirectUrl(String, Header[], ITaskMonitor)
 */
@NonNull
public Pair<InputStream, Integer> openDirectUrl(
        @NonNull  String urlString,
        @NonNull  ITaskMonitor monitor)
            throws IOException, CanceledByUserException {
    if (DEBUG) {
        System.out.println(String.format("%s : Direct download", urlString)); //$NON-NLS-1$
    }
    Pair<InputStream, HttpResponse> result = openUrl(
            urlString,
            false /*needsMarkResetSupport*/,
            monitor,
            null /*headers*/);
    return Pair.of(result.getFirst(), result.getSecond().getStatusLine().getStatusCode());
}
 
Example 10
Source File: AvdManager.java    From java-n-IDE-for-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Returns whether this AVD name would generate a conflict.
 *
 * @param name the name of the AVD to return
 * @return A pair of {@link AvdConflict} and the path or AVD name that conflicts.
 */
@NonNull
public Pair<AvdConflict, String> isAvdNameConflicting(@Nullable String name) {

    boolean ignoreCase = SdkConstants.currentPlatform() == SdkConstants.PLATFORM_WINDOWS;

    // Check whether we have a conflict with an existing or invalid AVD
    // known to the manager.
    synchronized (mAllAvdList) {
        for (AvdInfo info : mAllAvdList) {
            String name2 = info.getName();
            if (name2.equals(name) || (ignoreCase && name2.equalsIgnoreCase(name))) {
                if (info.getStatus() == AvdStatus.OK) {
                    return Pair.of(AvdConflict.CONFLICT_EXISTING_AVD, name2);
                } else {
                    return Pair.of(AvdConflict.CONFLICT_INVALID_AVD, name2);
                }
            }
        }
    }

    // No conflict with known AVDs.
    // Are some existing files/folders in the way of creating this AVD?

    try {
        File file = AvdInfo.getDefaultIniFile(this, name);
        if (file.exists()) {
            return Pair.of(AvdConflict.CONFLICT_EXISTING_PATH, file.getPath());
        }

        file = AvdInfo.getDefaultAvdFolder(this, name);
        if (file.exists()) {
            return Pair.of(AvdConflict.CONFLICT_EXISTING_PATH, file.getPath());
        }

    } catch (AndroidLocationException e) {
        // ignore
    }


    return Pair.of(AvdConflict.NO_CONFLICT, null);
}
 
Example 11
Source File: ExtractAnnotations.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
@NonNull
private Pair<Collection<CompilationUnitDeclaration>, INameEnvironment> parseSources() {
    final List<ICompilationUnit> sourceUnits = Lists.newArrayListWithExpectedSize(100);

    getSource().visit(new EmptyFileVisitor() {
        @Override
        public void visitFile(FileVisitDetails fileVisitDetails) {
            File file = fileVisitDetails.getFile();
            String path = file.getPath();
            if (path.endsWith(DOT_JAVA) && file.isFile()) {
                char[] contents = new char[0];
                try {
                    contents = Util.getFileCharContent(file, encoding);
                    ICompilationUnit unit = new CompilationUnit(contents, path, encoding);
                    sourceUnits.add(unit);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    });

    Map<ICompilationUnit, CompilationUnitDeclaration> outputMap = Maps.newHashMapWithExpectedSize(((ArrayList<ICompilationUnit>) sourceUnits).size());
    List<String> jars = Lists.newArrayList();
    if (bootClasspath != null) {
        ((ArrayList<String>) jars).addAll(bootClasspath);
    }

    if (getClasspath() != null) {
        for (File jar : getClasspath()) {
            ((ArrayList<String>) jars).add(jar.getPath());
        }

    }


    CompilerOptions options = EcjParser.createCompilerOptions();
    options.docCommentSupport = true;// So I can find @hide

    // Note: We can *not* set options.ignoreMethodBodies=true because it disables
    // type attribution!

    long level = getLanguageLevel(getSourceCompatibility());
    options.sourceLevel = level;
    options.complianceLevel = options.sourceLevel;
    // We don't generate code, but just in case the parser consults this flag
    // and makes sure that it's not greater than the source level:
    options.targetJDK = options.sourceLevel;
    options.originalComplianceLevel = options.sourceLevel;
    options.originalSourceLevel = options.sourceLevel;
    options.inlineJsrBytecode = true;// >= 1.5

    INameEnvironment environment = EcjParser.parse(options, sourceUnits, jars, outputMap, null);
    Collection<CompilationUnitDeclaration> parsedUnits = ((HashMap<ICompilationUnit, CompilationUnitDeclaration>) outputMap).values();
    return Pair.of(parsedUnits, environment);
}
 
Example 12
Source File: DownloadCache.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/**
 * This is a simplified convenience method that calls
 * {@link #openDirectUrl(String, Header[], ITaskMonitor)}
 * without passing any specific HTTP headers  and returns the resulting input stream
 * and the HTTP status code.
 * See the original method's description for details on its behavior.
 * <p/>
 * {@link #openDirectUrl(String, Header[], ITaskMonitor)} can accept customized
 * HTTP headers to send with the requests and also returns the full HTTP
 * response -- status line with code and protocol and all headers.
 * <p/>
 * The resulting input stream may not support mark/reset.
 *
 * @param urlString the URL string to be opened.
 * @param monitor {@link ITaskMonitor} which is related to this URL
 *                 fetching.
 * @return Returns a pair with a {@link InputStream} and an HTTP status code.
 *              The pair is never null.
 *              The input stream can be null in case of error, although in general the
 *              method will probably throw an exception instead.
 *              The caller should look at the response code's status and only accept the
 *              input stream if it's the desired code (e.g. 200 or 206).
 * @throws IOException Exception thrown when there are problems retrieving
 *                 the URL or its content.
 * @throws CanceledByUserException Exception thrown if the user cancels the
 *              authentication dialog.
 * @see #openDirectUrl(String, Header[], ITaskMonitor)
 */
@NonNull
public Pair<InputStream, Integer> openDirectUrl(
        @NonNull  String urlString,
        @NonNull  ITaskMonitor monitor)
            throws IOException, CanceledByUserException {
    if (DEBUG) {
        System.out.println(String.format("%s : Direct download", urlString)); //$NON-NLS-1$
    }
    Pair<InputStream, HttpResponse> result = openUrl(
            urlString,
            false /*needsMarkResetSupport*/,
            monitor,
            null /*headers*/);
    return Pair.of(result.getFirst(), result.getSecond().getStatusLine().getStatusCode());
}
 
Example 13
Source File: PreProcessCache.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Returns an {@link Item} loaded from the cache. If no item can be found this, throws an
 * exception.
 *
 * @param itemKey the key of the item
 * @return a pair of item, boolean
 */
protected synchronized Pair<Item, Boolean> getItem(@NonNull T itemKey) {

    // get the item
    Item item = mMap.get(itemKey);

    boolean newItem = false;

    if (item == null) {
        // check if we have a stored version.
        StoredItem storedItem = mStoredItems.get(itemKey);

        File inputFile = itemKey.getSourceFile();

        if (storedItem != null) {
            // check the sha1 is still valid, and the pre-dex files are still there.
            if (storedItem.areOutputFilesPresent() &&
                    storedItem.getSourceHash().equals(getHash(inputFile))) {

                Logger.getAnonymousLogger().info("Cached result for getItem(" + inputFile + "): "
                        + storedItem.getOutputFiles());
                for (File f : storedItem.getOutputFiles()) {
                    Logger.getAnonymousLogger().info(
                            String.format("%s l:%d ts:%d", f, f.length(), f.lastModified()));
                }

                // create an item where the outFile is the one stored since it
                // represent the pre-dexed library already.
                // Next time this lib needs to be pre-dexed, we'll use the item
                // rather than the stored item, allowing us to not compute the sha1 again.
                // Use a 0-count latch since there is nothing to do.
                item = new Item(inputFile, storedItem.getOutputFiles(), new CountDownLatch(0));
            }
        }

        // if we didn't find a valid stored item, create a new one.
        if (item == null) {
            item = new Item(inputFile, new CountDownLatch(1));
            newItem = true;
        }

        mMap.put(itemKey, item);
    }

    return Pair.of(item, newItem);
}
 
Example 14
Source File: ResourceUsageAnalyzer.java    From bazel with Apache License 2.0 4 votes vote down vote up
private void parseResourceTxtFile(Path rTxt, Set<String> resourcePackages) throws IOException {
  BufferedReader reader = java.nio.file.Files.newBufferedReader(rTxt, UTF_8);
  String line;
  while ((line = reader.readLine()) != null) {
    String[] tokens = line.split(" ");
    ResourceType type = ResourceType.getEnum(tokens[1]);
    for (String resourcePackage : resourcePackages) {
      String owner = resourcePackage.replace('.', '/') + "/R$" + type.getName();
      Pair<ResourceType, Map<String, String>> pair = resourceObfuscation.get(owner);
      if (pair == null) {
        Map<String, String> nameMap = Maps.newHashMap();
        pair = Pair.of(type, nameMap);
      }
      resourceObfuscation.put(owner, pair);
    }
    if (type == ResourceType.STYLEABLE) {
      if (tokens[0].equals("int[]")) {
        ArrayList<Integer> values = new ArrayList<>();
        for (int i = 4; ; ++i) { // skip tokens "int[] identifier = {"
          String token = tokens[i];
          if (token.equals("}")) {
            // empty set?
            break;
          }

          if (token.endsWith(",")) {
            // strip trailing comma
            token = token.substring(0, token.length() - 1);
            values.add(Integer.decode(token));
          } else {
            values.add(Integer.decode(token));
            // no comma means that this is the last value
            break;
          }
        }

        styleableToAttrs.put(tokens[2], values);
        model.addResource(ResourceType.DECLARE_STYLEABLE, tokens[2], null);
      } else {
        // TODO(jongerrish): Implement stripping of styleables.
      }
    } else {
      model.addResource(type, tokens[2], tokens[3]);
    }
  }
}