List of usage examples for com.google.common.base Splitter split
@CheckReturnValue public Iterable<String> split(final CharSequence sequence)
From source file:com.haulmont.cuba.core.sys.AppComponents.java
private void load(AppComponent component) { try {/*from w w w. j ava 2s . c om*/ Document doc = getDescriptorDoc(component); String dependsOnAttr = doc.getRootElement().attributeValue("dependsOn"); if (!StringUtils.isEmpty(dependsOnAttr)) { for (String depCompId : splitCommaSeparatedValue(dependsOnAttr)) { AppComponent depComp = get(depCompId); if (depComp == null) { depComp = new AppComponent(depCompId); load(depComp); components.add(depComp); } component.addDependency(depComp); } } for (Element moduleEl : Dom4j.elements(doc.getRootElement(), "module")) { String blocksAttr = moduleEl.attributeValue("blocks"); if (StringUtils.isEmpty(blocksAttr)) continue; List<String> blocks = splitCommaSeparatedValue(blocksAttr); if (blocks.contains("*") || blocks.contains(block)) { for (Element propertyEl : Dom4j.elements(moduleEl, "property")) { String name = propertyEl.attributeValue("name"); String value = propertyEl.attributeValue("value"); String existingValue = component.getProperty(name); if (value.startsWith("\\+")) { if (existingValue != null) { log.debug("Overwrite value of property {} from {} to {}", name, existingValue, value); } component.setProperty(name, value.substring(1), false); continue; } if (!value.startsWith("+")) { if (existingValue != null) { log.debug("Overwrite value of property {} from {} to {}", name, existingValue, value); } component.setProperty(name, value, false); continue; } String cleanValue = value.substring(1); if (existingValue != null) { String newValue = existingValue; Splitter splitter = Splitter.on(AppProperties.SEPARATOR_PATTERN).omitEmptyStrings(); List<String> existingParts = splitter.splitToList(existingValue); for (String part : splitter.split(cleanValue)) { if (!existingParts.contains(part)) newValue += " " + part; } component.setProperty(name, newValue, true); } else { component.setProperty(name, cleanValue, true); } } } } } catch (IOException | DocumentException e) { throw new RuntimeException("Error loading app component '" + component + "'", e); } }
From source file:com.android.manifmerger.XmlAttribute.java
/** * Handles tools: namespace attributes presence in both documents. * @param higherPriority the higherPriority attribute *///from ww w.j a va 2 s . c om private void handleBothToolsAttributePresent(XmlAttribute higherPriority) { // do not merge tools:node attributes, the higher priority one wins. if (getName().getLocalName().equals(NodeOperationType.NODE_LOCAL_NAME)) { return; } // everything else should be merged, duplicates should be eliminated. Splitter splitter = Splitter.on(','); ImmutableSet.Builder<String> targetValues = ImmutableSet.builder(); targetValues.addAll(splitter.split(higherPriority.getValue())); targetValues.addAll(splitter.split(getValue())); higherPriority.getXml().setValue(Joiner.on(',').join(targetValues.build())); }
From source file:edu.mit.streamjit.tuner.OfflineTuner.java
/** * Creates a new {@link Configuration} from the received python dictionary * string. This is not a good way to do. * <p>/*ww w .j a v a 2s. co m*/ * TODO: Need to add a method to {@link Configuration} so that the * configuration object can be updated from the python dict string. Now we * are destructing the old confg object and recreating a new one every time. * Not a appreciatable way. * * @param pythonDict * Python dictionary string. Autotuner gives a dictionary of * features with trial values. * @param config * Old configuration object. * @return New configuration object with updated values from the pythonDict. */ private Configuration rebuildConfiguration(String pythonDict, Configuration config) { // System.out.println(pythonDict); checkNotNull(pythonDict, "Received Python dictionary is null"); pythonDict = pythonDict.replaceAll("u'", ""); pythonDict = pythonDict.replaceAll("':", ""); pythonDict = pythonDict.replaceAll("\\{", ""); pythonDict = pythonDict.replaceAll("\\}", ""); Splitter dictSplitter = Splitter.on(", ").omitEmptyStrings().trimResults(); Configuration.Builder builder = Configuration.builder(); System.out.println("New parameter values from Opentuner..."); for (String s : dictSplitter.split(pythonDict)) { String[] str = s.split(" "); if (str.length != 2) throw new AssertionError("Wrong python dictionary..."); Parameter p = config.getParameter(str[0]); if (p == null) continue; // System.out.println(String.format("\t%s = %s", str[0], str[1])); if (p instanceof IntParameter) { IntParameter ip = (IntParameter) p; builder.addParameter( new IntParameter(ip.getName(), ip.getMin(), ip.getMax(), Integer.parseInt(str[1]))); } else if (p instanceof SwitchParameter<?>) { SwitchParameter sp = (SwitchParameter) p; Class<?> type = sp.getGenericParameter(); int val = Integer.parseInt(str[1]); SwitchParameter<?> sp1 = new SwitchParameter(sp.getName(), type, sp.getUniverse().get(val), sp.getUniverse()); builder.addParameter(sp1); } } return builder.build(); }
From source file:io.prestosql.server.HttpRequestSessionContext.java
private Set<String> parseClientCapabilities(HttpServletRequest servletRequest) { Splitter splitter = Splitter.on(',').trimResults().omitEmptyStrings(); return ImmutableSet .copyOf(splitter.split(nullToEmpty(servletRequest.getHeader(PRESTO_CLIENT_CAPABILITIES)))); }
From source file:com.mapr.synth.samplers.SsnSampler.java
public SsnSampler() { Splitter onComma = Splitter.on(",").trimResults(); try {/*from w w w .j av a 2 s . c om*/ names = null; for (String line : Resources.readLines(Resources.getResource("ssn-seeds"), Charsets.UTF_8)) { if (line.startsWith("#")) { // last comment line contains actual field names names = Lists.newArrayList(onComma.split(line.substring(1))); } else { Preconditions.checkState(names != null); assert names != null; List<String> fields = Lists.newArrayList(onComma.split(line)); for (int i = Integer.parseInt(fields.get(1)); i <= Integer.parseInt(fields.get(1)); i++) { String key = String.format("%03d", i); values.put(key, fields.subList(2, fields.size())); codes.add(key); } } } assert names != null; names = names.subList(2, names.size()); } catch (IOException e) { throw new RuntimeException("Couldn't read built-in resource", e); } }
From source file:bspkrs.util.config.ConfigCategory.java
public void write(BufferedWriter out, int indent) throws IOException { String pad0 = getIndent(indent); String pad1 = getIndent(indent + 1); String pad2 = getIndent(indent + 2); if (comment != null && !comment.isEmpty()) { write(out, pad0, COMMENT_SEPARATOR); write(out, pad0, "# ", name); write(out, pad0,/*www. j av a 2 s . c o m*/ "#--------------------------------------------------------------------------------------------------------#"); Splitter splitter = Splitter.onPattern("\r?\n"); for (String line : splitter.split(comment)) { write(out, pad0, "# ", line); } write(out, pad0, COMMENT_SEPARATOR, NEW_LINE); } if (!allowedProperties.matchesAllOf(name)) { name = '"' + name + '"'; } write(out, pad0, name, " {"); Property[] props = getOrderedValuesArray(); for (int x = 0; x < props.length; x++) { Property prop = props[x]; if (prop.comment != null && !prop.comment.isEmpty()) { if (x != 0) { out.newLine(); } Splitter splitter = Splitter.onPattern("\r?\n"); for (String commentLine : splitter.split(prop.comment)) { write(out, pad1, "# ", commentLine); } } String propName = prop.getName(); if (!allowedProperties.matchesAllOf(propName)) { propName = '"' + propName + '"'; } if (prop.isList()) { char type = prop.getType().getID(); write(out, pad1, String.valueOf(type), ":", propName, " <"); for (String line : prop.getStringList()) { write(out, pad2, line); } write(out, pad1, " >"); } else if (prop.getType() == null) { write(out, pad1, propName, "=", prop.getString()); } else { char type = prop.getType().getID(); write(out, pad1, String.valueOf(type), ":", propName, "=", prop.getString()); } } if (children.size() > 0) out.newLine(); for (ConfigCategory child : children) { child.write(out, indent + 1); } write(out, pad0, "}", NEW_LINE); }
From source file:com.mapr.synth.samplers.FileSampler.java
private void readDelimitedData(String lookup, List<String> lines) { Splitter splitter; if (lookup.matches(".*\\.csv")) { splitter = Splitter.on(","); } else if (lookup.matches(".*\\.tsv")) { splitter = Splitter.on("\t"); } else {//www . j ava 2 s .c om throw new IllegalArgumentException("Must have file with .csv, .tsv or .json suffix"); } List<String> names = Lists.newArrayList(splitter.split(lines.get(0))); JsonNodeFactory nf = JsonNodeFactory.withExactBigDecimals(false); ArrayNode localData = nf.arrayNode(); for (String line : lines.subList(1, lines.size())) { ObjectNode r = nf.objectNode(); List<String> fields = Lists.newArrayList(splitter.split(line)); Preconditions.checkState(names.size() == fields.size(), "Wrong number of fields, expected ", names.size(), fields.size()); Iterator<String> ix = names.iterator(); for (String field : fields) { r.put(ix.next(), field); } localData.add(r); } data = localData; }
From source file:com.android.tools.idea.structure.services.ServiceContext.java
/** * Converts this service context, which is itself backed by a flat map, into a hierarchical map, * a data structure that freemarker works well with. * <p/>/*from w ww. j av a 2 s . c o m*/ * For example, a service context with the values "parent.child1" and "parent.child2" will return * a map that is nested like so * <pre> * parent * child1 * child2 * </pre> */ @NotNull public Map<String, Object> toValueMap() { Map<String, Object> valueMap = Maps.newHashMap(); Splitter splitter = Splitter.on('.'); for (String key : myValues.keySet()) { ObservableValue value = getValue(key); Map<String, Object> currLevel = valueMap; Iterator<String> keyParts = splitter.split(key).iterator(); while (keyParts.hasNext()) { String keyPart = keyParts.next(); if (keyParts.hasNext()) { if (currLevel.containsKey(keyPart)) { currLevel = (Map<String, Object>) currLevel.get(keyPart); } else { Map<String, Object> nextLevel = Maps.newHashMap(); currLevel.put(keyPart, nextLevel); currLevel = nextLevel; } } else { // We're the last part of the key currLevel.put(keyPart, value); } } } return valueMap; }
From source file:mods.railcraft.common.core.Railcraft.java
@Mod.EventHandler public void processIMCRequests(FMLInterModComms.IMCEvent event) { Splitter splitter = Splitter.on("@").trimResults(); for (FMLInterModComms.IMCMessage mess : event.getMessages()) { if (mess.key.equals("ballast")) { String[] tokens = Iterables.toArray(splitter.split(mess.getStringValue()), String.class); if (tokens.length != 2) { Game.log(Level.WARN, String.format("Mod %s attempted to register a ballast, but failed: %s", mess.getSender(), mess.getStringValue())); continue; }//from w ww. j av a2 s.com String blockName = tokens[0]; Integer metadata = Ints.tryParse(tokens[1]); if (blockName == null || metadata == null) { Game.log(Level.WARN, String.format("Mod %s attempted to register a ballast, but failed: %s", mess.getSender(), mess.getStringValue())); continue; } BallastRegistry.registerBallast(Block.getBlockFromName(blockName), metadata); Game.log(Level.DEBUG, String.format("Mod %s registered %s as a valid ballast", mess.getSender(), mess.getStringValue())); } else if (mess.key.equals("boiler-fuel-liquid")) { String[] tokens = Iterables.toArray(splitter.split(mess.getStringValue()), String.class); if (tokens.length != 2) { Game.log(Level.WARN, String.format("Mod %s attempted to register a liquid Boiler fuel, but failed: %s", mess.getSender(), mess.getStringValue())); continue; } Fluid fluid = FluidRegistry.getFluid(tokens[0]); Integer fuel = Ints.tryParse(tokens[1]); if (fluid == null || fuel == null) { Game.log(Level.WARN, String.format("Mod %s attempted to register a liquid Boiler fuel, but failed: %s", mess.getSender(), mess.getStringValue())); continue; } FuelManager.addBoilerFuel(fluid, fuel); Game.log(Level.DEBUG, String.format("Mod %s registered %s as a valid liquid Boiler fuel", mess.getSender(), mess.getStringValue())); } else if (mess.key.equals("rock-crusher")) { NBTTagCompound nbt = mess.getNBTValue(); ItemStack input = ItemStack.loadItemStackFromNBT(nbt.getCompoundTag("input")); IRockCrusherRecipe recipe = RailcraftCraftingManager.rockCrusher.createNewRecipe(input, nbt.getBoolean("matchMeta"), nbt.getBoolean("matchNBT")); for (int i = 0; i < 9; i++) { if (nbt.hasKey("output" + i)) { NBTTagCompound outputNBT = nbt.getCompoundTag("output" + i); recipe.addOutput(ItemStack.loadItemStackFromNBT(outputNBT), outputNBT.getFloat("chance")); } } } } }
From source file:com.github.ferstl.depgraph.AbstractGraphMojo.java
private void createGraphImage() throws IOException { String graphFileName = createGraphFileName(); Path graphFile = this.outputFile.toPath().getParent().resolve(graphFileName); String dotExecutable = determineDotExecutable(); String[] arguments = new String[] { "-T", this.imageFormat, "-o", graphFile.toAbsolutePath().toString(), this.outputFile.getAbsolutePath() }; Commandline cmd = new Commandline(); cmd.setExecutable(dotExecutable);/*from w w w. j av a2s .c o m*/ cmd.addArguments(arguments); getLog().info("Running Graphviz: " + dotExecutable + " " + Joiner.on(" ").join(arguments)); StringStreamConsumer systemOut = new StringStreamConsumer(); StringStreamConsumer systemErr = new StringStreamConsumer(); int exitCode; try { exitCode = CommandLineUtils.executeCommandLine(cmd, systemOut, systemErr); } catch (CommandLineException e) { throw new IOException("Unable to execute Graphviz", e); } Splitter lineSplitter = Splitter.on(LINE_SEPARATOR_PATTERN).omitEmptyStrings().trimResults(); Iterable<String> output = Iterables.concat(lineSplitter.split(systemOut.getOutput()), lineSplitter.split(systemErr.getOutput())); for (String line : output) { getLog().info(" dot> " + line); } if (exitCode != 0) { throw new IOException("Graphviz terminated abnormally. Exit code: " + exitCode); } getLog().info("Graph image created on " + graphFile.toAbsolutePath()); }