Example usage for com.google.common.collect ImmutableList isEmpty

List of usage examples for com.google.common.collect ImmutableList isEmpty

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableList isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this list contains no elements.

Usage

From source file:com.facebook.buck.apple.toolchain.impl.AppleCxxPlatforms.java

@VisibleForTesting
public static AppleCxxPlatform buildWithXcodeToolFinder(ProjectFilesystem filesystem, AppleSdk targetSdk,
        String minVersion, String targetArchitecture, AppleSdkPaths sdkPaths, BuckConfig buckConfig,
        XcodeToolFinder xcodeToolFinder, XcodeBuildVersionCache xcodeBuildVersionCache) {
    AppleCxxPlatform.Builder platformBuilder = AppleCxxPlatform.builder();

    ImmutableList.Builder<Path> toolSearchPathsBuilder = ImmutableList.builder();
    // Search for tools from most specific to least specific.
    toolSearchPathsBuilder.add(sdkPaths.getSdkPath().resolve(USR_BIN))
            .add(sdkPaths.getSdkPath().resolve("Developer").resolve(USR_BIN))
            .add(sdkPaths.getPlatformPath().resolve("Developer").resolve(USR_BIN));
    for (Path toolchainPath : sdkPaths.getToolchainPaths()) {
        toolSearchPathsBuilder.add(toolchainPath.resolve(USR_BIN));
    }/*  w  ww  . ja va2s  .co m*/
    if (sdkPaths.getDeveloperPath().isPresent()) {
        toolSearchPathsBuilder.add(sdkPaths.getDeveloperPath().get().resolve(USR_BIN));
        toolSearchPathsBuilder.add(sdkPaths.getDeveloperPath().get().resolve("Tools"));
    }

    // TODO(beng): Add more and better cflags.
    ImmutableList.Builder<String> cflagsBuilder = ImmutableList.builder();
    cflagsBuilder.add("-isysroot", sdkPaths.getSdkPath().toString());
    cflagsBuilder.add("-arch", targetArchitecture);
    cflagsBuilder.add(targetSdk.getApplePlatform().getMinVersionFlagPrefix() + minVersion);

    if (targetSdk.getApplePlatform().equals(ApplePlatform.WATCHOS)) {
        cflagsBuilder.add("-fembed-bitcode");
    }

    AppleConfig appleConfig = buckConfig.getView(AppleConfig.class);

    ImmutableList.Builder<String> ldflagsBuilder = ImmutableList.builder();
    ldflagsBuilder.addAll(Linkers.iXlinker("-sdk_version", targetSdk.getVersion()));
    if (appleConfig.linkAllObjC()) {
        ldflagsBuilder.addAll(Linkers.iXlinker("-ObjC"));
    }
    if (targetSdk.getApplePlatform().equals(ApplePlatform.WATCHOS)) {
        ldflagsBuilder.addAll(Linkers.iXlinker("-bitcode_verify"));
    }

    // Populate Xcode version keys from Xcode's own Info.plist if available.
    Optional<String> xcodeBuildVersion = Optional.empty();
    Optional<Path> developerPath = sdkPaths.getDeveloperPath();
    if (developerPath.isPresent()) {
        Path xcodeBundlePath = developerPath.get().getParent();
        if (xcodeBundlePath != null) {
            Path xcodeInfoPlistPath = xcodeBundlePath.resolve("Info.plist");
            try (InputStream stream = Files.newInputStream(xcodeInfoPlistPath)) {
                NSDictionary parsedXcodeInfoPlist = (NSDictionary) PropertyListParser.parse(stream);

                NSObject xcodeVersionObject = parsedXcodeInfoPlist.objectForKey("DTXcode");
                if (xcodeVersionObject != null) {
                    Optional<String> xcodeVersion = Optional.of(xcodeVersionObject.toString());
                    platformBuilder.setXcodeVersion(xcodeVersion);
                }
            } catch (IOException e) {
                LOG.warn("Error reading Xcode's info plist %s; ignoring Xcode versions", xcodeInfoPlistPath);
            } catch (PropertyListFormatException | ParseException | ParserConfigurationException
                    | SAXException e) {
                LOG.warn("Error in parsing %s; ignoring Xcode versions", xcodeInfoPlistPath);
            }
        }

        xcodeBuildVersion = xcodeBuildVersionCache.lookup(developerPath.get());
        platformBuilder.setXcodeBuildVersion(xcodeBuildVersion);
        LOG.debug("Xcode build version is: " + xcodeBuildVersion.orElse("<absent>"));
    }

    ImmutableList.Builder<String> versions = ImmutableList.builder();
    versions.add(targetSdk.getVersion());

    ImmutableList<String> toolchainVersions = targetSdk.getToolchains().stream().map(AppleToolchain::getVersion)
            .flatMap(Optionals::toStream).collect(ImmutableList.toImmutableList());
    if (toolchainVersions.isEmpty()) {
        if (!xcodeBuildVersion.isPresent()) {
            throw new HumanReadableException("Failed to read toolchain versions and Xcode version.");
        }
        versions.add(xcodeBuildVersion.get());
    } else {
        versions.addAll(toolchainVersions);
    }

    String version = Joiner.on(':').join(versions.build());

    ImmutableList<Path> toolSearchPaths = toolSearchPathsBuilder.build();

    Tool clangPath = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "clang", version);

    Tool clangXxPath = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "clang++",
            version);

    Tool ar = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "ar", version);

    Tool ranlib = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "ranlib", version);

    Tool strip = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "strip", version);

    Tool nm = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "nm", version);

    Tool actool = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "actool", version);

    Tool ibtool = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "ibtool", version);

    Tool momc = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "momc", version);

    Tool xctest = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "xctest", version);

    Tool dsymutil = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "dsymutil",
            version);

    Tool lipo = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "lipo", version);

    Tool lldb = getXcodeTool(filesystem, toolSearchPaths, xcodeToolFinder, appleConfig, "lldb", version);

    Optional<Path> stubBinaryPath = targetSdk.getApplePlatform().getStubBinaryPath()
            .map(input -> sdkPaths.getSdkPath().resolve(input));

    UserFlavor targetFlavor = UserFlavor.of(
            Flavor.replaceInvalidCharacters(targetSdk.getName() + "-" + targetArchitecture),
            String.format("SDK: %s, architecture: %s", targetSdk.getName(), targetArchitecture));
    CxxBuckConfig config = appleConfig.useFlavoredCxxSections() ? new CxxBuckConfig(buckConfig, targetFlavor)
            : new CxxBuckConfig(buckConfig);

    ImmutableBiMap.Builder<Path, String> sanitizerPaths = ImmutableBiMap.builder();
    sanitizerPaths.put(sdkPaths.getSdkPath(), "APPLE_SDKROOT");
    sanitizerPaths.put(sdkPaths.getPlatformPath(), "APPLE_PLATFORM_DIR");
    if (sdkPaths.getDeveloperPath().isPresent()) {
        sanitizerPaths.put(sdkPaths.getDeveloperPath().get(), "APPLE_DEVELOPER_DIR");
    }

    // https://github.com/facebook/buck/pull/1168: add the root cell's absolute path to the quote
    // include path, and also force it to be sanitized by all user rule keys.
    sanitizerPaths.put(filesystem.getRootPath(), ".");
    cflagsBuilder.add("-iquote", filesystem.getRootPath().toString());

    DebugPathSanitizer compilerDebugPathSanitizer = new PrefixMapDebugPathSanitizer(
            DebugPathSanitizer.getPaddedDir(".", config.getDebugPathSanitizerLimit(), File.separatorChar),
            sanitizerPaths.build());
    DebugPathSanitizer assemblerDebugPathSanitizer = new MungingDebugPathSanitizer(
            config.getDebugPathSanitizerLimit(), File.separatorChar, Paths.get("."), sanitizerPaths.build());

    ImmutableList<String> cflags = cflagsBuilder.build();

    ImmutableMap.Builder<String, String> macrosBuilder = ImmutableMap.builder();
    macrosBuilder.put("SDKROOT", sdkPaths.getSdkPath().toString());
    macrosBuilder.put("PLATFORM_DIR", sdkPaths.getPlatformPath().toString());
    macrosBuilder.put("CURRENT_ARCH", targetArchitecture);
    if (sdkPaths.getDeveloperPath().isPresent()) {
        macrosBuilder.put("DEVELOPER_DIR", sdkPaths.getDeveloperPath().get().toString());
    }
    ImmutableMap<String, String> macros = macrosBuilder.build();

    Optional<String> buildVersion = Optional.empty();
    Path platformVersionPlistPath = sdkPaths.getPlatformPath().resolve("version.plist");
    try (InputStream versionPlist = Files.newInputStream(platformVersionPlistPath)) {
        NSDictionary versionInfo = (NSDictionary) PropertyListParser.parse(versionPlist);
        if (versionInfo != null) {
            NSObject productBuildVersion = versionInfo.objectForKey("ProductBuildVersion");
            if (productBuildVersion != null) {
                buildVersion = Optional.of(productBuildVersion.toString());
            } else {
                LOG.warn("In %s, missing ProductBuildVersion. Build version will be unset for this platform.",
                        platformVersionPlistPath);
            }
        } else {
            LOG.warn("Empty version plist in %s. Build version will be unset for this platform.",
                    platformVersionPlistPath);
        }
    } catch (NoSuchFileException e) {
        LOG.warn("%s does not exist. Build version will be unset for this platform.", platformVersionPlistPath);
    } catch (PropertyListFormatException | SAXException | ParserConfigurationException | ParseException
            | IOException e) {
        // Some other error occurred, print the exception since it may contain error details.
        LOG.warn(e, "Failed to parse %s. Build version will be unset for this platform.",
                platformVersionPlistPath);
    }

    PreprocessorProvider aspp = new PreprocessorProvider(new ConstantToolProvider(clangPath),
            CxxToolProvider.Type.CLANG);
    CompilerProvider as = new CompilerProvider(new ConstantToolProvider(clangPath), CxxToolProvider.Type.CLANG,
            config.getUseDetailedUntrackedHeaderMessages());
    PreprocessorProvider cpp = new PreprocessorProvider(new ConstantToolProvider(clangPath),
            CxxToolProvider.Type.CLANG);
    CompilerProvider cc = new CompilerProvider(new ConstantToolProvider(clangPath), CxxToolProvider.Type.CLANG,
            config.getUseDetailedUntrackedHeaderMessages());
    PreprocessorProvider cxxpp = new PreprocessorProvider(new ConstantToolProvider(clangXxPath),
            CxxToolProvider.Type.CLANG);
    CompilerProvider cxx = new CompilerProvider(new ConstantToolProvider(clangXxPath),
            CxxToolProvider.Type.CLANG, config.getUseDetailedUntrackedHeaderMessages());
    ImmutableList.Builder<String> whitelistBuilder = ImmutableList.builder();
    whitelistBuilder.add("^" + Pattern.quote(sdkPaths.getSdkPath().toString()) + "\\/.*");
    whitelistBuilder
            .add("^" + Pattern.quote(sdkPaths.getPlatformPath() + "/Developer/Library/Frameworks") + "\\/.*");
    for (Path toolchainPath : sdkPaths.getToolchainPaths()) {
        LOG.debug("Apple toolchain path: %s", toolchainPath);
        try {
            whitelistBuilder.add("^" + Pattern.quote(toolchainPath.toRealPath().toString()) + "\\/.*");
        } catch (IOException e) {
            LOG.warn(e, "Apple toolchain path could not be resolved: %s", toolchainPath);
        }
    }
    HeaderVerification headerVerification = config.getHeaderVerificationOrIgnore()
            .withPlatformWhitelist(whitelistBuilder.build());
    LOG.debug("Headers verification platform whitelist: %s", headerVerification.getPlatformWhitelist());

    CxxPlatform cxxPlatform = CxxPlatforms.build(targetFlavor, Platform.MACOS, config, as, aspp, cc, cxx, cpp,
            cxxpp,
            new DefaultLinkerProvider(LinkerProvider.Type.DARWIN, new ConstantToolProvider(clangXxPath),
                    config.shouldCacheLinks()),
            ImmutableList.<String>builder().addAll(cflags).addAll(ldflagsBuilder.build()).build(),
            ImmutableMultimap.of(), strip, ArchiverProvider.from(new BsdArchiver(ar)), ArchiveContents.NORMAL,
            Optional.of(new ConstantToolProvider(ranlib)), new PosixNmSymbolNameTool(nm), cflagsBuilder.build(),
            ImmutableList.of(), cflags, ImmutableList.of(), cflags, ImmutableList.of(), "dylib", "%s.dylib",
            "a", "o", compilerDebugPathSanitizer, assemblerDebugPathSanitizer, macros, Optional.empty(),
            headerVerification, PicType.PIC);

    ApplePlatform applePlatform = targetSdk.getApplePlatform();
    ImmutableList.Builder<Path> swiftOverrideSearchPathBuilder = ImmutableList.builder();
    AppleSdkPaths.Builder swiftSdkPathsBuilder = AppleSdkPaths.builder().from(sdkPaths);
    Optional<SwiftPlatform> swiftPlatform = getSwiftPlatform(applePlatform.getName(),
            targetArchitecture + "-apple-" + applePlatform.getSwiftName().orElse(applePlatform.getName())
                    + minVersion,
            version, swiftSdkPathsBuilder.build(),
            swiftOverrideSearchPathBuilder.addAll(toolSearchPaths).build(), xcodeToolFinder, filesystem);

    platformBuilder.setCxxPlatform(cxxPlatform).setSwiftPlatform(swiftPlatform).setAppleSdk(targetSdk)
            .setAppleSdkPaths(sdkPaths).setMinVersion(minVersion).setBuildVersion(buildVersion)
            .setActool(actool).setIbtool(ibtool).setMomc(momc)
            .setCopySceneKitAssets(getOptionalTool("copySceneKitAssets", toolSearchPaths, xcodeToolFinder,
                    version, filesystem))
            .setXctest(xctest).setDsymutil(dsymutil).setLipo(lipo).setStubBinary(stubBinaryPath).setLldb(lldb)
            .setCodesignAllocate(
                    getOptionalTool("codesign_allocate", toolSearchPaths, xcodeToolFinder, version, filesystem))
            .setCodesignProvider(appleConfig.getCodesignProvider());

    return platformBuilder.build();
}

From source file:com.google.devtools.build.lib.rules.java.JavaCommon.java

private static String determinePrimaryClass(Target target, ImmutableList<Artifact> sourceFiles) {
    if (!sourceFiles.isEmpty()) {
        String mainSource = target.getName() + ".java";
        for (Artifact sourceFile : sourceFiles) {
            PathFragment path = sourceFile.getRootRelativePath();
            if (path.getBaseName().equals(mainSource)) {
                return JavaUtil.getJavaFullClassname(FileSystemUtils.removeExtension(path));
            }/* w w w .  j a v a2 s .c o m*/
        }
    }
    // Last resort: Use the name and package name of the target.
    // TODO(bazel-team): this should be fixed to use a source file from the dependencies to
    // determine the package of the Java class.
    return JavaUtil.getJavaFullClassname(Util.getWorkspaceRelativePath(target));
}

From source file:com.facebook.buck.android.ExopackageInstaller.java

/**
 * Breaks a list of strings into groups whose total size is within some limit.
 * Kind of like the xargs command that groups arguments to avoid maximum argument length limits.
 * Except that the limit in adb is about 1k instead of 512k or 2M on Linux.
 *///from  ww w  .  j  a  v  a  2  s . c  o m
@VisibleForTesting
static ImmutableList<ImmutableList<String>> chunkArgs(Iterable<String> args, int sizeLimit) {
    ImmutableList.Builder<ImmutableList<String>> topLevelBuilder = ImmutableList.builder();
    ImmutableList.Builder<String> chunkBuilder = ImmutableList.builder();
    int chunkSize = 0;
    for (String arg : args) {
        if (chunkSize + arg.length() > sizeLimit) {
            topLevelBuilder.add(chunkBuilder.build());
            chunkBuilder = ImmutableList.builder();
            chunkSize = 0;
        }
        // We don't check for an individual arg greater than the limit.
        // We just put it in its own chunk and hope for the best.
        chunkBuilder.add(arg);
        chunkSize += arg.length();
    }
    ImmutableList<String> tail = chunkBuilder.build();
    if (!tail.isEmpty()) {
        topLevelBuilder.add(tail);
    }
    return topLevelBuilder.build();
}

From source file:com.getbase.android.schema.Schemas.java

private static void validateTableOperations(String tableName,
        ImmutableList<? extends TableOperation> operations) {
    Preconditions.checkArgument(!operations.isEmpty(), "Schema part should contain at least one operation");

    List<TableOperationId> ids = Lists.newArrayList();
    for (TableOperation operation : operations) {
        ids.add(operation.getId());/*from   www .java  2s .  c o m*/
    }

    if (ids.contains(DropTable.DROP_TABLE_OPERATION_ID)) {
        Preconditions.checkArgument(operations.size() == 1,
                "DropTable operation in downgrade definition for table " + tableName
                        + " cannot be mixed with other operations");
    }
    Preconditions.checkArgument(Sets.newHashSet(ids).size() == ids.size(),
            "Duplicate operations on single column or constraint in " + tableName);
}

From source file:com.google.javascript.jscomp.PolymerClassDefinition.java

/**
 * Validates the class definition and if valid, destructively extracts the class definition from
 * the AST./*from  w w  w .  ja v a  2 s. c o  m*/
 */
@Nullable
static PolymerClassDefinition extractFromCallNode(Node callNode, AbstractCompiler compiler,
        GlobalNamespace globalNames) {
    Node descriptor = NodeUtil.getArgumentForCallOrNew(callNode, 0);
    if (descriptor == null || !descriptor.isObjectLit()) {
        // report bad class definition
        compiler.report(JSError.make(callNode, PolymerPassErrors.POLYMER_DESCRIPTOR_NOT_VALID));
        return null;
    }

    int paramCount = callNode.getChildCount() - 1;
    if (paramCount != 1) {
        compiler.report(JSError.make(callNode, PolymerPassErrors.POLYMER_UNEXPECTED_PARAMS));
        return null;
    }

    Node elName = NodeUtil.getFirstPropMatchingKey(descriptor, "is");
    if (elName == null) {
        compiler.report(JSError.make(callNode, PolymerPassErrors.POLYMER_MISSING_IS));
        return null;
    }

    Node target;
    if (NodeUtil.isNameDeclaration(callNode.getGrandparent())) {
        target = IR.name(callNode.getParent().getString());
    } else if (callNode.getParent().isAssign()) {
        target = callNode.getParent().getFirstChild().cloneTree();
    } else {
        String elNameStringBase = elName.isQualifiedName() ? elName.getQualifiedName().replace('.', '$')
                : elName.getString();
        String elNameString = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, elNameStringBase);
        elNameString += "Element";
        target = IR.name(elNameString);
    }

    JSDocInfo classInfo = NodeUtil.getBestJSDocInfo(target);

    JSDocInfo ctorInfo = null;
    Node constructor = NodeUtil.getFirstPropMatchingKey(descriptor, "factoryImpl");
    if (constructor == null) {
        constructor = NodeUtil.emptyFunction();
        compiler.reportChangeToChangeScope(constructor);
        constructor.useSourceInfoFromForTree(callNode);
    } else {
        ctorInfo = NodeUtil.getBestJSDocInfo(constructor);
    }

    Node baseClass = NodeUtil.getFirstPropMatchingKey(descriptor, "extends");
    String nativeBaseElement = baseClass == null ? null : baseClass.getString();

    Node behaviorArray = NodeUtil.getFirstPropMatchingKey(descriptor, "behaviors");
    PolymerBehaviorExtractor behaviorExtractor = new PolymerBehaviorExtractor(compiler, globalNames);
    ImmutableList<BehaviorDefinition> behaviors = behaviorExtractor.extractBehaviors(behaviorArray);
    List<MemberDefinition> allProperties = new ArrayList<>();
    for (BehaviorDefinition behavior : behaviors) {
        overwriteMembersIfPresent(allProperties, behavior.props);
    }
    overwriteMembersIfPresent(allProperties,
            PolymerPassStaticUtils.extractProperties(descriptor, DefinitionType.ObjectLiteral, compiler,
                    /** constructor= */
                    null));

    FeatureSet newFeatures = null;
    if (!behaviors.isEmpty()) {
        newFeatures = behaviors.get(0).features;
        for (int i = 1; i < behaviors.size(); i++) {
            newFeatures = newFeatures.union(behaviors.get(i).features);
        }
    }

    List<MemberDefinition> methods = new ArrayList<>();
    for (Node keyNode : descriptor.children()) {
        boolean isFunctionDefinition = keyNode.isMemberFunctionDef()
                || (keyNode.isStringKey() && keyNode.getFirstChild().isFunction());
        if (isFunctionDefinition) {
            methods.add(
                    new MemberDefinition(NodeUtil.getBestJSDocInfo(keyNode), keyNode, keyNode.getFirstChild()));
        }
    }

    return new PolymerClassDefinition(DefinitionType.ObjectLiteral, callNode, target, descriptor, classInfo,
            new MemberDefinition(ctorInfo, null, constructor), nativeBaseElement, allProperties, methods,
            behaviors, newFeatures);
}

From source file:com.google.devtools.build.lib.rules.java.DeployArchiveBuilder.java

public static CustomCommandLine.Builder defaultSingleJarCommandLine(Artifact outputJar, String javaMainClass,
        ImmutableList<String> deployManifestLines, Iterable<Artifact> buildInfoFiles,
        ImmutableList<Artifact> classpathResources, Iterable<Artifact> runtimeClasspath,
        boolean includeBuildData, Compression compress, Artifact launcher) {

    CustomCommandLine.Builder args = CustomCommandLine.builder();
    args.addExecPath("--output", outputJar);
    if (compress == Compression.COMPRESSED) {
        args.add("--compression");
    }// w  w  w .j av  a 2s.com
    args.add("--normalize");
    if (javaMainClass != null) {
        args.add("--main_class");
        args.add(javaMainClass);
    }

    if (!deployManifestLines.isEmpty()) {
        args.add("--deploy_manifest_lines");
        args.add(deployManifestLines);
    }

    if (buildInfoFiles != null) {
        for (Artifact artifact : buildInfoFiles) {
            args.addExecPath("--build_info_file", artifact);
        }
    }
    if (!includeBuildData) {
        args.add("--exclude_build_data");
    }
    if (launcher != null) {
        args.add("--java_launcher");
        args.add(launcher.getExecPathString());
    }

    args.addExecPaths("--classpath_resources", classpathResources);
    args.addExecPaths("--sources", runtimeClasspath);
    return args;
}

From source file:com.android.tools.idea.editors.theme.ThemeEditorUtils.java

/**
 * Creates a new style by displaying the dialog of the {@link NewStyleDialog}.
 * @param defaultParentStyle is used in NewStyleDialog, will be preselected in the parent text field and name will be suggested based on it
 * @param themeEditorContext  current theme editor context
 * @param isTheme whether theme or style will be created
 * @param message is used in NewStyleDialog to display message to user
 * @return the new style name or null if the style wasn't created
 *//* w w  w. j a  va2 s  .com*/
@Nullable
public static String showCreateNewStyleDialog(@Nullable ConfiguredThemeEditorStyle defaultParentStyle,
        @NotNull final ThemeEditorContext themeEditorContext, boolean isTheme, boolean enableParentChoice,
        @Nullable final String message,
        @Nullable ThemeSelectionPanel.ThemeChangedListener themeChangedListener) {
    // if isTheme is true, defaultParentStyle shouldn't be null
    String defaultParentStyleName = null;
    if (isTheme && defaultParentStyle == null) {
        ImmutableList<String> defaultThemes = getDefaultThemeNames(themeEditorContext.getThemeResolver());
        defaultParentStyleName = !defaultThemes.isEmpty() ? defaultThemes.get(0) : null;
    } else if (defaultParentStyle != null) {
        defaultParentStyleName = defaultParentStyle.getQualifiedName();
    }

    final NewStyleDialog dialog = new NewStyleDialog(isTheme, themeEditorContext, defaultParentStyleName,
            (defaultParentStyle == null) ? null : defaultParentStyle.getName(), message);
    dialog.enableParentChoice(enableParentChoice);
    if (themeChangedListener != null) {
        dialog.setThemeChangedListener(themeChangedListener);
    }

    boolean createStyle = dialog.showAndGet();
    if (!createStyle) {
        return null;
    }

    int minModuleApi = getMinApiLevel(themeEditorContext.getCurrentContextModule());
    int minAcceptableApi = ResolutionUtils.getOriginalApiLevel(
            ResolutionUtils.getStyleResourceUrl(dialog.getStyleParentName()), themeEditorContext.getProject());

    final String fileName = AndroidResourceUtil.getDefaultResourceFileName(ResourceType.STYLE);
    FolderConfiguration config = new FolderConfiguration();
    if (minModuleApi < minAcceptableApi) {
        VersionQualifier qualifier = new VersionQualifier(minAcceptableApi);
        config.setVersionQualifier(qualifier);
    }

    if (fileName == null) {
        LOG.error("Couldn't find a default filename for ResourceType.STYLE");
        return null;
    }

    final List<String> dirNames = Collections.singletonList(config.getFolderName(ResourceFolderType.VALUES));
    String parentStyleName = dialog.getStyleParentName();

    Module module = themeEditorContext.getCurrentContextModule();
    AndroidFacet facet = AndroidFacet.getInstance(module);
    if (facet == null) {
        LOG.error("Create new style for non-Android module " + module.getName());
        return null;
    }
    Project project = module.getProject();
    VirtualFile resourceDir = facet.getPrimaryResourceDir();
    if (resourceDir == null) {
        AndroidUtils.reportError(project, AndroidBundle.message("check.resource.dir.error", module.getName()));
        return null;
    }
    boolean isCreated = createNewStyle(project, resourceDir, dialog.getStyleName(), parentStyleName, fileName,
            dirNames);

    return isCreated ? dialog.getStyleName() : null;
}

From source file:google.registry.rdap.RdapJsonFormatter.java

/**
 * Creates a vCard address entry: array of strings specifying the components of the address.
 *
 * @see <a href="https://tools.ietf.org/html/rfc7095">
 *        RFC 7095: jCard: The JSON Format for vCard</a>
 *//*from   w w  w  .  j a v a 2  s.co  m*/
private static ImmutableList<Object> makeVCardAddressEntry(Address address) {
    if (address == null) {
        return null;
    }
    ImmutableList.Builder<Object> jsonBuilder = new ImmutableList.Builder<>();
    jsonBuilder.add(""); // PO box
    jsonBuilder.add(""); // extended address

    // The vCard spec allows several different ways to handle multiline street addresses. Per
    // Gustavo Lozano of ICANN, the one we should use is an embedded array of street address lines
    // if there is more than one line:
    //
    //   RFC7095 provides two examples of structured addresses, and one of the examples shows a
    //   street JSON element that contains several data elements. The example showing (see below)
    //   several data elements is the expected output when two or more <contact:street> elements
    //   exists in the contact object.
    //
    //   ["adr", {}, "text",
    //    [
    //    "", "",
    //    ["My Street", "Left Side", "Second Shack"],
    //    "Hometown", "PA", "18252", "U.S.A."
    //    ]
    //   ]
    ImmutableList<String> street = address.getStreet();
    if (street.isEmpty()) {
        jsonBuilder.add("");
    } else if (street.size() == 1) {
        jsonBuilder.add(street.get(0));
    } else {
        jsonBuilder.add(street);
    }
    jsonBuilder.add(nullToEmpty(address.getCity()));
    jsonBuilder.add(nullToEmpty(address.getState()));
    jsonBuilder.add(nullToEmpty(address.getZip()));
    jsonBuilder.add(new Locale("en", address.getCountryCode()).getDisplayCountry(new Locale("en")));
    return ImmutableList.<Object>of("adr", ImmutableMap.of(), "text", jsonBuilder.build());
}

From source file:com.google.gerrit.server.update.ReviewDbBatchUpdate.java

static void execute(ImmutableList<ReviewDbBatchUpdate> updates, BatchUpdateListener listener,
        @Nullable RequestId requestId, boolean dryrun) throws UpdateException, RestApiException {
    if (updates.isEmpty()) {
        return;/*w  w w .j a v a 2s. com*/
    }
    setRequestIds(updates, requestId);
    try {
        Order order = getOrder(updates, listener);
        boolean updateChangesInParallel = getUpdateChangesInParallel(updates);
        switch (order) {
        case REPO_BEFORE_DB:
            for (ReviewDbBatchUpdate u : updates) {
                u.executeUpdateRepo();
            }
            listener.afterUpdateRepos();
            for (ReviewDbBatchUpdate u : updates) {
                u.executeRefUpdates(dryrun);
            }
            listener.afterUpdateRefs();
            for (ReviewDbBatchUpdate u : updates) {
                u.reindexChanges(u.executeChangeOps(updateChangesInParallel, dryrun));
            }
            listener.afterUpdateChanges();
            break;
        case DB_BEFORE_REPO:
            for (ReviewDbBatchUpdate u : updates) {
                u.reindexChanges(u.executeChangeOps(updateChangesInParallel, dryrun));
            }
            for (ReviewDbBatchUpdate u : updates) {
                u.executeUpdateRepo();
            }
            for (ReviewDbBatchUpdate u : updates) {
                u.executeRefUpdates(dryrun);
            }
            break;
        default:
            throw new IllegalStateException("invalid execution order: " + order);
        }

        ChangeIndexer.allAsList(updates.stream().flatMap(u -> u.indexFutures.stream()).collect(toList())).get();

        // Fire ref update events only after all mutations are finished, since callers may assume a
        // patch set ref being created means the change was created, or a branch advancing meaning
        // some changes were closed.
        updates.stream().filter(u -> u.batchRefUpdate != null)
                .forEach(u -> u.gitRefUpdated.fire(u.project, u.batchRefUpdate, u.getAccount().orElse(null)));

        if (!dryrun) {
            for (ReviewDbBatchUpdate u : updates) {
                u.executePostOps();
            }
        }
    } catch (Exception e) {
        wrapAndThrowException(e);
    }
}

From source file:com.google.template.soy.jbcsrc.restricted.BytecodeUtils.java

/** Returns an expression that returns a new {@link ArrayList} containing all the given items. */
public static Expression asList(Iterable<? extends Expression> items) {
    final ImmutableList<Expression> copy = ImmutableList.copyOf(items);
    if (copy.isEmpty()) {
        return MethodRef.IMMUTABLE_LIST_OF.get(0).invoke();
    }//from   w ww.j a va  2 s  . c  o m
    // Note, we cannot necessarily use ImmutableList for anything besides the empty list because
    // we may need to put a null in it.
    final Expression construct = ConstructorRef.ARRAY_LIST_SIZE.construct(constant(copy.size()));
    return new Expression(ARRAY_LIST_TYPE, Feature.NON_NULLABLE) {
        @Override
        protected void doGen(CodeBuilder mv) {
            construct.gen(mv);
            for (Expression child : copy) {
                mv.dup();
                child.gen(mv);
                MethodRef.ARRAY_LIST_ADD.invokeUnchecked(mv);
                mv.pop(); // pop the bool result of arraylist.add
            }
        }
    };
}