List of usage examples for com.google.common.base Splitter onPattern
@CheckReturnValue @GwtIncompatible("java.util.regex") public static Splitter onPattern(String separatorPattern)
From source file:org.apache.sentry.api.service.thrift.SentryPolicyStoreProcessor.java
@VisibleForTesting static List<NotificationHandler> createHandlers(Configuration conf) throws SentrySiteConfigurationException { List<NotificationHandler> handlers = Lists.newArrayList(); Iterable<String> notificationHandlers = Splitter.onPattern("[\\s,]").trimResults().omitEmptyStrings() .split(conf.get(PolicyStoreServerConfig.NOTIFICATION_HANDLERS, "")); for (String notificationHandler : notificationHandlers) { Class<?> clazz = null; try {//w w w . j a va 2s . co m clazz = Class.forName(notificationHandler); if (!NotificationHandler.class.isAssignableFrom(clazz)) { throw new SentrySiteConfigurationException( "Class " + notificationHandler + " is not a " + NotificationHandler.class.getName()); } } catch (ClassNotFoundException e) { throw new SentrySiteConfigurationException("Value " + notificationHandler + " is not a class", e); } Preconditions.checkNotNull(clazz, "Error class cannot be null"); try { Constructor<?> constructor = clazz.getConstructor(Configuration.class); handlers.add((NotificationHandler) constructor.newInstance(conf)); } catch (Exception e) { throw new SentrySiteConfigurationException("Error attempting to create " + notificationHandler, e); } } return handlers; }
From source file:org.robotframework.ide.eclipse.main.plugin.tableeditor.source.SuiteSourceFormattingStrategy.java
private List<Integer> getCellLenghts(final String line) { final List<String> cells = Splitter.onPattern(" +").splitToList(line); return newArrayList(Iterables.transform(cells, new Function<String, Integer>() { @Override/*from w w w.ja va 2s . co m*/ public Integer apply(final String cellContent) { return cellContent.length(); } })); }
From source file:org.gpfvic.mahout.cf.taste.impl.model.file.FileDataModel.java
/** * @param delimiterRegex If your data file don't use '\t' or ',' as delimiters, you can specify * user own using regex pattern./*w w w. ja v a 2s.c o m*/ * @throws IOException */ public FileDataModel(File dataFile, boolean transpose, long minReloadIntervalMS, String delimiterRegex) throws IOException { this.dataFile = Preconditions.checkNotNull(dataFile.getAbsoluteFile()); if (!dataFile.exists() || dataFile.isDirectory()) { throw new FileNotFoundException(dataFile.toString()); } Preconditions.checkArgument(dataFile.length() > 0L, "dataFile is empty"); Preconditions.checkArgument(minReloadIntervalMS >= 0L, "minReloadIntervalMs must be non-negative"); log.info("Creating FileDataModel for file {}", dataFile); this.lastModified = dataFile.lastModified(); this.lastUpdateFileModified = readLastUpdateFileModified(); FileLineIterator iterator = new FileLineIterator(dataFile, false); String firstLine = iterator.peek(); while (firstLine.isEmpty() || firstLine.charAt(0) == COMMENT_CHAR) { iterator.next(); firstLine = iterator.peek(); } Closeables.close(iterator, true); char delimiter; if (delimiterRegex == null) { delimiter = determineDelimiter(firstLine); delimiterPattern = Splitter.on(delimiter); } else { delimiter = '\0'; delimiterPattern = Splitter.onPattern(delimiterRegex); if (!delimiterPattern.split(firstLine).iterator().hasNext()) { throw new IllegalArgumentException("Did not find a delimiter(pattern) in first line"); } } List<String> firstLineSplit = new ArrayList<>(); for (String token : delimiterPattern.split(firstLine)) { firstLineSplit.add(token); } // If preference value exists and isn't empty then the file is specifying pref values hasPrefValues = firstLineSplit.size() >= 3 && !firstLineSplit.get(2).isEmpty(); this.reloadLock = new ReentrantLock(); this.transpose = transpose; this.minReloadIntervalMS = minReloadIntervalMS; reload(); }
From source file:org.apache.mahout.cf.taste.impl.model.file.FileDataModel.java
/** * @param delimiterRegex If your data file don't use '\t' or ',' as delimiters, you can specify * user own using regex pattern./* w ww.jav a 2 s . co m*/ * @throws IOException */ public FileDataModel(File dataFile, boolean transpose, long minReloadIntervalMS, String delimiterRegex) throws IOException { this.dataFile = Preconditions.checkNotNull(dataFile.getAbsoluteFile()); if (!dataFile.exists() || dataFile.isDirectory()) { throw new FileNotFoundException(dataFile.toString()); } Preconditions.checkArgument(dataFile.length() > 0L, "dataFile is empty"); Preconditions.checkArgument(minReloadIntervalMS >= 0L, "minReloadIntervalMs must be non-negative"); log.info("Creating FileDataModel for file {}", dataFile); this.lastModified = dataFile.lastModified(); this.lastUpdateFileModified = readLastUpdateFileModified(); FileLineIterator iterator = new FileLineIterator(dataFile, false); String firstLine = iterator.peek(); while (firstLine.isEmpty() || firstLine.charAt(0) == COMMENT_CHAR) { iterator.next(); firstLine = iterator.peek(); } Closeables.close(iterator, true); if (delimiterRegex == null) { delimiter = determineDelimiter(firstLine); delimiterPattern = Splitter.on(delimiter); } else { delimiter = '\0'; delimiterPattern = Splitter.onPattern(delimiterRegex); if (!delimiterPattern.split(firstLine).iterator().hasNext()) { throw new IllegalArgumentException("Did not find a delimiter(pattern) in first line"); } } List<String> firstLineSplit = Lists.newArrayList(); for (String token : delimiterPattern.split(firstLine)) { firstLineSplit.add(token); } // If preference value exists and isn't empty then the file is specifying pref values hasPrefValues = firstLineSplit.size() >= 3 && !firstLineSplit.get(2).isEmpty(); this.reloadLock = new ReentrantLock(); this.transpose = transpose; this.minReloadIntervalMS = minReloadIntervalMS; reload(); }
From source file:vogar.Run.java
/** * Returns a parsed list of the --invoke-with command and its * arguments, or an empty list if no --invoke-with was provided. *///from w w w . ja v a2 s . c o m public Iterable<String> invokeWith() { if (invokeWith == null) { return Collections.emptyList(); } return Splitter.onPattern("\\s+").omitEmptyStrings().split(invokeWith); }
From source file:fr.obeo.intent.specification.parser.SpecificationParser.java
private void parseScenarios(IntentSection intentSection, StringBuffer validElements) { // Get valid scenarios StringBuffer validScenarios = new StringBuffer(); for (String element : Splitter.onPattern("\r?\n").trimResults().omitEmptyStrings().split(validElements)) { if (isScenario(element)) { validScenarios.append(element + "\n"); }// www . ja v a 2 s. co m } // "Scenario:" final String scenarioPattern = SpecificationKeyword.SCENARIO.value + COLON; for (String description : Splitter.onPattern(scenarioPattern).trimResults().omitEmptyStrings() .split(validScenarios)) { Iterable<String> results = Splitter.onPattern("\r?\n").trimResults().omitEmptyStrings() .split(scenarioPattern + description); Scenario scenario = null; for (String result : results) { if (result.startsWith(SpecificationKeyword.SCENARIO.value)) { String scenarioDescription = Splitter.on(SpecificationKeyword.SCENARIO.value + COLON) .trimResults().omitEmptyStrings().split(result).iterator().next(); // Scenario: Name [Parent Story] final String scenarioName = scenarioDescription .substring(0, scenarioDescription.indexOf(OPEN_BRACKET)).trim(); NamedElement namedElement = getNamedElement(scenarioName, Scenario.class); if (namedElement == null) { scenario = specificationFactory.createScenario(); scenario.setName(scenarioName); parsedElements.add(new ParsedElement(intentSection, scenario)); } else if (namedElement instanceof Scenario) { scenario = (Scenario) namedElement; } else { throw new UnsupportedOperationException(); } // Scenario: Name [Parent Story] @ui TestGenerationNote testNote = specificationFactory.createTestGenerationNote(); scenario.getNotes().add(testNote); if (scenarioDescription.contains(AROBASE)) { final String scenarioTestType = scenarioDescription .substring(scenarioDescription.indexOf(AROBASE)); if (scenarioTestType.contains(TestType.UI.getName().toLowerCase())) { testNote.setType(TestType.UI); } else if (scenarioTestType.contains(TestType.UNIT.getName().toLowerCase())) { testNote.setType(TestType.UNIT); } else if (scenarioTestType.contains(TestType.PLUGIN.getName().toLowerCase())) { testNote.setType(TestType.PLUGIN); } } String stories = scenarioDescription.substring(scenarioDescription.indexOf(OPEN_BRACKET) + 1, scenarioDescription.indexOf(CLOSE_BRACKET)); for (String storyName : Splitter.on(COMMA).trimResults().omitEmptyStrings().split(stories)) { namedElement = getNamedElement(storyName, Story.class); Story story = null; if (namedElement == null) { story = specificationFactory.createStory(); story.setName(storyName); specification.getStories().add(story); parsedElements.add(new ParsedElement(intentSection, story)); } else if (namedElement instanceof Story) { story = (Story) namedElement; } else { throw new UnsupportedOperationException(); } story.getScenarios().add(scenario); } } else if (result.startsWith(SpecificationKeyword.GIVEN.value)) { String contextName = null; if (result.contains(VARIABLE)) { contextName = Splitter.on(SpecificationKeyword.GIVEN.value + COLON).trimResults() .omitEmptyStrings().split(result.substring(0, result.indexOf(VARIABLE))).iterator() .next(); } else { // Given: MyContext [ParentContext] if (result.contains(OPEN_BRACKET)) { contextName = Splitter.on(SpecificationKeyword.GIVEN.value + COLON).trimResults() .omitEmptyStrings().split(result.substring(0, result.indexOf(OPEN_BRACKET))) .iterator().next(); } else { // Given: MyContext contextName = Splitter.on(SpecificationKeyword.GIVEN.value + COLON).trimResults() .omitEmptyStrings().split(result).iterator().next(); } } Context parentContext = null; // Given: MyContext [ParentContext] if (result.contains(OPEN_BRACKET) && result.contains(CLOSE_BRACKET)) { String parentContextName = result.substring(result.indexOf(OPEN_BRACKET) + 1, result.indexOf(CLOSE_BRACKET)); NamedElement namedElement = getNamedElement(parentContextName, Context.class); if (namedElement == null) { parentContext = specificationFactory.createContext(); parentContext.setName(parentContextName); automationLayer.getContext().add(parentContext); } else if (namedElement instanceof Context) { parentContext = (Context) namedElement; } } NamedElement namedElement = getNamedElement(contextName, Context.class); Context context = null; if (namedElement == null) { context = specificationFactory.createContext(); context.setName(contextName); if (parentContext != null) { context.getContexts().add(parentContext); } automationLayer.getContext().add(context); } else if (namedElement instanceof Context) { context = (Context) namedElement; } else { throw new UnsupportedOperationException(); } parseParameters(result, context, scenario); scenario.getGiven().add(context); } else if (result.startsWith(SpecificationKeyword.WHEN.value)) { String actionName = null; if (result.contains(VARIABLE)) { actionName = Splitter.on(SpecificationKeyword.WHEN.value + COLON).trimResults() .omitEmptyStrings().split(result.substring(0, result.indexOf(VARIABLE))).iterator() .next(); } else { actionName = Splitter.on(SpecificationKeyword.WHEN.value + COLON).trimResults() .omitEmptyStrings().split(result).iterator().next(); } NamedElement namedElement = getNamedElement(actionName, Action.class); Action action = null; if (namedElement == null) { action = specificationFactory.createAction(); action.setName(actionName); automationLayer.getActions().add(action); } else if (namedElement instanceof Action) { action = (Action) namedElement; } else { throw new UnsupportedOperationException(); } parseParameters(result, action, scenario); scenario.getWhen().add(action); } else if (result.startsWith(SpecificationKeyword.THEN.value)) { String behaviourName = null; if (result.contains(VARIABLE)) { behaviourName = Splitter.on(SpecificationKeyword.THEN.value + COLON).trimResults() .omitEmptyStrings().split(result.substring(0, result.indexOf(VARIABLE))).iterator() .next(); } else { behaviourName = Splitter.on(SpecificationKeyword.THEN.value + COLON).trimResults() .omitEmptyStrings().split(result).iterator().next(); } NamedElement namedElement = getNamedElement(behaviourName, Behaviour.class); Behaviour behaviour = null; if (namedElement == null) { behaviour = specificationFactory.createBehaviour(); behaviour.setName(behaviourName); automationLayer.getBehaviours().add(behaviour); } else if (namedElement instanceof Behaviour) { behaviour = (Behaviour) namedElement; } else { throw new UnsupportedOperationException(); } parseParameters(result, behaviour, scenario); scenario.getThen().add(behaviour); } } } }
From source file:keepcalm.programs.idfixer.Configuration.java
private void save(BufferedWriter out) throws IOException { for (Map.Entry<String, Map<String, Property>> category : categories.entrySet()) { out.write("####################\r\n"); out.write("# " + category.getKey() + " \r\n"); if (customCategoryComments.containsKey(category.getKey())) { out.write("#===================\r\n"); String comment = customCategoryComments.get(category.getKey()); Splitter splitter = Splitter.onPattern("\r?\n"); for (String commentLine : splitter.split(comment)) { out.write("# "); out.write(commentLine + "\r\n"); }//from ww w. j a va2 s . c o m } out.write("####################\r\n\r\n"); String catKey = category.getKey(); if (!allowedProperties.matchesAllOf(catKey)) { catKey = '"' + catKey + '"'; } out.write(catKey + " {\r\n"); writeProperties(out, category.getValue().values()); out.write("}\r\n\r\n"); } }
From source file:keepcalm.programs.idfixer.Configuration.java
private void writeProperties(BufferedWriter buffer, Collection<Property> props) throws IOException { for (Property property : props) { if (property.comment != null) { Splitter splitter = Splitter.onPattern("\r?\n"); for (String commentLine : splitter.split(property.comment)) { buffer.write(" # " + commentLine + "\r\n"); }//from w w w . ja va2 s. c o m } String propName = property.getName(); if (!allowedProperties.matchesAllOf(propName)) { propName = '"' + propName + '"'; } buffer.write(" " + propName + "=" + property.value); buffer.write("\r\n"); } }
From source file:com.facebook.buck.apple.project_generator.XCodeProjectCommandHelper.java
private FocusedModuleTargetMatcher getFocusModules(ListeningExecutorService executor) throws IOException, InterruptedException { if (modulesToFocusOn == null) { return FocusedModuleTargetMatcher.noFocus(); }// w w w. j a v a 2s. c om Iterable<String> patterns = Splitter.onPattern("\\s+").split(modulesToFocusOn); // Parse patterns with the following syntax: // https://buckbuild.com/concept/build_target_pattern.html ImmutableList<TargetNodeSpec> specs = argsParser.apply(patterns); // Resolve the list of targets matching the patterns. ImmutableSet<BuildTarget> passedInTargetsSet; ParserConfig parserConfig = buckConfig.getView(ParserConfig.class); try { passedInTargetsSet = parser .resolveTargetSpecs(buckEventBus, cell, enableParserProfiling, executor, specs, SpeculativeParsing.of(false), parserConfig.getDefaultFlavorsMode()) .stream().flatMap(Collection::stream).map(target -> target.withoutCell()) .collect(MoreCollectors.toImmutableSet()); } catch (BuildTargetException | BuildFileParseException | HumanReadableException e) { buckEventBus.post(ConsoleEvent.severe(MoreExceptions.getHumanReadableOrLocalizedMessage(e))); return FocusedModuleTargetMatcher.noFocus(); } LOG.debug("Selected targets: %s", passedInTargetsSet.toString()); ImmutableSet<UnflavoredBuildTarget> passedInUnflavoredTargetsSet = RichStream.from(passedInTargetsSet) .map(BuildTarget::getUnflavoredBuildTarget).toImmutableSet(); LOG.debug("Selected unflavored targets: %s", passedInUnflavoredTargetsSet.toString()); return FocusedModuleTargetMatcher.focusedOn(passedInUnflavoredTargetsSet); }
From source file:com.facebook.buck.features.apple.project.XCodeProjectCommandHelper.java
private FocusedModuleTargetMatcher getFocusModules() throws IOException, InterruptedException { if (modulesToFocusOn == null) { return FocusedModuleTargetMatcher.noFocus(); }/*from w ww.j ava 2 s . c o m*/ Iterable<String> patterns = Splitter.onPattern("\\s+").split(modulesToFocusOn); // Parse patterns with the following syntax: // https://buckbuild.com/concept/build_target_pattern.html ImmutableList<TargetNodeSpec> specs = argsParser.apply(patterns); // Resolve the list of targets matching the patterns. ImmutableSet<BuildTarget> passedInTargetsSet; try { passedInTargetsSet = parser .resolveTargetSpecs(parsingContext.withSpeculativeParsing(SpeculativeParsing.DISABLED), specs, targetConfiguration) .stream().flatMap(Collection::stream).collect(ImmutableSet.toImmutableSet()); } catch (HumanReadableException e) { buckEventBus.post(ConsoleEvent.severe(MoreExceptions.getHumanReadableOrLocalizedMessage(e))); return FocusedModuleTargetMatcher.noFocus(); } LOG.debug("Selected targets: %s", passedInTargetsSet.toString()); ImmutableSet<UnflavoredBuildTarget> passedInUnflavoredTargetsSet = RichStream.from(passedInTargetsSet) .map(BuildTarget::getUnflavoredBuildTarget).toImmutableSet(); LOG.debug("Selected unflavored targets: %s", passedInUnflavoredTargetsSet.toString()); return FocusedModuleTargetMatcher.focusedOn(passedInUnflavoredTargetsSet); }