List of usage examples for com.google.common.collect ImmutableList isEmpty
boolean isEmpty();
From source file:com.google.devtools.build.lib.skyframe.PackageLookupFunction.java
private PackageLookupValue computeWorkspacePackageLookupValue(Environment env, ImmutableList<Path> packagePathEntries) throws PackageLookupFunctionException, InterruptedException { PackageLookupValue result = getPackageLookupValue(env, packagePathEntries, Label.EXTERNAL_PACKAGE_IDENTIFIER, BuildFileName.WORKSPACE); if (result == null) { return null; }//from ww w . j ava 2 s . com if (result.packageExists()) { return result; } // Fall back on the last package path entry if there were any and nothing else worked. // TODO(kchodorow): get rid of this, the semantics are wrong (successful package lookup should // mean the package exists). a bunch of tests need to be rewritten first though. if (packagePathEntries.isEmpty()) { return PackageLookupValue.NO_BUILD_FILE_VALUE; } Path lastPackagePath = packagePathEntries.get(packagePathEntries.size() - 1); FileValue lastPackagePackagePathFileValue = getFileValue( RootedPath.toRootedPath(lastPackagePath, PathFragment.EMPTY_FRAGMENT), env, Label.EXTERNAL_PACKAGE_IDENTIFIER); if (lastPackagePackagePathFileValue == null) { return null; } return lastPackagePackagePathFileValue.exists() ? PackageLookupValue.success(lastPackagePath, BuildFileName.WORKSPACE) : PackageLookupValue.NO_BUILD_FILE_VALUE; }
From source file:codecrafter47.bungeetablistplus.BungeeTabListPlus.java
/** * Called when the plugin is enabled//from ww w .j a va 2s .c o m */ public void onEnable() { if (!plugin.getDataFolder().exists()) { plugin.getDataFolder().mkdirs(); } try { Class.forName("net.md_5.bungee.api.Title"); } catch (ClassNotFoundException ex) { throw new RuntimeException("You need to run at least BungeeCord version #995"); } try { Field field = BungeeTabListPlusAPI.class.getDeclaredField("instance"); field.setAccessible(true); field.set(null, this); } catch (NoSuchFieldException | IllegalAccessException ex) { getLogger().log(Level.SEVERE, "Failed to initialize API", ex); } INSTANCE = this; try { File file = new File(plugin.getDataFolder(), "config.yml"); if (!file.exists()) { config = new MainConfig(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)); YamlConfig.writeWithComments(writer, config, "This is the configuration file of BungeeTabListPlus", "See https://github.com/CodeCrafter47/BungeeTabListPlus/wiki for additional information"); } else { config = YamlConfig.read(new FileInputStream(file), MainConfig.class); } } catch (IOException | YAMLException ex) { plugin.getLogger().warning("Unable to load Config"); plugin.getLogger().log(Level.WARNING, null, ex); plugin.getLogger().warning("Disabling Plugin"); return; } if (config.automaticallySendBugReports) { String revision = "unknown"; try { Properties current = new Properties(); current.load(getClass().getClassLoader().getResourceAsStream("version.properties")); revision = current.getProperty("revision", revision); } catch (IOException ex) { getLogger().log(Level.SEVERE, "Unexpected exception", ex); } String version = getPlugin().getDescription().getVersion(); if (!"unknown".equals(revision)) { version += "-git-" + revision; } String systemInfo = "" + "System Info\n" + "===========\n" + "Bungee: " + getProxy().getVersion() + "\n" + "Java: " + System.getProperty("java.version") + "\n"; bugReportingService = new BugReportingService(Level.SEVERE, getPlugin().getDescription().getName(), version, command -> plugin.getProxy().getScheduler().runAsync(plugin, command), systemInfo); bugReportingService.registerLogger(getLogger()); } resendThread = new ResendThread(); File headsFolder = new File(plugin.getDataFolder(), "heads"); if (!headsFolder.exists()) { headsFolder.mkdirs(); try { // copy default heads ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(plugin.getFile())); ZipEntry entry; while ((entry = zipInputStream.getNextEntry()) != null) { if (!entry.isDirectory() && entry.getName().startsWith("heads/")) { try { File targetFile = new File(plugin.getDataFolder(), entry.getName()); targetFile.getParentFile().mkdirs(); if (!targetFile.exists()) { Files.copy(zipInputStream, targetFile.toPath()); getLogger().info("Extracted " + entry.getName()); } } catch (IOException ex) { getLogger().log(Level.SEVERE, "Failed to extract file " + entry.getName(), ex); } } } zipInputStream.close(); } catch (IOException ex) { getLogger().log(Level.SEVERE, "Error extracting files", ex); } } skins = new SkinManagerImpl(plugin, headsFolder); fakePlayerManager = new FakePlayerManagerImpl(plugin); playerProviders = new ArrayList<>(); if (plugin.getProxy().getPluginManager().getPlugin("RedisBungee") != null) { redisPlayerManager = new RedisPlayerManager(connectedPlayerManager, this, getLogger()); playerProviders.add(redisPlayerManager); plugin.getLogger().info("Hooked RedisBungee"); } playerProviders.add(connectedPlayerManager); playerProviders.add(fakePlayerManager); plugin.getProxy().registerChannel(BridgeProtocolConstants.CHANNEL); bukkitBridge = new BukkitBridge(this); pm = new PermissionManager(this); dataManager = new DataManager(this); placeholderManager = new PlaceholderManagerImpl(); placeholderManager.internalRegisterPlaceholderProvider(new BasicPlaceholders()); placeholderManager.internalRegisterPlaceholderProvider(new BukkitPlaceholders()); placeholderManager.internalRegisterPlaceholderProvider(new ColorPlaceholder()); placeholderManager.internalRegisterPlaceholderProvider(new ConditionalPlaceholders()); placeholderManager.internalRegisterPlaceholderProvider(new OnlineStatePlaceholder()); placeholderManager.internalRegisterPlaceholderProvider(new PlayerCountPlaceholder()); if (plugin.getProxy().getPluginManager().getPlugin("RedisBungee") != null) { placeholderManager.internalRegisterPlaceholderProvider(new RedisBungeePlaceholders()); } placeholderManager.internalRegisterPlaceholderProvider(new TimePlaceholders()); if (plugin.getProxy().getPluginManager().getPlugin("ProtocolSupportBungee") != null) { protocolVersionProvider = new ProtocolSupportVersionProvider(); } else { protocolVersionProvider = new BungeeProtocolVersionProvider(); } // register commands and update Notifier ProxyServer.getInstance().getPluginManager().registerCommand(plugin, new CommandBungeeTabListPlus()); ProxyServer.getInstance().getScheduler().schedule(plugin, new UpdateNotifier(this), 15, 15, TimeUnit.MINUTES); // Start metrics try { Metrics metrics = new Metrics(plugin); metrics.start(); } catch (IOException e) { plugin.getLogger().log(Level.SEVERE, "Failed to initialize Metrics", e); } // Load updateCheck thread if (config.checkForUpdates) { updateChecker = new UpdateChecker(plugin); plugin.getLogger().info("Starting UpdateChecker Task"); plugin.getProxy().getScheduler() .schedule(plugin, updateChecker, 0, UpdateChecker.interval, TimeUnit.MINUTES).getId(); } // Start packet listeners ProtocolManager protocolManager = new ProtocolManager(plugin); protocolManager.enable(); int[] serversHash = { getProxy().getServers().hashCode() }; getProxy().getScheduler().schedule(plugin, () -> { int hash = getProxy().getServers().hashCode(); if (hash != serversHash[0]) { serversHash[0] = hash; getLogger().info("Network topology change detected. Reloading plugin."); reload(); } }, 1, 1, TimeUnit.MINUTES); placeholderAPIHook = new PlaceholderAPIHook(this); tabLists = new TabListManager(this); if (!tabLists.loadTabLists()) { return; } ProxyServer.getInstance().getPluginManager().registerListener(plugin, listener); plugin.getProxy().getScheduler().runAsync(plugin, resendThread); restartRefreshThread(); plugin.getProxy().getScheduler().schedule(plugin, () -> { ImmutableList<String> filesNeedingUpgrade = tabLists.getFilesNeedingUpgrade(); if (!filesNeedingUpgrade.isEmpty()) { BaseComponent[] message = ChatUtil.parseBBCode( "&c[BungeeTabListPlus] Warning: &eThe following tablist configuration files need to be upgraded: &f" + Joiner.on(", ").join(filesNeedingUpgrade) + "\n&eYou can find more information at &b[url]https://github.com/CodeCrafter47/BungeeTabListPlus/wiki/Updating[/url]&e."); for (ProxiedPlayer player : plugin.getProxy().getPlayers()) { if (getPermissionManager().hasPermission(player, "bungeetablistplus.admin")) { player.sendMessage(message); } } } }, 15, 15, TimeUnit.MINUTES); }
From source file:google.registry.rdap.RdapJsonFormatter.java
/** * Adds the required top-level boilerplate. RFC 7483 specifies that the top-level object should * include an entry indicating the conformance level. The ICANN RDAP Profile document (dated 3 * December 2015) mandates several additional entries, in sections 1.4.4, 1.4.10, 1.5.18 and * 1.5.20. Note that this method will only work if there are no object-specific remarks already in * the JSON object being built. If there are, the boilerplate must be merged in. * * @param jsonBuilder a builder for a JSON map object * @param boilerplateType type of boilerplate to be added; the ICANN RDAP Profile document * mandates extra boilerplate for domain objects * @param notices a list of notices to be inserted before the boilerplate notices. If the TOS * notice is in this list, the method avoids adding a second copy. * @param remarks a list of remarks to be inserted before the boilerplate notices. * @param rdapLinkBase the base for link URLs *///from w ww.j a va 2 s.c o m void addTopLevelEntries(ImmutableMap.Builder<String, Object> jsonBuilder, BoilerplateType boilerplateType, List<ImmutableMap<String, Object>> notices, List<ImmutableMap<String, Object>> remarks, String rdapLinkBase) { jsonBuilder.put("rdapConformance", CONFORMANCE_LIST); ImmutableList.Builder<ImmutableMap<String, Object>> noticesBuilder = new ImmutableList.Builder<>(); ImmutableMap<String, Object> tosNotice = getJsonTosNotice(rdapLinkBase); boolean tosNoticeFound = false; if (!notices.isEmpty()) { noticesBuilder.addAll(notices); for (ImmutableMap<String, Object> notice : notices) { if (notice.equals(tosNotice)) { tosNoticeFound = true; break; } } } if (!tosNoticeFound) { noticesBuilder.add(tosNotice); } jsonBuilder.put(NOTICES, noticesBuilder.build()); ImmutableList.Builder<ImmutableMap<String, Object>> remarksBuilder = new ImmutableList.Builder<>(); remarksBuilder.addAll(remarks); switch (boilerplateType) { case DOMAIN: remarksBuilder.addAll(RdapIcannStandardInformation.domainBoilerplateRemarks); break; case NAMESERVER: case ENTITY: remarksBuilder.addAll(RdapIcannStandardInformation.nameserverAndEntityBoilerplateRemarks); break; default: // things other than domains, nameservers and entities cannot contain remarks break; } ImmutableList<ImmutableMap<String, Object>> remarksToAdd = remarksBuilder.build(); if (!remarksToAdd.isEmpty()) { jsonBuilder.put(REMARKS, remarksToAdd); } }
From source file:google.registry.rdap.RdapJsonFormatter.java
/** * Creates a JSON object for a {@link HostResource}. * * @param hostResource the host resource object from which the JSON object should be created * @param isTopLevel if true, the top-level boilerplate will be added * @param linkBase the URL base to be used when creating links * @param whoisServer the fully-qualified domain name of the WHOIS server to be listed in the * port43 field; if null, port43 is not added to the object * @param now the as-date/*from w w w . j a v a 2s.c om*/ * @param outputDataType whether to generate full or summary data */ ImmutableMap<String, Object> makeRdapJsonForHost(HostResource hostResource, boolean isTopLevel, @Nullable String linkBase, @Nullable String whoisServer, DateTime now, OutputDataType outputDataType) { ImmutableMap.Builder<String, Object> jsonBuilder = new ImmutableMap.Builder<>(); jsonBuilder.put("objectClassName", "nameserver"); jsonBuilder.put("handle", hostResource.getRepoId()); jsonBuilder.put("ldhName", hostResource.getFullyQualifiedHostName()); // Only include the unicodeName field if there are unicode characters. if (hasUnicodeComponents(hostResource.getFullyQualifiedHostName())) { jsonBuilder.put("unicodeName", Idn.toUnicode(hostResource.getFullyQualifiedHostName())); } jsonBuilder.put("status", makeStatusValueList(hostResource.getStatusValues())); jsonBuilder.put("links", ImmutableList.of(makeLink("nameserver", hostResource.getFullyQualifiedHostName(), linkBase))); List<ImmutableMap<String, Object>> remarks; // If we are outputting all data (not just summary data), also add events taken from the history // entries. If we are outputting summary data, instead add a remark indicating that fact. if (outputDataType == OutputDataType.SUMMARY) { remarks = ImmutableList.of(RdapIcannStandardInformation.SUMMARY_DATA_REMARK); } else { remarks = ImmutableList.of(); ImmutableList<Object> events = makeEvents(hostResource, now); if (!events.isEmpty()) { jsonBuilder.put("events", events); } } ImmutableSet<InetAddress> inetAddresses = hostResource.getInetAddresses(); if (!inetAddresses.isEmpty()) { ImmutableList.Builder<String> v4AddressesBuilder = new ImmutableList.Builder<>(); ImmutableList.Builder<String> v6AddressesBuilder = new ImmutableList.Builder<>(); for (InetAddress inetAddress : inetAddresses) { if (inetAddress instanceof Inet4Address) { v4AddressesBuilder.add(InetAddresses.toAddrString(inetAddress)); } else if (inetAddress instanceof Inet6Address) { v6AddressesBuilder.add(InetAddresses.toAddrString(inetAddress)); } } ImmutableMap.Builder<String, ImmutableList<String>> ipAddressesBuilder = new ImmutableMap.Builder<>(); ImmutableList<String> v4Addresses = v4AddressesBuilder.build(); if (!v4Addresses.isEmpty()) { ipAddressesBuilder.put("v4", Ordering.natural().immutableSortedCopy(v4Addresses)); } ImmutableList<String> v6Addresses = v6AddressesBuilder.build(); if (!v6Addresses.isEmpty()) { ipAddressesBuilder.put("v6", Ordering.natural().immutableSortedCopy(v6Addresses)); } ImmutableMap<String, ImmutableList<String>> ipAddresses = ipAddressesBuilder.build(); if (!ipAddresses.isEmpty()) { jsonBuilder.put("ipAddresses", ipAddressesBuilder.build()); } } if (whoisServer != null) { jsonBuilder.put("port43", whoisServer); } if (isTopLevel) { addTopLevelEntries(jsonBuilder, BoilerplateType.NAMESERVER, remarks, ImmutableList.<ImmutableMap<String, Object>>of(), linkBase); } else if (!remarks.isEmpty()) { jsonBuilder.put(REMARKS, remarks); } return jsonBuilder.build(); }
From source file:google.registry.rdap.RdapJsonFormatter.java
/** * Creates a JSON object for a {@link DomainResource}. * * @param domainResource the domain resource object from which the JSON object should be created * @param isTopLevel if true, the top-level boilerplate will be added * @param linkBase the URL base to be used when creating links * @param whoisServer the fully-qualified domain name of the WHOIS server to be listed in the * port43 field; if null, port43 is not added to the object * @param now the as-date// ww w .j ava 2 s .c o m * @param outputDataType whether to generate full or summary data */ ImmutableMap<String, Object> makeRdapJsonForDomain(DomainResource domainResource, boolean isTopLevel, @Nullable String linkBase, @Nullable String whoisServer, DateTime now, OutputDataType outputDataType) { // Start with the domain-level information. ImmutableMap.Builder<String, Object> jsonBuilder = new ImmutableMap.Builder<>(); jsonBuilder.put("objectClassName", "domain"); jsonBuilder.put("handle", domainResource.getRepoId()); jsonBuilder.put("ldhName", domainResource.getFullyQualifiedDomainName()); // Only include the unicodeName field if there are unicode characters. if (hasUnicodeComponents(domainResource.getFullyQualifiedDomainName())) { jsonBuilder.put("unicodeName", Idn.toUnicode(domainResource.getFullyQualifiedDomainName())); } jsonBuilder.put("status", makeStatusValueList(domainResource.getStatusValues())); jsonBuilder.put("links", ImmutableList.of(makeLink("domain", domainResource.getFullyQualifiedDomainName(), linkBase))); // If we are outputting all data (not just summary data), also add information about hosts, // contacts and events (history entries). If we are outputting summary data, instead add a // remark indicating that fact. List<ImmutableMap<String, Object>> remarks; if (outputDataType == OutputDataType.SUMMARY) { remarks = ImmutableList.of(RdapIcannStandardInformation.SUMMARY_DATA_REMARK); } else { remarks = ImmutableList.of(); ImmutableList<Object> events = makeEvents(domainResource, now); if (!events.isEmpty()) { jsonBuilder.put("events", events); } // Kick off the database loads of the nameservers that we will need. Map<Key<HostResource>, HostResource> loadedHosts = ofy().load().keys(domainResource.getNameservers()); // And the registrant and other contacts. Map<Key<ContactResource>, ContactResource> loadedContacts = ofy().load() .keys(domainResource.getReferencedContacts()); // Nameservers ImmutableList.Builder<Object> nsBuilder = new ImmutableList.Builder<>(); for (HostResource hostResource : HOST_RESOURCE_ORDERING.immutableSortedCopy(loadedHosts.values())) { nsBuilder.add(makeRdapJsonForHost(hostResource, false, linkBase, null, now, outputDataType)); } ImmutableList<Object> ns = nsBuilder.build(); if (!ns.isEmpty()) { jsonBuilder.put("nameservers", ns); } // Contacts ImmutableList.Builder<Object> entitiesBuilder = new ImmutableList.Builder<>(); for (DesignatedContact designatedContact : FluentIterable.from(domainResource.getContacts()) .append(DesignatedContact.create(Type.REGISTRANT, domainResource.getRegistrant())) .toSortedList(DESIGNATED_CONTACT_ORDERING)) { ContactResource loadedContact = loadedContacts.get(designatedContact.getContactKey()); entitiesBuilder.add(makeRdapJsonForContact(loadedContact, false, Optional.of(designatedContact.getType()), linkBase, null, now, outputDataType)); } ImmutableList<Object> entities = entitiesBuilder.build(); if (!entities.isEmpty()) { jsonBuilder.put("entities", entities); } } if (whoisServer != null) { jsonBuilder.put("port43", whoisServer); } if (isTopLevel) { addTopLevelEntries(jsonBuilder, BoilerplateType.DOMAIN, remarks, ImmutableList.<ImmutableMap<String, Object>>of(), linkBase); } else if (!remarks.isEmpty()) { jsonBuilder.put(REMARKS, remarks); } return jsonBuilder.build(); }
From source file:google.registry.rdap.RdapJsonFormatter.java
/** * Creates a JSON object for a {@link ContactResource} and associated contact type. * * @param contactResource the contact resource object from which the JSON object should be created * @param isTopLevel if true, the top-level boilerplate will be added * @param contactType the contact type to map to an RDAP role; if absent, no role is listed * @param linkBase the URL base to be used when creating links * @param whoisServer the fully-qualified domain name of the WHOIS server to be listed in the * port43 field; if null, port43 is not added to the object * @param now the as-date/*from w ww. j a v a 2 s . c o m*/ * @param outputDataType whether to generate full or summary data */ ImmutableMap<String, Object> makeRdapJsonForContact(ContactResource contactResource, boolean isTopLevel, Optional<DesignatedContact.Type> contactType, @Nullable String linkBase, @Nullable String whoisServer, DateTime now, OutputDataType outputDataType) { ImmutableMap.Builder<String, Object> jsonBuilder = new ImmutableMap.Builder<>(); jsonBuilder.put("objectClassName", "entity"); jsonBuilder.put("handle", contactResource.getRepoId()); jsonBuilder.put("status", makeStatusValueList(contactResource.getStatusValues())); if (contactType.isPresent()) { jsonBuilder.put("roles", ImmutableList.of(convertContactTypeToRdapRole(contactType.get()))); } jsonBuilder.put("links", ImmutableList.of(makeLink("entity", contactResource.getRepoId(), linkBase))); // Create the vCard. ImmutableList.Builder<Object> vcardBuilder = new ImmutableList.Builder<>(); vcardBuilder.add(VCARD_ENTRY_VERSION); PostalInfo postalInfo = contactResource.getInternationalizedPostalInfo(); if (postalInfo == null) { postalInfo = contactResource.getLocalizedPostalInfo(); } if (postalInfo != null) { if (postalInfo.getName() != null) { vcardBuilder.add(ImmutableList.of("fn", ImmutableMap.of(), "text", postalInfo.getName())); } if (postalInfo.getOrg() != null) { vcardBuilder.add(ImmutableList.of("org", ImmutableMap.of(), "text", postalInfo.getOrg())); } ImmutableList<Object> addressEntry = makeVCardAddressEntry(postalInfo.getAddress()); if (addressEntry != null) { vcardBuilder.add(addressEntry); } } ContactPhoneNumber voicePhoneNumber = contactResource.getVoiceNumber(); if (voicePhoneNumber != null) { vcardBuilder.add(makePhoneEntry(PHONE_TYPE_VOICE, makePhoneString(voicePhoneNumber))); } ContactPhoneNumber faxPhoneNumber = contactResource.getFaxNumber(); if (faxPhoneNumber != null) { vcardBuilder.add(makePhoneEntry(PHONE_TYPE_FAX, makePhoneString(faxPhoneNumber))); } String emailAddress = contactResource.getEmailAddress(); if (emailAddress != null) { vcardBuilder.add(ImmutableList.of("email", ImmutableMap.of(), "text", emailAddress)); } jsonBuilder.put("vcardArray", ImmutableList.of("vcard", vcardBuilder.build())); // If we are outputting all data (not just summary data), also add events taken from the history // entries. If we are outputting summary data, instead add a remark indicating that fact. List<ImmutableMap<String, Object>> remarks; if (outputDataType == OutputDataType.SUMMARY) { remarks = ImmutableList.of(RdapIcannStandardInformation.SUMMARY_DATA_REMARK); } else { remarks = ImmutableList.of(); ImmutableList<Object> events = makeEvents(contactResource, now); if (!events.isEmpty()) { jsonBuilder.put("events", events); } } if (whoisServer != null) { jsonBuilder.put("port43", whoisServer); } if (isTopLevel) { addTopLevelEntries(jsonBuilder, BoilerplateType.ENTITY, remarks, ImmutableList.<ImmutableMap<String, Object>>of(), linkBase); } else if (!remarks.isEmpty()) { jsonBuilder.put(REMARKS, remarks); } return jsonBuilder.build(); }
From source file:google.registry.rdap.RdapJsonFormatter.java
/** * Creates a JSON object for a {@link Registrar}. * * @param registrar the registrar object from which the JSON object should be created * @param isTopLevel if true, the top-level boilerplate will be added * @param linkBase the URL base to be used when creating links * @param whoisServer the fully-qualified domain name of the WHOIS server to be listed in the * port43 field; if null, port43 is not added to the object * @param now the as-date/*from w w w . j av a 2 s. c o m*/ * @param outputDataType whether to generate full or summary data */ ImmutableMap<String, Object> makeRdapJsonForRegistrar(Registrar registrar, boolean isTopLevel, @Nullable String linkBase, @Nullable String whoisServer, DateTime now, OutputDataType outputDataType) { ImmutableMap.Builder<String, Object> jsonBuilder = new ImmutableMap.Builder<>(); jsonBuilder.put("objectClassName", "entity"); jsonBuilder.put("handle", registrar.getIanaIdentifier().toString()); jsonBuilder.put("status", STATUS_LIST_ACTIVE); jsonBuilder.put("roles", ImmutableList.of(RdapEntityRole.REGISTRAR.rfc7483String)); jsonBuilder.put("links", ImmutableList.of(makeLink("entity", registrar.getIanaIdentifier().toString(), linkBase))); jsonBuilder.put("publicIds", ImmutableList.of(ImmutableMap.of("type", "IANA Registrar ID", "identifier", registrar.getIanaIdentifier().toString()))); // Create the vCard. ImmutableList.Builder<Object> vcardBuilder = new ImmutableList.Builder<>(); vcardBuilder.add(VCARD_ENTRY_VERSION); String registrarName = registrar.getRegistrarName(); if (registrarName != null) { vcardBuilder.add(ImmutableList.of("fn", ImmutableMap.of(), "text", registrarName)); } RegistrarAddress address = registrar.getInternationalizedAddress(); if (address == null) { address = registrar.getLocalizedAddress(); } if (address != null) { ImmutableList<Object> addressEntry = makeVCardAddressEntry(address); if (addressEntry != null) { vcardBuilder.add(addressEntry); } } String voicePhoneNumber = registrar.getPhoneNumber(); if (voicePhoneNumber != null) { vcardBuilder.add(makePhoneEntry(PHONE_TYPE_VOICE, "tel:" + voicePhoneNumber)); } String faxPhoneNumber = registrar.getFaxNumber(); if (faxPhoneNumber != null) { vcardBuilder.add(makePhoneEntry(PHONE_TYPE_FAX, "tel:" + faxPhoneNumber)); } String emailAddress = registrar.getEmailAddress(); if (emailAddress != null) { vcardBuilder.add(ImmutableList.of("email", ImmutableMap.of(), "text", emailAddress)); } jsonBuilder.put("vcardArray", ImmutableList.of("vcard", vcardBuilder.build())); // If we are outputting all data (not just summary data), also add registrar contacts. If we are // outputting summary data, instead add a remark indicating that fact. List<ImmutableMap<String, Object>> remarks; if (outputDataType == OutputDataType.SUMMARY) { remarks = ImmutableList.of(RdapIcannStandardInformation.SUMMARY_DATA_REMARK); } else { remarks = ImmutableList.of(); ImmutableList<Object> events = makeEvents(registrar, now); if (!events.isEmpty()) { jsonBuilder.put("events", events); } // include the registrar contacts as subentities ImmutableList.Builder<Map<String, Object>> registrarContactsBuilder = new ImmutableList.Builder<>(); for (RegistrarContact registrarContact : registrar.getContacts()) { if (isVisible(registrarContact)) { registrarContactsBuilder.add(makeRdapJsonForRegistrarContact(registrarContact, null)); } } ImmutableList<Map<String, Object>> registrarContacts = registrarContactsBuilder.build(); if (!registrarContacts.isEmpty()) { jsonBuilder.put("entities", registrarContacts); } } if (whoisServer != null) { jsonBuilder.put("port43", whoisServer); } if (isTopLevel) { addTopLevelEntries(jsonBuilder, BoilerplateType.ENTITY, remarks, ImmutableList.<ImmutableMap<String, Object>>of(), linkBase); } else if (!remarks.isEmpty()) { jsonBuilder.put(REMARKS, remarks); } return jsonBuilder.build(); }
From source file:com.getbase.android.schema.Schemas.java
private ImmutableMap<String, ImmutableList<? extends TableDefinitionOperation>> merge( ImmutableMap<String, ImmutableList<? extends TableDefinitionOperation>> schema, ImmutableMap<String, ImmutableList<? extends TableDowngradeOperation>> downgrades, int targetRevision) { ImmutableMap.Builder<String, ImmutableList<? extends TableDefinitionOperation>> builder = ImmutableMap .builder();/* w w w .j a v a 2 s. co m*/ for (String unchangedTable : Sets.difference(schema.keySet(), downgrades.keySet())) { builder.put(unchangedTable, schema.get(unchangedTable)); } for (String alteredTable : Sets.intersection(downgrades.keySet(), schema.keySet())) { ImmutableList<? extends TableDefinitionOperation> mergedOperations = MERGER.merge( schema.get(alteredTable), downgrades.get(alteredTable), alteredTable, targetRevision, mRevisionDescriptionBuilder); if (!mergedOperations.isEmpty()) { builder.put(alteredTable, mergedOperations); } } for (String addedTable : Sets.difference(downgrades.keySet(), schema.keySet())) { builder.put(addedTable, CONVERTER.convert(downgrades.get(addedTable), addedTable, targetRevision, mRevisionDescriptionBuilder)); } return builder.build(); }
From source file:com.google.javascript.jscomp.FunctionTypeBuilder.java
/** * Infer the role of the function (whether it's a constructor or interface) * and what it inherits from in JSDocInfo. *//*from w ww.j a v a 2s . c o m*/ FunctionTypeBuilder inferInheritance(@Nullable JSDocInfo info) { if (info != null) { isConstructor = info.isConstructor(); makesStructs = info.makesStructs(); makesDicts = info.makesDicts(); isInterface = info.isInterface(); if (makesStructs && !isConstructor) { reportWarning(CONSTRUCTOR_REQUIRED, "@struct", formatFnName()); } else if (makesDicts && !isConstructor) { reportWarning(CONSTRUCTOR_REQUIRED, "@dict", formatFnName()); } if (typeRegistry.isIObject(fnName, info)) { // This case is only for setting template types // for IObject<KEY1, VALUE1>. // In the (old) type system, there should be only one unique template // type for <KEY1> and <VALUE1> respectively classTemplateTypeNames = typeRegistry.getIObjectTemplateTypeNames(); typeRegistry.setTemplateTypeNames(classTemplateTypeNames); } else { // Otherwise, create new template type for // the template values of the constructor/interface // Class template types, which can be used in the scope of a constructor // definition. ImmutableList<String> typeParameters = info.getTemplateTypeNames(); if (!typeParameters.isEmpty() && (isConstructor || isInterface)) { ImmutableList.Builder<TemplateType> builder = ImmutableList.builder(); for (String typeParameter : typeParameters) { builder.add(typeRegistry.createTemplateType(typeParameter)); } classTemplateTypeNames = builder.build(); typeRegistry.setTemplateTypeNames(classTemplateTypeNames); } } // base type if (info.hasBaseType()) { if (isConstructor) { JSType maybeBaseType = info.getBaseType().evaluate(scope, typeRegistry); if (maybeBaseType != null && maybeBaseType.setValidator(new ExtendedTypeValidator())) { baseType = (ObjectType) maybeBaseType; } } else { reportWarning(EXTENDS_WITHOUT_TYPEDEF, formatFnName()); } } // Implemented interfaces (for constructors only). if (info.getImplementedInterfaceCount() > 0) { if (isConstructor) { implementedInterfaces = new ArrayList<>(); Set<JSType> baseInterfaces = new HashSet<>(); for (JSTypeExpression t : info.getImplementedInterfaces()) { JSType maybeInterType = t.evaluate(scope, typeRegistry); if (maybeInterType != null && maybeInterType.setValidator(new ImplementedTypeValidator())) { // Disallow implementing the same base (not templatized) interface // type more than once. JSType baseInterface = maybeInterType; if (baseInterface.toMaybeTemplatizedType() != null) { baseInterface = baseInterface.toMaybeTemplatizedType().getReferencedType(); } if (!baseInterfaces.add(baseInterface)) { reportWarning(SAME_INTERFACE_MULTIPLE_IMPLEMENTS, baseInterface.toString()); } implementedInterfaces.add((ObjectType) maybeInterType); } } } else if (isInterface) { reportWarning(TypeCheck.CONFLICTING_IMPLEMENTED_TYPE, formatFnName()); } else { reportWarning(CONSTRUCTOR_REQUIRED, "@implements", formatFnName()); } } // extended interfaces (for interfaces only) // We've already emitted a warning if this is not an interface. if (isInterface) { extendedInterfaces = new ArrayList<>(); for (JSTypeExpression t : info.getExtendedInterfaces()) { JSType maybeInterfaceType = t.evaluate(scope, typeRegistry); if (maybeInterfaceType != null && maybeInterfaceType.setValidator(new ExtendedTypeValidator())) { extendedInterfaces.add((ObjectType) maybeInterfaceType); } } } } return this; }
From source file:com.google.javascript.jscomp.PolymerClassRewriter.java
/** * Rewrites a class which extends Polymer.Element to a set of declarations and assignments which * can be understood by the compiler./*w w w . j a v a 2 s. c o m*/ * * @param clazz The class node * @param cls The extracted {@link PolymerClassDefinition} for the Polymer element created by this * call. */ void rewritePolymerClassDeclaration(Node clazz, final PolymerClassDefinition cls, boolean isInGlobalScope) { if (cls.descriptor != null) { addTypesToFunctions(cls.descriptor, cls.target.getQualifiedName(), cls.defType); } PolymerPassStaticUtils.switchDollarSignPropsToBrackets(NodeUtil.getClassMembers(clazz), compiler); for (MemberDefinition prop : cls.props) { if (prop.value.isObjectLit()) { PolymerPassStaticUtils.switchDollarSignPropsToBrackets(prop.value, compiler); } } // For simplicity add everything into a block, before adding it to the AST. Node block = IR.block(); // For each Polymer property we found in the "properties" configuration object, append a // property declaration to the prototype (e.g. "/** @type {string} */ MyElement.prototype.foo"). appendPropertiesToBlock(cls.props, block, cls.target.getQualifiedName() + ".prototype."); ImmutableList<MemberDefinition> readOnlyProps = parseReadOnlyProperties(cls, block); ImmutableList<MemberDefinition> attributeReflectedProps = parseAttributeReflectedProperties(cls); createExportsAndExterns(cls, readOnlyProps, attributeReflectedProps); // If an external interface is required, mark the class as implementing it if (polymerExportPolicy == PolymerExportPolicy.EXPORT_ALL || !readOnlyProps.isEmpty() || !attributeReflectedProps.isEmpty()) { Node jsDocInfoNode = NodeUtil.getBestJSDocInfoNode(clazz); JSDocInfoBuilder classInfo = JSDocInfoBuilder.maybeCopyFrom(jsDocInfoNode.getJSDocInfo()); String interfaceName = getInterfaceName(cls); JSTypeExpression interfaceType = new JSTypeExpression(new Node(Token.BANG, IR.string(interfaceName)), VIRTUAL_FILE); classInfo.recordImplementedInterface(interfaceType); jsDocInfoNode.setJSDocInfo(classInfo.build()); } if (block.hasChildren()) { removePropertyDocs(cls.descriptor, cls.defType); Node stmt = NodeUtil.getEnclosingStatement(clazz); stmt.getParent().addChildrenAfter(block.removeChildren(), stmt); compiler.reportChangeToEnclosingScope(stmt); } addReturnTypeIfMissing(cls, "is", new JSTypeExpression(IR.string("string"), VIRTUAL_FILE)); Node type = new Node(Token.BANG); Node array = IR.string("Array"); type.addChildToBack(array); Node arrayTemplateType = new Node(Token.BLOCK, IR.string("string")); array.addChildToBack(arrayTemplateType); addReturnTypeIfMissing(cls, "observers", new JSTypeExpression(type, VIRTUAL_FILE)); addReturnTypeIfMissing(cls, "properties", new JSTypeExpression(IR.string(POLYMER_ELEMENT_PROP_CONFIG), VIRTUAL_FILE)); // If property renaming is enabled, wrap the properties object literal // in a reflection call so that the properties are renamed consistently // with the class members. if (propertyRenamingEnabled && cls.descriptor != null) { addObjectReflectionCall(cls, cls.descriptor); } }