List of usage examples for com.google.common.collect Iterables toString
public static String toString(Iterable<?> iterable)
From source file:clocker.docker.location.DockerLocation.java
@Override public MachineLocation obtain(Map<?, ?> flags) throws NoMachinesAvailableException { // Check context for entity being deployed Object context = flags.get(LocationConfigKeys.CALLER_CONTEXT.getName()); if (context != null && !(context instanceof Entity)) { throw new IllegalStateException("Invalid location context: " + context); }/*from w w w .ja v a2 s . c o m*/ Entity entity = (Entity) context; // Get the available hosts List<DockerHostLocation> available = getDockerHostLocations(); LOG.debug("Placement for: {}", Iterables.toString(Iterables.transform(available, EntityFunctions.id()))); // Apply placement strategies List<DockerAwarePlacementStrategy> entityStrategies = entity.config() .get(DockerAttributes.PLACEMENT_STRATEGIES); if (entityStrategies == null) entityStrategies = ImmutableList.of(); for (DockerAwarePlacementStrategy strategy : Iterables.concat(strategies, entityStrategies)) { available = strategy.filterLocations(available, entity); LOG.debug("Placement after {}: {}", strategy, Iterables.toString(Iterables.transform(available, EntityFunctions.id()))); } // Use the provisioning strategy to add a new host DockerHostLocation machine = null; DockerHost dockerHost = null; if (available.size() > 0) { machine = available.get(0); dockerHost = machine.getOwner(); } else { // Get permission to create a new Docker host if (permit.tryAcquire()) { try { // Determine if headroom scaling policy is being used and suspend Integer headroom = getOwner().config().get(ContainerHeadroomEnricher.CONTAINER_HEADROOM); Double headroomPercent = getOwner().config() .get(ContainerHeadroomEnricher.CONTAINER_HEADROOM_PERCENTAGE); boolean headroomSet = (headroom != null && headroom > 0) || (headroomPercent != null && headroomPercent > 0d); Optional<Policy> policy = Iterables.tryFind(getOwner().getDockerHostCluster().policies(), Predicates.instanceOf(AutoScalerPolicy.class)); if (headroomSet && policy.isPresent()) policy.get().suspend(); try { // Resize the host cluster LOG.info("Provisioning new host"); Entity added = Iterables.getOnlyElement(getOwner().getDockerHostCluster().resizeByDelta(1)); dockerHost = (DockerHost) added; machine = dockerHost.getDynamicLocation(); // Update autoscaler policy with new minimum size and resume if (headroomSet && policy.isPresent()) { int currentMin = policy.get().config().get(AutoScalerPolicy.MIN_POOL_SIZE); LOG.info("Updating autoscaler policy ({}) setting {} to {}", new Object[] { policy.get(), AutoScalerPolicy.MIN_POOL_SIZE.getName(), currentMin + 1 }); policy.get().config().set(AutoScalerPolicy.MIN_POOL_SIZE, currentMin + 1); } } finally { if (policy.isPresent()) policy.get().resume(); } } finally { permit.release(); } } else { // Wait until whoever has the permit releases it, and try again try { permit.acquire(); } catch (InterruptedException ie) { Exceptions.propagate(ie); } finally { permit.release(); } return obtain(flags); } } // Now wait until the host has started up Entities.waitForServiceUp(dockerHost); // Obtain a new Docker container location, save and return it try { LOG.debug("Obtain a new container from {} for {}", machine, entity); Map<?, ?> hostFlags = MutableMap.copyOf(flags); DockerContainerLocation container = machine.obtain(hostFlags); containers.put(machine, container.getId()); return container; } finally { // Release any placement strategy locks for (DockerAwarePlacementStrategy strategy : Iterables.concat(strategies, entityStrategies)) { if (strategy instanceof WithMutexes) { ((WithMutexes) strategy).releaseMutex(entity.getApplicationId()); } } } }
From source file:brooklyn.entity.network.bind.BindDnsServerImpl.java
public void update() { Lifecycle serverState = getAttribute(Attributes.SERVICE_STATE_ACTUAL); if (Lifecycle.STOPPED.equals(serverState) || Lifecycle.STOPPING.equals(serverState) || Lifecycle.DESTROYED.equals(serverState) || !getAttribute(Attributes.SERVICE_UP)) { LOG.debug("Skipped update of {} when service state is {} and running is {}", new Object[] { this, getAttribute(Attributes.SERVICE_STATE_ACTUAL), getAttribute(SERVICE_UP) }); return;/*ww w. j a v a 2 s . co m*/ } synchronized (this) { Iterable<Entity> availableEntities = FluentIterable.from(getEntities().getMembers()) .filter(new HasHostnameAndValidLifecycle()); LOG.debug("{} updating with entities: {}", this, Iterables.toString(availableEntities)); ImmutableListMultimap<String, Entity> hostnameToEntity = Multimaps.index(availableEntities, new HostnameTransformer()); Map<String, String> octetToName = Maps.newHashMap(); BiMap<String, String> ipToARecord = HashBiMap.create(); Multimap<String, String> aRecordToCnames = MultimapBuilder.hashKeys().hashSetValues().build(); Multimap<String, String> ipToAllNames = MultimapBuilder.hashKeys().hashSetValues().build(); for (Map.Entry<String, Entity> e : hostnameToEntity.entries()) { String domainName = e.getKey(); Maybe<SshMachineLocation> location = Machines .findUniqueSshMachineLocation(e.getValue().getLocations()); if (!location.isPresent()) { LOG.debug("Member {} of {} does not have an SSH location so will not be configured", e.getValue(), this); continue; } else if (ipToARecord.inverse().containsKey(domainName)) { continue; } String address = location.get().getAddress().getHostAddress(); ipToAllNames.put(address, domainName); if (!ipToARecord.containsKey(address)) { ipToARecord.put(address, domainName); if (getReverseLookupNetwork().contains(new Cidr(address + "/32"))) { String octet = Iterables.get(Splitter.on('.').split(address), 3); if (!octetToName.containsKey(octet)) octetToName.put(octet, domainName); } } else { aRecordToCnames.put(ipToARecord.get(address), domainName); } } setAttribute(A_RECORDS, ImmutableMap.copyOf(ipToARecord.inverse())); setAttribute(PTR_RECORDS, ImmutableMap.copyOf(octetToName)); setAttribute(CNAME_RECORDS, Multimaps.unmodifiableMultimap(aRecordToCnames)); setAttribute(ADDRESS_MAPPINGS, Multimaps.unmodifiableMultimap(ipToAllNames)); // Update Bind configuration files and restart the service getDriver().updateBindConfiguration(); } }
From source file:org.apache.brooklyn.entity.network.bind.BindDnsServerImpl.java
public void update() { Lifecycle serverState = getAttribute(Attributes.SERVICE_STATE_ACTUAL); if (Lifecycle.STOPPED.equals(serverState) || Lifecycle.STOPPING.equals(serverState) || Lifecycle.DESTROYED.equals(serverState) || !getAttribute(Attributes.SERVICE_UP)) { LOG.debug("Skipped update of {} when service state is {} and running is {}", new Object[] { this, getAttribute(Attributes.SERVICE_STATE_ACTUAL), getAttribute(SERVICE_UP) }); return;/*from w w w. j a va 2s .com*/ } synchronized (this) { Iterable<Entity> availableEntities = FluentIterable.from(getEntities().getMembers()) .filter(new HasHostnameAndValidLifecycle()); LOG.debug("{} updating with entities: {}", this, Iterables.toString(availableEntities)); ImmutableListMultimap<String, Entity> hostnameToEntity = Multimaps.index(availableEntities, new HostnameTransformer()); Map<String, String> octetToName = Maps.newHashMap(); BiMap<String, String> ipToARecord = HashBiMap.create(); Multimap<String, String> aRecordToCnames = MultimapBuilder.hashKeys().hashSetValues().build(); Multimap<String, String> ipToAllNames = MultimapBuilder.hashKeys().hashSetValues().build(); for (Map.Entry<String, Entity> e : hostnameToEntity.entries()) { String domainName = e.getKey(); Maybe<SshMachineLocation> location = Machines.findUniqueMachineLocation(e.getValue().getLocations(), SshMachineLocation.class); if (!location.isPresent()) { LOG.debug("Member {} of {} does not have an SSH location so will not be configured", e.getValue(), this); continue; } else if (ipToARecord.inverse().containsKey(domainName)) { continue; } String address = location.get().getAddress().getHostAddress(); ipToAllNames.put(address, domainName); if (!ipToARecord.containsKey(address)) { ipToARecord.put(address, domainName); if (getReverseLookupNetwork().contains(new Cidr(address + "/32"))) { String octet = Iterables.get(Splitter.on('.').split(address), 3); if (!octetToName.containsKey(octet)) octetToName.put(octet, domainName); } } else { aRecordToCnames.put(ipToARecord.get(address), domainName); } } sensors().set(A_RECORDS, ImmutableMap.copyOf(ipToARecord.inverse())); sensors().set(PTR_RECORDS, ImmutableMap.copyOf(octetToName)); sensors().set(CNAME_RECORDS, Multimaps.unmodifiableMultimap(aRecordToCnames)); sensors().set(ADDRESS_MAPPINGS, Multimaps.unmodifiableMultimap(ipToAllNames)); // Update Bind configuration files and restart the service getDriver().updateBindConfiguration(); } }
From source file:org.apache.hadoop.metrics2.impl.MetricsConfig.java
ClassLoader getPluginLoader() { if (pluginLoader != null) return pluginLoader; final ClassLoader defaultLoader = getClass().getClassLoader(); Object purls = super.getProperty(PLUGIN_URLS_KEY); if (purls == null) return defaultLoader; Iterable<String> jars = SPLITTER.split((String) purls); int len = Iterables.size(jars); if (len > 0) { final URL[] urls = new URL[len]; try {//from www . j a v a 2s. co m int i = 0; for (String jar : jars) { LOG.debug(jar); urls[i++] = new URL(jar); } } catch (Exception e) { throw new MetricsConfigException(e); } if (LOG.isDebugEnabled()) { LOG.debug("using plugin jars: " + Iterables.toString(jars)); } pluginLoader = doPrivileged(new PrivilegedAction<ClassLoader>() { @Override public ClassLoader run() { return new URLClassLoader(urls, defaultLoader); } }); return pluginLoader; } if (parent instanceof MetricsConfig) { return ((MetricsConfig) parent).getPluginLoader(); } return defaultLoader; }
From source file:eu.interedition.collatex.nmerge.mvd.Variant.java
/** * Compare two Variants. Try to short-circuit the * comparison to reduce computation./*from w w w .j a v a2 s . com*/ * * @param other the variant to compare ourselves to */ public int compareTo(Variant<T> other) { if (this.startIndex < other.startIndex) { return -1; } else if (this.startIndex > other.startIndex) { return 1; } else if (this.startOffset < other.startOffset) { return -1; } else if (this.startOffset > other.startOffset) { return 1; } else if (this.length < other.length) { return -1; } else if (this.length > other.length) { return 1; } else { // FIXME: What is a proper ordering of witness sets? final Joiner joiner = Joiner.on(','); String thisV = joiner.join(versions); String thatV = joiner.join(other.versions); int res = thisV.compareTo(thatV); if (res != 0) { return res; } else { // FIXME: introduce token comparator to do a proper comparison return Iterables.toString(data).compareTo(Iterables.toString(other.data)); } } }
From source file:org.apache.jackrabbit.oak.plugins.index.solr.configuration.nodestate.OakSolrNodeStateConfiguration.java
@Override public String toString() { return "OakSolrNodeStateConfiguration{" + "definitionChildren=" + Iterables.toString(definition.getChildNodeNames()) + '}'; }
From source file:io.sarl.maven.docs.generator.SARLDocGenerate.java
@Override protected void compile(XtendBatchCompiler xtend2BatchCompiler, String classPath, List<String> sourceDirectories, String outputPath) throws MojoExecutionException { configureWorkspace(sourceDirectories, outputPath); this.resourceSetProvider.get().eAdapters().clear(); xtend2BatchCompiler.setResourceSetProvider(this.resourceSetProvider); MavenProjectAdapter.install(this.resourceSetProvider.get(), this.project); Iterable<String> filtered = Iterables.filter(sourceDirectories, FILE_EXISTS); if (Iterables.isEmpty(filtered)) { getLog().info("skip compiling sources because the configured directory '" //$NON-NLS-1$ + Iterables.toString(sourceDirectories) + "' does not exists."); //$NON-NLS-1$ return;/*ww w . j ava 2 s . c om*/ } getLog().debug("Set temp directory: " + getTempDirectory()); //$NON-NLS-1$ xtend2BatchCompiler.setTempDirectory(getTempDirectory()); getLog().debug("Set DeleteTempDirectory: " + false); //$NON-NLS-1$ xtend2BatchCompiler.setDeleteTempDirectory(false); getLog().debug("Set classpath: " + classPath); //$NON-NLS-1$ xtend2BatchCompiler.setClassPath(classPath); getLog().debug("Set source path: " + Strings.concat(File.pathSeparator, Lists.newArrayList(filtered))); //$NON-NLS-1$ xtend2BatchCompiler.setSourcePath(Strings.concat(File.pathSeparator, Lists.newArrayList(filtered))); getLog().debug("Set output path: " + outputPath); //$NON-NLS-1$ xtend2BatchCompiler.setOutputPath(outputPath); getLog().debug("Set encoding: " + this.encoding); //$NON-NLS-1$ xtend2BatchCompiler.setFileEncoding(this.encoding); getLog().debug("Set writeTraceFiles: " + this.writeTraceFiles); //$NON-NLS-1$ xtend2BatchCompiler.setWriteTraceFiles(this.writeTraceFiles); if (!xtend2BatchCompiler.compile()) { throw new MojoExecutionException("Error compiling xtend sources in '" //$NON-NLS-1$ + Strings.concat(File.pathSeparator, Lists.newArrayList(filtered)) + "'."); //$NON-NLS-1$ } }
From source file:org.zanata.webtrans.client.presenter.KeyShortcutPresenter.java
/** * Register a {@link KeyShortcut} to respond to a specific key combination * for a context.//from w ww .j av a 2 s . co m * * @param shortcut * to register * * @return a {@link HandlerRegistration} that can be used to un-register the * shortcut */ public HandlerRegistration register(KeyShortcut shortcut) { Log.debug("Registering key shortcut. Key codes follow:" + Iterables.toString(shortcut.getAllKeys())); shortcutManager.add(shortcut); attentionKeyManager.add(shortcut); return new KeyShortcutHandlerRegistration(shortcut); }
From source file:org.openqa.selenium.android.app.WebDriverActivity.java
public Object onReceiveBroadcast(String action, Object... args) { if (Action.GET_URL.equals(action)) { return currentView.getUrl(); } else if (Action.GET_TITLE.equals(action)) { return currentView.getTitle(); } else if (Action.TAKE_SCREENSHOT.equals(action)) { return takeScreenshot(); } else if (Action.NAVIGATE.equals(action)) { currentView.navigateTo((String) args[0]); } else if (Action.NAVIGATE_BACK.equals(action)) { currentView.goBackOrForward(-1); } else if (Action.NAVIGATE_FORWARD.equals(action)) { currentView.goBackOrForward(1);// w w w . ja v a 2 s. com } else if (Action.REFRESH.equals(action)) { currentView.reload(); } else if (Action.EXECUTE_JAVASCRIPT.equals(action)) { if (args.length == 1) { currentView.executeJavascript((String) args[0]); } else { throw new IllegalArgumentException("Error while trying to execute Javascript." + "SingleSessionActivity.executeJS takes one argument, but received: " + (args == null ? 0 : args.length)); } } else if (Action.ADD_COOKIE.equals(action)) { Cookie cookie = new Cookie((String) args[0], (String) args[1], (String) args[2]); sessionCookieManager.addCookie(currentView.getUrl(), cookie); } else if (Action.GET_ALL_COOKIES.equals(action)) { return sessionCookieManager.getAllCookiesAsString(currentView.getUrl()); } else if (Action.GET_COOKIE.equals(action)) { return sessionCookieManager.getCookie(currentView.getUrl(), (String) args[0]); } else if (Action.REMOVE_ALL_COOKIES.equals(action)) { sessionCookieManager.removeAllCookies(currentView.getUrl()); } else if (Action.REMOVE_COOKIE.equals(action)) { sessionCookieManager.remove(currentView.getUrl(), (String) args[0]); } else if (Action.SEND_MOTION_EVENT.equals(action)) { TouchScreen.sendMotion(currentView, (MotionEvent) args[0], (MotionEvent) args[1]); return true; } else if (Action.SEND_KEYS.equals(action)) { CharSequence[] inputKeys = new CharSequence[args.length]; for (int i = 0; i < inputKeys.length; i++) { inputKeys[i] = args[i].toString(); } WebViewAction.sendKeys(currentView, inputKeys); } else if (Action.ROTATE_SCREEN.equals(action)) { this.setRequestedOrientation(getAndroidScreenOrientation((ScreenOrientation) args[0])); } else if (Action.GET_SCREEN_ORIENTATION.equals(action)) { return getScreenOrientation(); } else if (Action.SWITCH_TO_WINDOW.equals(action)) { return switchToWebView(viewManager.getView((String) args[0])); } else if (Action.GET_CURRENT_WINDOW_HANDLE.equals(action)) { return currentView.getWindowHandle(); } else if (Action.GET_ALL_WINDOW_HANDLES.equals(action)) { return Iterables.toString(viewManager.getAllHandles()); } return null; }
From source file:org.apache.brooklyn.policy.action.AbstractScheduledEffectorPolicy.java
@Override public synchronized void run() { if (effector == null) return;/*from w w w. j a v a2 s . co m*/ if (!(isRunning() && getManagementContext().isRunning())) return; try { ConfigBag bag = ResolvingConfigBag.newInstanceExtending(getManagementContext(), config().getBag()); Map<String, Object> args = EntityInitializers.resolve(bag, EFFECTOR_ARGUMENTS); LOG.debug("{}: Resolving arguments for {}: {}", new Object[] { this, effector.getName(), Iterables.toString(args.keySet()) }); Map<String, Object> resolved = (Map) Tasks.resolving(args, Object.class).deep(true, true) .context(entity).get(); LOG.debug("{}: Invoking effector on {}, {}({})", new Object[] { this, entity, effector.getName(), resolved }); Object result = entity.invoke(effector, resolved).getUnchecked(); LOG.debug("{}: Effector {} returned {}", new Object[] { this, effector.getName(), result }); } catch (RuntimeInterruptedException rie) { // Gracefully stop Thread.currentThread().interrupt(); } catch (Throwable t) { LOG.warn("{}: Exception running {}: {}", new Object[] { this, effector.getName(), t.getMessage() }); Exceptions.propagate(t); } }