List of usage examples for com.google.common.base Splitter on
@CheckReturnValue @GwtIncompatible("java.util.regex") public static Splitter on(final Pattern separatorPattern)
From source file:name.marcelomorales.siqisiqi.examples.simple.init.InitialData.java
@Inject public InitialData(DataSource dataSource) throws SQLException, IOException { jdbcTemplate = new JdbcTemplate(dataSource); try (Connection c = dataSource.getConnection()) { URL resource = Resources.getResource("ddl.sql"); String s = Resources.toString(resource, Charsets.US_ASCII); Iterable<String> split = Splitter.on(';').omitEmptyStrings().trimResults().split(s); for (String sql : split) { try (Statement st = c.createStatement()) { st.execute(sql);// w w w . j a v a 2 s . co m } } c.commit(); // this is needed because we don't use @TransactionAttribute } }
From source file:co.cask.cdap.data2.metadata.dataset.SortInfo.java
/** * Parses a {@link SortInfo} object from the specified string. The supported format is * <pre>[sortBy][whitespace][sortOrder]</pre>. * * @param sort the string to parse into a {@link SortInfo}. If {@code null}, {@link #DEFAULT} is returned * @return the parsed {@link SortInfo}/*from w w w . ja v a 2 s. c o m*/ * @throws BadRequestException if the string does not conform to the expected format */ public static SortInfo of(@Nullable String sort) throws BadRequestException { if (Strings.isNullOrEmpty(sort)) { return SortInfo.DEFAULT; } Iterable<String> sortSplit = Splitter.on(SPACE_SPLIT_PATTERN).trimResults().omitEmptyStrings().split(sort); if (Iterables.size(sortSplit) != 2) { throw new BadRequestException(String.format( "'sort' parameter should be a space separated string containing the field ('%s' or '%s') and " + "the sort order ('%s' or '%s'). Found %s.", AbstractSystemMetadataWriter.ENTITY_NAME_KEY, AbstractSystemMetadataWriter.CREATION_TIME_KEY, SortOrder.ASC, SortOrder.DESC, sort)); } Iterator<String> iterator = sortSplit.iterator(); String sortBy = iterator.next(); String sortOrder = iterator.next(); if (!AbstractSystemMetadataWriter.ENTITY_NAME_KEY.equalsIgnoreCase(sortBy) && !AbstractSystemMetadataWriter.CREATION_TIME_KEY.equalsIgnoreCase(sortBy)) { throw new BadRequestException(String.format("Sort field must be '%s' or '%s'. Found %s.", AbstractSystemMetadataWriter.ENTITY_NAME_KEY, AbstractSystemMetadataWriter.CREATION_TIME_KEY, sortBy)); } if (!"asc".equalsIgnoreCase(sortOrder) && !"desc".equalsIgnoreCase(sortOrder)) { throw new BadRequestException(String.format("Sort order must be one of '%s' or '%s'. Found %s.", SortOrder.ASC, SortOrder.DESC, sortOrder)); } return new SortInfo(sortBy, SortInfo.SortOrder.valueOf(sortOrder.toUpperCase())); }
From source file:org.sonar.updatecenter.common.PluginReferentialManifestConverter.java
public static PluginReferential fromPluginManifests(List<PluginManifest> pluginManifestList) { List<Plugin> plugins = newArrayList(); for (PluginManifest pluginManifest : pluginManifestList) { Plugin plugin = new Plugin(pluginManifest.getKey()); plugin.merge(pluginManifest);//from w ww . j av a 2s .c o m Release release = new Release(plugin, pluginManifest.getVersion()); release.addRequiredSonarVersions(Version.create(pluginManifest.getSonarVersion())); plugin.addRelease(release); plugins.add(plugin); } PluginReferential pluginReferential = PluginReferential.create(plugins); for (PluginManifest pluginManifest : pluginManifestList) { Plugin plugin = pluginReferential.findPlugin(pluginManifest.getKey()); String parentKey = pluginManifest.getParent(); if (StringUtils.isNotBlank(parentKey)) { Release release = plugin.getLastRelease(); pluginReferential.setParent(release, parentKey); } } for (PluginManifest pluginManifest : pluginManifestList) { Plugin plugin = pluginReferential.findPlugin(pluginManifest.getKey()); for (String requiresPluginKey : pluginManifest.getRequirePlugins()) { if (StringUtils.isNotBlank(requiresPluginKey)) { for (Release release : plugin.getReleases()) { Iterator<String> split = Splitter.on(':').split(requiresPluginKey).iterator(); String requiredPluginReleaseKey = split.next(); String requiredMinimumReleaseVersion = split.next(); pluginReferential.addOutgoingDependency(release, requiredPluginReleaseKey, requiredMinimumReleaseVersion); } } } } return pluginReferential; }
From source file:org.gradle.api.internal.PropertiesUtils.java
/** * Writes a {@link java.util.Properties} in a way that the results can be expected to be reproducible. * * <p>There are a number of differences compared to {@link java.util.Properties#store(java.io.Writer, String)}:</p> * <ul>//from w ww .j a va 2 s. co m * <li>no timestamp comment is generated at the beginning of the file</li> * <li>the lines in the resulting files are separated by a pre-set separator (defaults to * {@literal '\n'}) instead of the system default line separator</li> * <li>the properties are sorted alphabetically</li> * </ul> * * <p>Like with {@link java.util.Properties#store(java.io.OutputStream, String)}, Unicode characters are * escaped when using the default Latin-1 (ISO-8559-1) encoding.</p> */ public static void store(Properties properties, OutputStream outputStream, String comment, Charset charset, String lineSeparator) throws IOException { String rawContents; if (charset.equals(Charsets.ISO_8859_1)) { ByteArrayOutputStream out = new ByteArrayOutputStream(); properties.store(out, comment); rawContents = new String(out.toByteArray(), Charsets.ISO_8859_1); } else { StringWriter out = new StringWriter(); properties.store(out, comment); rawContents = out.toString(); } String systemLineSeparator = SystemProperties.getInstance().getLineSeparator(); List<String> lines = Lists .newArrayList(Splitter.on(systemLineSeparator).omitEmptyStrings().split(rawContents)); int lastCommentLine = -1; for (int lineNo = 0, len = lines.size(); lineNo < len; lineNo++) { String line = lines.get(lineNo); if (line.startsWith("#")) { lastCommentLine = lineNo; } } // The last comment line is the timestamp List<String> nonCommentLines; if (lastCommentLine != -1) { lines.remove(lastCommentLine); nonCommentLines = lines.subList(lastCommentLine, lines.size()); } else { nonCommentLines = lines; } Collections.sort(nonCommentLines); String contents = Joiner.on(lineSeparator).join(lines); outputStream.write(contents.getBytes(charset)); }
From source file:com.bennavetta.aeneas.mesos.slave.docker.Daemon.java
private static void mountFilesystems() throws IOException { Path cgroup = Paths.get("/sys/fs/cgroup"); if (!Files.isDirectory(cgroup)) Files.createDirectory(cgroup); LOG.debug("Creating '{}' tmpfs", cgroup); if (!isMountpoint(cgroup)) { try {//from w w w. ja v a 2 s . c o m mount(cgroup, "cgroup", "tmpfs", "uid=0,gid=0,mode=0755", false); } catch (IOException e) { throw new IOException("Could not make a tmpfs mount. Was the --privileged flag used?", e); } } Path security = Paths.get("/sys/kernel/security"); LOG.debug("Creating security file system in '{}'", security); if (Files.isDirectory(security) && !isMountpoint(security)) { try { mount(security, "none", "securityfs", null, true); } catch (IOException e) { LOG.warn("Could not mount {}. AppArmor detection and --privileged mode might break.", security); } } String cgroupsText = new String(Files.readAllBytes(Paths.get("/proc/1/cgroup"))); List<String> cgroups = StreamSupport.stream(Splitter.on('\n').split(cgroupsText).spliterator(), false) .filter(s -> !s.trim().isEmpty()).map(s -> Splitter.on(':').split(s)).map(i -> Iterables.get(i, 1)) .collect(Collectors.toList()); for (String subsystem : cgroups) { LOG.debug("Creating '{}' cgroup", subsystem); Path subsysPath = cgroup.resolve(subsystem); if (!Files.isDirectory(subsysPath)) Files.createDirectory(subsysPath); if (!isMountpoint(subsysPath)) { mount(subsysPath, "cgroup", "cgroup", subsystem, false); } /* * Address some bugs * See https://github.com/jpetazzo/dind/blob/master/wrapdocker */ if (subsystem.startsWith("name=")) { String name = subsystem.substring(6); Files.createSymbolicLink(cgroup.resolve(name), Paths.get(subsystem)); } if (subsystem.equals("cpuacct,cpu")) { Files.createSymbolicLink(cgroup.resolve("cpu,cpuacct"), Paths.get(subsystem)); } } if (!cgroupsText.contains(":devices:")) { LOG.warn("The 'devices' cgroup should be in its own hierarchy."); } if (!Iterables.contains(Splitter.on(CharMatcher.BREAKING_WHITESPACE).split(cgroupsText), "devices")) { LOG.warn("The 'devices' cgroup does not appear to be mounted."); } }
From source file:org.sonar.batch.issue.tracking.DefaultServerLineHashesLoader.java
@Override public String[] getLineHashes(String fileKey, @Nullable MutableBoolean fromCache) { String hashesFromWs = loadHashesFromWs(fileKey, fromCache); return Iterators.toArray(Splitter.on('\n').split(hashesFromWs).iterator(), String.class); }
From source file:gobblin.compaction.mapreduce.avro.ConfBasedDeltaFieldProvider.java
public ConfBasedDeltaFieldProvider(Configuration conf) { String deltaConfValue = conf.get(DELTA_FIELDS_KEY); if (deltaConfValue == null) { this.deltaFields = new ArrayList<>(); } else {/* w w w . ja v a2 s. c om*/ this.deltaFields = Splitter.on(',').omitEmptyStrings().trimResults().splitToList(deltaConfValue); } }
From source file:io.prestosql.plugin.thrift.location.ExtendedSimpleAddressSelector.java
@Override public Optional<SimpleAddress> selectAddress(Optional<String> context, Set<SimpleAddress> attempted) { if (!context.isPresent()) { return delegate.selectAddress(context, attempted); }/*w ww . j a v a2 s. c o m*/ List<String> list = Splitter.on(',').splitToList(context.get()); String value = list.get(ThreadLocalRandom.current().nextInt(list.size())); HostAndPort address = HostAndPort.fromString(value); return Optional.of(new SimpleAddress(address)); }
From source file:org.n52.geolabel.server.config.TransformationDescriptionResources.java
@Inject public TransformationDescriptionResources(@Named("transformer.resources") String resourcesString, @Named(GeoLabelConfig.DRILLDOWN_EXTERNAL_ENDPOINT) String drilldownEndpoint) { this.drilldownEndpoint = drilldownEndpoint; Map<String, String> splitted = Splitter.on(",").withKeyValueSeparator("=").split(resourcesString); for (Entry<String, String> entry : splitted.entrySet()) try {/*from ww w .jav a 2 s. c o m*/ this.resources.put(new URL(entry.getKey()), entry.getValue()); log.debug("Added transformation resource {} with fallback {}", entry.getKey(), entry.getValue()); } catch (MalformedURLException e) { log.error("Could not create transformation description resources.", e); } }
From source file:omero.cmd.graphs.GraphUtil.java
/** * Split a list of strings by a given separator, trimming whitespace and ignoring empty items. * @param separator the separator between the list items * @param list the list// w w w.j a v a2 s . co m * @return a means of iterating over the list items */ private static Iterable<String> splitList(char separator, String list) { return Splitter.on(separator).trimResults().omitEmptyStrings().split(list); }