List of usage examples for com.google.common.collect Iterables getLast
public static <T> T getLast(Iterable<T> iterable)
From source file:com.google.jimfs.JimfsPath.java
/** * Returns the file name of this path. Unlike {@link #getFileName()}, this may return the name of * the root if this is a root path.// w ww .j av a2 s . c o m */ @Nullable public Name name() { if (!names.isEmpty()) { return Iterables.getLast(names); } return root; }
From source file:com.haulmont.cuba.web.exception.NoUserSessionHandler.java
@Override protected void doHandle(App app, String className, String message, @Nullable Throwable throwable) { try {//ww w.j a va 2s . c om // we may show two or more dialogs if user pressed F5 and we have no valid user session // just remove previous dialog and show new if (noUserSessionDialog != null) { app.getAppUI().removeWindow(noUserSessionDialog); } Messages messages = AppBeans.get(Messages.NAME); WebWindowManager wm = app.getWindowManager(); wm.showOptionDialog(messages.getMainMessage("dialogs.Information", locale), messages.getMainMessage("noUserSession.message", locale), Frame.MessageType.CONFIRMATION, new Action[] { new LoginAction() }); Collection<Window> windows = app.getAppUI().getWindows(); if (!windows.isEmpty()) { noUserSessionDialog = Iterables.getLast(windows); } } catch (Throwable th) { log.error("Unable to handle NoUserSessionException", throwable); log.error("Exception in NoUserSessionHandler", th); } }
From source file:org.eclipse.tracecompass.statesystem.core.tests.stubs.backend.HistoryTreeStub.java
/** * Get the latest leaf of the tree/*from w ww . ja va2 s. c om*/ * * @return The current leaf node of the tree */ public HTNode getLatestLeaf() { List<HTNode> latest = getLatestBranch(); return Iterables.getLast(latest); }
From source file:com.willwinder.universalgcodesender.gcode.processors.LineSplitter.java
@Override public List<String> processCommand(String commandString, GcodeState state) throws GcodeParserException { List<GcodeParser.GcodeMeta> commands = GcodeParser.processCommand(commandString, 0, state); List<String> results = new ArrayList<>(); Code code = hasLine(commands);/*from www. j a v a 2 s .co m*/ if (code == null) { return Collections.singletonList(commandString); } SplitCommand sc = GcodePreprocessorUtils.extractMotion(code, commandString); if (sc.remainder.length() > 0) { results.add(sc.remainder); } GcodeMeta command = Iterables.getLast(commands); if (command == null || command.point == null) { throw new GcodeParserException("Internal parser error: missing data."); } // line length Position start = state.currentPoint; Position end = command.point.point(); Position current = start; double length = start.distance(end); // Check if line needs splitting. if (length > this.maxSegmentLength) { int numSegments = (int) Math.ceil(length / this.maxSegmentLength); double segmentLength = length / Math.ceil(length / this.maxSegmentLength); // Create line segments, stop before the last one which uses the end point. for (int i = 1; i < numSegments; i++) { double k = 1 / (length / (i * segmentLength)); double newX = start.x + k * (end.x - start.x); double newY = start.y + k * (end.y - start.y); double newZ = start.z + k * (end.z - start.z); Position next = new Position(newX, newY, newZ, start.getUnits()); results.add(GcodePreprocessorUtils.generateLineFromPoints(command.code, current, next, command.state.inAbsoluteMode, null)); current = next; } // Add the last line point. results.add(GcodePreprocessorUtils.generateLineFromPoints(command.code, current, end, command.state.inAbsoluteMode, null)); } else { return Collections.singletonList(commandString); } return results; }
From source file:dropship.agent.statsd.SnitchService.java
SnitchService(Properties properties, String groupArtifactId, Class mainClass) { checkNotNull(properties, "properties"); this.gavKeys = ImmutableList.copyOf( Iterables.limit(Splitter.on(':').split(CharMatcher.is('.').replaceFrom(groupArtifactId, '-')), 2)); this.hostKeys = ImmutableList.of(getHostname()); String simplifiedMainClassName = Iterables.getLast(Splitter.on('.').split(mainClass.getName())); this.methodKeys = ImmutableList.of(simplifiedMainClassName); }
From source file:com.github.fge.jsonpatch.ReplaceOperation.java
@Override public JsonNode apply(final JsonNode node) throws JsonPatchException { /*// ww w .j av a2 s. c o m * FIXME cannot quite be replaced by a remove + add because of arrays. * For instance: * * { "op": "replace", "path": "/0", "value": 1 } * * with * * [ "x" ] * * If remove is done first, the array is empty and add rightly complains * that there is no such index in the array. */ if (path.path(node).isMissingNode()) throw new JsonPatchException(BUNDLE.getMessage("jsonPatch.noSuchPath")); final JsonNode replacement = value.deepCopy(); if (path.isEmpty()) return replacement; final JsonNode ret = node.deepCopy(); final JsonNode parent = path.parent().get(ret); final String rawToken = Iterables.getLast(path).getToken().getRaw(); if (parent.isObject()) ((ObjectNode) parent).replace(rawToken, replacement); else ((ArrayNode) parent).set(Integer.parseInt(rawToken), replacement); return ret; }
From source file:org.apache.aurora.scheduler.storage.StorageBackfill.java
private static void guaranteeShardUniqueness(ScheduledTask task, TaskStore.Mutable taskStore, Clock clock) { if (Tasks.isActive(task.getStatus())) { // Perform a sanity check on the number of active shards. Query.Builder query = Query.instanceScoped(IJobKey.build(task.getAssignedTask().getTask().getJob()), task.getAssignedTask().getInstanceId()).active(); Set<String> activeTasksInShard = FluentIterable.from(taskStore.fetchTasks(query)) .transform(Tasks.SCHEDULED_TO_ID).toSet(); if (activeTasksInShard.size() > 1) { SHARD_SANITY_CHECK_FAILS.incrementAndGet(); LOG.severe("Active shard sanity check failed when loading " + Tasks.id(task) + ", active tasks found: " + activeTasksInShard); // We want to keep exactly one task from this shard, so sort the IDs and keep the // highest (newest) in the hopes that it is legitimately running. String newestTask = Iterables.getLast(Sets.newTreeSet(activeTasksInShard)); if (Tasks.id(task).equals(newestTask)) { LOG.info("Retaining task " + Tasks.id(task)); } else { task.setStatus(ScheduleStatus.KILLED); task.addToTaskEvents(new TaskEvent(clock.nowMillis(), ScheduleStatus.KILLED) .setMessage("Killed duplicate shard.")); // TODO(wfarner); Circle back if this is necessary. Currently there's a race // condition between the time the scheduler is actually available without hitting // IllegalStateException (see DriverImpl). // driver.killTask(Tasks.id(task)); }/* www . j a v a2 s . com*/ } } }
From source file:net.holmes.core.business.streaming.airplay.controlpoint.CommandResponse.java
/** * Decode Http response.//from w w w. j a v a2 s .com * * @param responseLines response lines */ public void decodeHttpResponse(final List<String> responseLines) { // Decode http response on first line Matcher matcher = HTTP_RESPONSE_PATTERN.matcher(responseLines.get(0)); if (matcher.find()) { code = Integer.valueOf(matcher.group(2)); message = matcher.group(3); } // Decode http headers on next lines for (int i = 1; i < responseLines.size(); i++) { Iterable<String> it = Splitter.on(PARAMETER_SEPARATOR).trimResults().split(responseLines.get(i)); httpHeaders.put(Iterables.get(it, 0), Iterables.getLast(it)); } }
From source file:org.sonar.cxx.checks.SwitchLastCaseIsDefaultCheck.java
@Override public void visitNode(AstNode node) { List<AstNode> switchCases = getSwitchCases(node); int defaultCaseIndex = Iterables.indexOf(switchCases, DEFAULT_CASE_NODE_FILTER); if (defaultCaseIndex == -1) { getContext().createLineViolation(this, MISSING_DEFAULT_CASE_MESSAGE, node); } else {//from w w w. j a v a 2 s. c o m AstNode defaultCase = Iterables.get(switchCases, defaultCaseIndex); if (!defaultCase.equals(Iterables.getLast(switchCases))) { getContext().createLineViolation(this, DEFAULT_CASE_IS_NOT_LAST_MESSAGE, defaultCase); } } }
From source file:org.sosy_lab.cpachecker.cpa.statistics.StatisticsCPAStatistics.java
@SuppressWarnings("unchecked") @Override// www . ja va 2 s . c o m public void printStatistics(PrintStream out, Result result, ReachedSet reached) { StatisticsData statistics; if (cpa.isAnalysis()) { statistics = cpa.getFactory().getGlobalAnalysis(); } else { StatisticsState lastState = (StatisticsState) reached.getLastState(); if (lastState == null) { lastState = (StatisticsState) Iterables.getLast(reached); } statistics = lastState.getStatistics(); } Map<String, Object> jsonMap = new HashMap<>(); for (Entry<StatisticsProvider, StatisticsDataProvider> entry : statistics) { StatisticsProvider provider = entry.getKey(); StatisticsDataProvider data = entry.getValue(); String propName = provider.getPropertyName(); Object value = data.getPropertyValue(); String mergeInfo = ""; if (!cpa.isAnalysis()) { String mergeType = provider.getMergeType(); mergeInfo = "_" + mergeType; // Save in json with merge type Map<String, Object> innerJsonMap; if (jsonMap.containsKey(propName)) { innerJsonMap = (Map<String, Object>) jsonMap.get(propName); } else { innerJsonMap = new HashMap<>(); jsonMap.put(propName, innerJsonMap); } innerJsonMap.put(mergeType, value); } else { // Save in json without merge type jsonMap.put(propName, value); } out.println("\t" + propName + mergeInfo + ": " + value); } if (statisticsCPAFile != null) { try { JSON.writeJSONString(jsonMap, statisticsCPAFile); } catch (IOException e) { logger.logUserException(Level.WARNING, e, "Could not write statistics to file"); } } }