List of usage examples for com.google.common.base Splitter split
@CheckReturnValue public Iterable<String> split(final CharSequence sequence)
From source file:org.opendaylight.netconf.sal.restconf.impl.RestconfImpl.java
private static QName getModuleNameAndRevision(final String identifier) { final int mountIndex = identifier.indexOf(ControllerContext.MOUNT); String moduleNameAndRevision = ""; if (mountIndex >= 0) { moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length()); } else {//from ww w . j a v a 2 s. c o m moduleNameAndRevision = identifier; } final Splitter splitter = Splitter.on("/").omitEmptyStrings(); final Iterable<String> split = splitter.split(moduleNameAndRevision); final List<String> pathArgs = Lists.<String>newArrayList(split); if (pathArgs.size() < 2) { LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier); throw new RestconfDocumentedException( "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } try { final String moduleName = pathArgs.get(0); final String revision = pathArgs.get(1); final Date moduleRevision = REVISION_FORMAT.parse(revision); return QName.create(null, moduleRevision, moduleName); } catch (final ParseException e) { LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier); throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE); } }
From source file:org.atlasapi.AtlasModule.java
private List<ServerAddress> mongoHosts() { Splitter splitter = Splitter.on(",").omitEmptyStrings().trimResults(); return ImmutableList.copyOf(Iterables .filter(Iterables.transform(splitter.split(mongoHost), new Function<String, ServerAddress>() { @Override/*from ww w . ja v a 2s. co m*/ public ServerAddress apply(String input) { try { return new ServerAddress(input, 27017); } catch (UnknownHostException e) { return null; } } }), Predicates.notNull())); }
From source file:com.commercehub.bamboo.plugins.grailswrapper.GrailsWrapperTask.java
@NotNull private Iterable<List<String>> parseCommands(@NotNull TaskContext taskContext) { ConfigurationMap configurationMap = taskContext.getConfigurationMap(); String rawCommands = configurationMap.get(GrailsWrapperTaskConfigurator.COMMANDS); String rawCommonOpts = configurationMap.get(GrailsWrapperTaskConfigurator.COMMON_OPTIONS); String commonOpts = Utils.ensureEndsWith(Strings.nullToEmpty(rawCommonOpts), " "); Splitter splitter = Splitter.onPattern("[\r\n]").trimResults().omitEmptyStrings(); Iterable<String> splitCommands = splitter.split(rawCommands); Function<String, String> commonOptsFunction = new StringPrependFunction(commonOpts); Function<String, List<String>> tokenizeFunction = CommandlineStringUtils.tokeniseCommandlineFunction(); return Iterables.transform(splitCommands, Functions.compose(tokenizeFunction, commonOptsFunction)); }
From source file:com.optimaize.langdetect.profiles.util.LanguageProfileValidator.java
private List<TextObject> partition() { List<TextObject> result = new ArrayList<>(this.k); if (!breakWords) { int maxLength = this.inputSample.length() / (this.k - 1); Pattern p = Pattern.compile("\\G\\s*(.{1," + maxLength + "})(?=\\s|$)", Pattern.DOTALL); Matcher m = p.matcher(this.inputSample); while (m.find()) result.add(textObjectFactory.create().append(m.group(1))); } else {// w w w. j av a 2 s . c o m Splitter splitter = Splitter.fixedLength(this.k); for (String token : splitter.split(this.inputSample.toString())) { result.add(textObjectFactory.create().append(token)); } } return result; }
From source file:com.facebook.buck.intellij.ideabuck.api.BuckTarget.java
/** * Returns a syntatically valid (but semantically different) variation of this target, with * hierarchical path elements in the rule name moved to the path. Example, {@code foo//bar:baz/qux * => foo//bar/baz:qux}./*from www .j av a 2 s .c o m*/ * * <p>This conceit is imperfect but somewhat useful to resolve targets targets inside extension * files, as this sometimes allows intrafile targets to be syntactically resolved. * * <p>Note that while some tools will resolve these targets similarly, they are not semantically * interchangeable: {@code foo//bar:baz/qux} refers to a target in the buildfile in {@code * foo/bar}, while {@code foo//bar/baz:qux} refers to a target in the buildfile in {@code * foo/bar/baz}. Furthermore, when using a {@link BuckTarget} to represent the first argument to a * {@code load()} directive, if there were a buildfile present in foo/bar/baz, it would be * incorrect to use {@code foo/bar:baz/qux}, as this would cross a package boundary. */ public Optional<BuckTarget> flatten() { if (!ruleName.contains("/")) { return Optional.of(this); } if (cellPath == null) { return Optional.empty(); } List<String> pieces = new ArrayList<>(); Splitter splitter = Splitter.on('/').omitEmptyStrings(); splitter.split(cellPath).forEach(pieces::add); splitter.split(ruleName).forEach(pieces::add); String newRule = pieces.remove(pieces.size() - 1); String newPath = Joiner.on('/').join(pieces); if (ruleName.endsWith("/")) { newRule += '/'; } return Optional.of(new BuckTarget(cellName, newPath, newRule)); }
From source file:it.tidalwave.northernwind.rca.ui.contentmanager.impl.DefaultAddContentPresentationControl.java
/******************************************************************************************************************* * ******************************************************************************************************************/ private void createContent(final @Nonnull Content parentContent) throws IOException { final DateTime creationDateTime = new DateTime(); final String folderName = urlEncoded(bindings.folder.get()); // TODO: use TypeSafeMap, with a safe put() method final Map<Key<?>, Object> propertyValues = new HashMap<>(); putIfNonEmpty(propertyValues, PROPERTY_TITLE, bindings.title.get()); putIfNonEmpty(propertyValues, PROPERTY_EXPOSED_URI, bindings.exposedUri.get()); putIfNonEmpty(propertyValues, PROPERTY_CREATION_TIME, ISO_FORMATTER.print(creationDateTime)); putIfNonEmpty(propertyValues, PROPERTY_PUBLISHING_TIME, bindings.publishingDateTime.get()); putIfNonEmpty(propertyValues, PROPERTY_FULL_TEXT, xhtmlSkeleton); putIfNonEmpty(propertyValues, PROPERTY_ID, idFactory.createId()); final Splitter splitter = Splitter.on(',').trimResults().omitEmptyStrings(); final List<String> tags = Lists.newArrayList(splitter.split(bindings.tags.get())); if (!tags.isEmpty()) { // See NWRCA-69 propertyValues.put(PROPERTY_TAGS, tags.stream().collect(joining(","))); // propertyValues.put(PROPERTY_TAGS, tags); }/*from w w w .j av a2 s . c om*/ parentContent.as(ContentChildCreator).createContent(folderName, propertyValues); }
From source file:edu.umich.robot.SoarParametersView.java
public void showDialog(JFrame top) { final JDialog d = new JDialog(top, "Soar Parameters"); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { d.dispose();/* www . j a v a 2 s.co m*/ } }); ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { for (Map.Entry<LearnSetting, JRadioButton> entry : learnButtons.entrySet()) if (entry.getValue().isSelected()) properties.set(AgentProperties.LEARN, entry.getKey()); properties.set(AgentProperties.EPMEM_LEARNING, epmemLearn.isSelected()); properties.set(AgentProperties.SMEM_LEARNING, smemLearn.isSelected()); Splitter splitter = Splitter.onPattern("\\s+"); List<String> exclusions = Lists.newArrayList(splitter.split(epmemExclusions.getText())); properties.set(AgentProperties.EPMEM_EXCLUSIONS, exclusions.toArray(new String[exclusions.size()])); for (Map.Entry<PropertyKey<String>, JTextField> entry : spFields.entrySet()) properties.set(entry.getKey(), entry.getValue().getText()); for (Map.Entry<Mission, JRadioButton> entry : missionButtons.entrySet()) if (entry.getValue().isSelected()) properties.set(AgentProperties.MISSION, entry.getKey()); splitter = Splitter.on("\n").omitEmptyStrings(); List<String> miscCommands = Lists.newArrayList(splitter.split(misc.getText())); properties.set(AgentProperties.MISC_COMMANDS, miscCommands.toArray(new String[miscCommands.size()])); d.dispose(); } }); d.setContentPane(panel); d.pack(); d.setLocationRelativeTo(top); d.setVisible(true); }
From source file:uk.q3c.krail.core.navigate.sitemap.DefaultAnnotationSitemapLoader.java
/** * Scans for {@link View} annotations, starting from the reflectionRoot (the key for the AnnotationEntry). Annotations cannot hold enum parameters, so * the enum name has to be converted from the labelKeyName parameter of the {@link View} annotation. If a class has the {@link View} annotation, but does * not implement {@link KrailView}, then it is ignored. * <p/>//w ww. java 2s. c o m * <br> * Also scans for the {@link RedirectFrom} annotation, and populates the {@link MasterSitemap} redirects with the appropriate entries. If a class is * annotated with {@link RedirectFrom}, but does not implement {@link KrailView}, then the annotation is ignored. * */ @SuppressWarnings("unchecked") @Override public boolean load(MasterSitemap sitemap) { checkNotNull(sitemap); clearCounts(); if (sources != null) { for (Entry<String, AnnotationSitemapEntry> entry : sources.entrySet()) { String source = entry.getKey(); log.debug("scanning {} for View annotations", entry.getKey()); Reflections reflections = new Reflections(entry.getKey()); // find the View annotations Set<Class<?>> typesWithView = reflections.getTypesAnnotatedWith(View.class); log.debug("{} KrailViews with View annotation found", typesWithView.size()); // find the RedirectFrom annotations Set<Class<?>> typesWithRedirectFrom = reflections.getTypesAnnotatedWith(RedirectFrom.class); log.debug("{} KrailViews with RedirectFrom annotation found", typesWithRedirectFrom.size()); // process the View annotations for (Class<?> clazz : typesWithView) { Class<? extends KrailView> viewClass = null; if (KrailView.class.isAssignableFrom(clazz)) { viewClass = (Class<? extends KrailView>) clazz; View annotation = viewClass.getAnnotation(View.class); NodeRecord nodeRecord = new NodeRecord(annotation.uri()); nodeRecord.setViewClass(viewClass); nodeRecord.setPageAccessControl(annotation.pageAccessControl()); nodeRecord.setPositionIndex(annotation.positionIndex()); nodeRecord.setConfiguration(annotation.viewConfiguration()); if (StringUtils.isNotEmpty(annotation.roles())) { Splitter splitter = Splitter.on(",").trimResults(); Iterable<String> roles = splitter.split(annotation.roles()); for (String role : roles) { nodeRecord.addRole(role); } } I18NKey keySample = entry.getValue().getLabelSample(); String keyName = annotation.labelKeyName(); try { I18NKey key = keyFromName(keyName, keySample); nodeRecord.setLabelKey(key); } catch (IllegalArgumentException iae) { addError(source, AnnotationSitemapLoader.LABEL_NOT_VALID, clazz, keyName, keySample.getClass()); } sitemap.append(nodeRecord); } } // process the RedirectFrom annotations for (Class<?> clazz : typesWithRedirectFrom) { Class<? extends KrailView> viewClass = null; if (KrailView.class.isAssignableFrom(clazz)) { viewClass = (Class<? extends KrailView>) clazz; RedirectFrom redirectAnnotation = viewClass.getAnnotation(RedirectFrom.class); View viewAnnotation = viewClass.getAnnotation(View.class); if (viewAnnotation == null) { // report this addWarning(source, REDIRECT_FROM_IGNORED, clazz); } else { String[] sourcePages = redirectAnnotation.sourcePages(); String targetPage = viewAnnotation.uri(); for (String sourcePage : sourcePages) { sitemap.addRedirect(sourcePage, targetPage); } } } } } for (String source : sources.keySet()) { addInfo("Scanned for annotations", "Package name: " + source); } return true; } else { log.info("No Annotations Sitemap sources to load"); return false; } }
From source file:edu.cmu.lti.oaqa.knn4qa.apps.DebugKNNServicImpl.java
@Override void init() throws Exception { if (null == mInMemExtrInterm) showUsageSpecify(CommonParams.EXTRACTOR_TYPE_INTERM_DESC); if (null == mNmslibFields) showUsageSpecify(CommonParams.NMSLIB_FIELDS_PARAM); mQueryGen = new NmslibQueryGenerator(mNmslibFields, mMemIndexPref, mInMemExtrInterm); Splitter splitOnColon = Splitter.on(':'); String host = null;/* w ww. j a va2 s. c o m*/ int port = -1; int part = 0; for (String s : splitOnColon.split(mKnnServiceURL)) { if (0 == part) { host = s; } else if (1 == part) { try { port = Integer.parseInt(s); } catch (NumberFormatException e) { showUsage("Invalid port in the service address in '" + CommonParams.KNN_SERVICE_PARAM + "'"); } } else { showUsage("Extra colon in the service address in '" + CommonParams.KNN_SERVICE_PARAM + "'"); } ++part; } if (part != 2) { showUsage("Invalid format of the service address in '" + CommonParams.KNN_SERVICE_PARAM + "'"); } mKnnServiceTransp = new TSocket(host, port); mKnnServiceTransp.open(); mKnnServiceClient = new QueryService.Client(new TBinaryProtocol(mKnnServiceTransp)); }
From source file:org.apache.cassandra.transport.Client.java
private Message.Request parseLine(String line) { Splitter splitter = Splitter.on(' ').trimResults().omitEmptyStrings(); Iterator<String> iter = splitter.split(line).iterator(); if (!iter.hasNext()) return null; String msgType = iter.next().toUpperCase(); if (msgType.equals("STARTUP")) { Map<String, String> options = new HashMap<String, String>(); options.put(StartupMessage.CQL_VERSION, "3.0.0"); while (iter.hasNext()) { String next = iter.next(); if (next.toLowerCase().equals("snappy")) { options.put(StartupMessage.COMPRESSION, "snappy"); connection.setCompressor(FrameCompressor.SnappyCompressor.instance); }//from w w w .ja va 2 s . co m } return new StartupMessage(options); } else if (msgType.equals("QUERY")) { line = line.substring(6); // Ugly hack to allow setting a page size, but that's playground code anyway String query = line; int pageSize = -1; if (line.matches(".+ !\\d+$")) { int idx = line.lastIndexOf('!'); query = line.substring(0, idx - 1); try { pageSize = Integer.parseInt(line.substring(idx + 1, line.length())); } catch (NumberFormatException e) { return null; } } return new QueryMessage(query, QueryOptions.create(ConsistencyLevel.ONE, Collections.<ByteBuffer>emptyList(), false, pageSize, null, null)); } else if (msgType.equals("PREPARE")) { String query = line.substring(8); return new PrepareMessage(query); } else if (msgType.equals("EXECUTE")) { try { byte[] id = Hex.hexToBytes(iter.next()); List<ByteBuffer> values = new ArrayList<ByteBuffer>(); while (iter.hasNext()) { String next = iter.next(); ByteBuffer bb; try { int v = Integer.parseInt(next); bb = Int32Type.instance.decompose(v); } catch (NumberFormatException e) { bb = UTF8Type.instance.decompose(next); } values.add(bb); } return new ExecuteMessage(MD5Digest.wrap(id), QueryOptions.forInternalCalls(ConsistencyLevel.ONE, values)); } catch (Exception e) { return null; } } else if (msgType.equals("OPTIONS")) { return new OptionsMessage(); } else if (msgType.equals("CREDENTIALS")) { System.err.println("[WARN] CREDENTIALS command is deprecated, use AUTHENTICATE instead"); CredentialsMessage msg = new CredentialsMessage(); msg.credentials.putAll(readCredentials(iter)); return msg; } else if (msgType.equals("AUTHENTICATE")) { Map<String, String> credentials = readCredentials(iter); if (!credentials.containsKey(PasswordAuthenticator.USERNAME_KEY) || !credentials.containsKey(PasswordAuthenticator.PASSWORD_KEY)) { System.err.println("[ERROR] Authentication requires both 'username' and 'password'"); return null; } return new AuthResponse(encodeCredentialsForSasl(credentials)); } else if (msgType.equals("REGISTER")) { String type = line.substring(9).toUpperCase(); try { return new RegisterMessage(Collections.singletonList(Enum.valueOf(Event.Type.class, type))); } catch (IllegalArgumentException e) { System.err.println("[ERROR] Unknown event type: " + type); return null; } } return null; }