List of usage examples for com.google.common.collect Iterables getLast
public static <T> T getLast(Iterable<T> iterable)
From source file:org.sosy_lab.cpachecker.cpa.bam.BAMTransferRelationWithFixPointForRecursion.java
private Collection<AbstractState> analyseBlockAndExpandForRecursion(final AbstractState initialState, final Precision pPrecision, final CFANode node, final Block outerSubtree, final AbstractState reducedInitialState, final Precision reducedInitialPrecision) throws CPAException, InterruptedException, CPATransferException { assert !((ARGState) initialState).getParents().isEmpty(); // get the rootState, that is the abstract state of the functioncall. Collection<ARGState> possibleRootStates = ((ARGState) initialState).getParents(); assert possibleRootStates.size() == 1 : "too many functioncalls: " + possibleRootStates; AbstractState rootState = possibleRootStates.iterator().next(); final Collection<AbstractState> expandedFunctionReturnStates; final Triple<AbstractState, Precision, Block> coveringLevel = getCoveringLevel(stack, Iterables.getLast(stack)); if (coveringLevel != null) { // if level is twice in stack, we have endless recursion. // with current knowledge we would never abort unrolling the recursion. // lets skip the function and return only a short "summary" of the function. // this summary is the result of a previous analysis of this block from the cache. logger.logf(Level.FINEST, "recursion will cause endless unrolling (with current precision), " + "aborting call of function '%s' at state %s", node.getFunctionName(), reducedInitialState); expandedFunctionReturnStates = analyseRecursiveBlockAndExpand(initialState, pPrecision, outerSubtree, reducedInitialState, coveringLevel); } else {/* w w w . jav a 2 s.c o m*/ // enter block of function-call and start recursive analysis expandedFunctionReturnStates = super.analyseBlockAndExpand(initialState, pPrecision, outerSubtree, reducedInitialState, reducedInitialPrecision); } final Collection<AbstractState> rebuildStates = new ArrayList<>(expandedFunctionReturnStates.size()); for (final AbstractState expandedState : expandedFunctionReturnStates) { rebuildStates.add(getRebuildState(rootState, initialState, expandedState)); } return rebuildStates; }
From source file:org.apache.stratos.cloud.controller.iaases.openstack.networking.NeutronNetworkingApi.java
/** * Assign a {@link FloatingIP} from the given {@link FloatingNetwork} to the given {@link Port}. * It will either assign an existing floating IP * or it will create and assign a new floating IP. * * @param port the {@link Port} to which a floating IP to be assigned. * @param floatingNetworkUuid the network uuid of the floating network * from which a floating IP to be chosen/created * @return the assigned Floating IP/* ww w . j a va 2s.co m*/ */ private FloatingIP assignFloatingIP(Port port, String floatingNetworkUuid) { // checking whether if there are any available floating IPs in the external network // if there are any we don't need to create a new one ArrayList<FloatingIP> unassignedFloatingIPs = getUnassignedFloatingIPsByNetworkUuid(floatingNetworkUuid); // we should remove all predefined floating IPs from unassigned list // otherwise, these predefined floating IPs can be associated to some other interfaces if (unassignedFloatingIPs != null) { if (log.isDebugEnabled()) { String msg = String.format("Unassigned floating IPs from the network %s - %s", floatingNetworkUuid, unassignedFloatingIPs.toString()); log.debug(msg); } Iterator<FloatingIP> unassginedFloatingIPsIterator = unassignedFloatingIPs.iterator(); while (unassginedFloatingIPsIterator.hasNext()) { FloatingIP floatingIP = unassginedFloatingIPsIterator.next(); List<String> allPredefinedFloatingIPs = getAllPredefinedFloatingIPs( iaasProvider.getNetworkInterfaces()); if (allPredefinedFloatingIPs != null && !allPredefinedFloatingIPs.isEmpty()) { if (log.isDebugEnabled()) { String msg = String.format("Predefined floating IPs - %s found in cartridge", allPredefinedFloatingIPs.toString()); log.debug(msg); } Iterator<String> predefinedFloatingIPsIterator = allPredefinedFloatingIPs.iterator(); while (predefinedFloatingIPsIterator.hasNext()) { String floatingIPAddress = predefinedFloatingIPsIterator.next(); if (floatingIP.getFloatingIpAddress() != null && floatingIP.getFloatingIpAddress().equals(floatingIPAddress)) { unassginedFloatingIPsIterator.remove(); if (log.isDebugEnabled()) { String msg = String.format( "Removed predefined floating IP %s from available floating IPs", floatingIPAddress); log.debug(msg); } } } } } } if (unassignedFloatingIPs == null || unassignedFloatingIPs.isEmpty()) { return createAndAssignFloatingIP(port, floatingNetworkUuid); } if (log.isDebugEnabled()) { String msg = String.format("Available floating IPs from the network %s - %s", floatingNetworkUuid, unassignedFloatingIPs.toString()); log.debug(msg); } // shuffle and get the last for randomness Collections.shuffle(unassignedFloatingIPs); FloatingIP selectedFloatingIP = Iterables.getLast(unassignedFloatingIPs); if (log.isDebugEnabled()) { String msg = String.format("Floating IP %s is selected among %s from the network %s", selectedFloatingIP.getFloatingIpAddress(), unassignedFloatingIPs.toString(), floatingNetworkUuid); log.debug(msg); } return updateFloatingIP(selectedFloatingIP, port); }
From source file:org.eclipse.tracecompass.internal.statesystem.core.backend.historytree.HTNode.java
/** * We've received word from the containerTree that newest nodes now exist to * our right. (Puts isDone = true and sets the endtime) * * @param endtime/*from w w w .j a va 2 s .c om*/ * The nodeEnd time that the node will have */ public void closeThisNode(long endtime) { fRwl.writeLock().lock(); try { /** * FIXME: was assert (endtime >= fNodeStart); but that exception * is reached with an empty node that has start time endtime + 1 */ // if (endtime < fNodeStart) { // throw new IllegalArgumentException("Endtime " + endtime + " cannot be lower than start time " + fNodeStart); // } if (!fIntervals.isEmpty()) { /* * Make sure there are no intervals in this node with their * EndTime > the one requested. Only need to check the last one * since they are sorted */ if (endtime < Iterables.getLast(fIntervals).getEndTime()) { throw new IllegalArgumentException( "Closing end time should be greater than or equal to the end time of the intervals of this node"); //$NON-NLS-1$ } } fNodeEnd = endtime; } finally { fRwl.writeLock().unlock(); } }
From source file:org.jclouds.gogrid.GoGridLiveTestDisabled.java
@Test(enabled = true) public void testShellAccess() throws IOException { final String nameOfServer = "Server" + String.valueOf(new Date().getTime()).substring(6); serversToDeleteAfterTheTests.add(nameOfServer); Set<Ip> availableIps = api.getIpServices().getUnassignedIpList(); Ip availableIp = Iterables.getLast(availableIps); Server createdServer = api.getServerServices().addServer(nameOfServer, "GSI-f8979644-e646-4711-ad58-d98a5fa3612c", "1", availableIp.getIp()); assertNotNull(createdServer);//from w w w. ja va 2 s .co m assert serverLatestJobCompleted.apply(createdServer); // get server by name Set<Server> response = api.getServerServices().getServersByName(nameOfServer); assert (response.size() == 1); createdServer = Iterables.getOnlyElement(response); Map<String, Credentials> credsMap = api.getServerServices().getServerCredentialsList(); LoginCredentials instanceCredentials = LoginCredentials .fromCredentials(credsMap.get(createdServer.getName())); assertNotNull(instanceCredentials); HostAndPort socket = HostAndPort.fromParts(createdServer.getIp().getIp(), 22); SocketOpen socketOpen = Guice.createInjector().getInstance(SocketOpen.class); Predicate<HostAndPort> socketTester = retry(socketOpen, 180, 5, SECONDS); socketTester.apply(socket); // check that the get credentials call is the same as this assertEquals(api.getServerServices().getServerCredentials(createdServer.getId()), instanceCredentials); try { assertEquals(api.getServerServices().getServerCredentials(Long.MAX_VALUE), null); } catch (AssertionError e) { e.printStackTrace(); } // delete the server api.getServerServices().deleteByName(nameOfServer); }
From source file:org.diqube.server.queryremote.ClusterQueryServiceHandler.java
/** * Starts executing a {@link RExecutionPlan} on all {@link TableShard}s on this node, which act as "query remote" * node./*from w ww . j a v a 2 s. co m*/ * * Please note that the results of this call will be available through a {@link QueryResultHandler} which can be * registered at {@link QueryRegistry}. */ @Override public void executeOnAllLocalShards(RExecutionPlan executionPlan, RUUID remoteQueryUuid, RNodeAddress resultAddress) throws TException { Object connSync = new Object(); Connection<ClusterQueryService.Client> resultConnection; ClusterQueryService.Iface resultService; UUID queryUuid = RUuidUtil.toUuid(remoteQueryUuid); // The executionUuid we will use for the all executors executing something started by this API call. UUID executionUuid = queryUuidProvider.createNewExecutionUuid(queryUuid, "remote-" + queryUuid); if (resultAddress.equals(clusterManager.getOurHostAddr().createRemote())) { // implement short cut if we should answer to the local node, i.e. the query master is running on this node, too. // This is a nice implementation for unit tests, too. resultConnection = null; resultService = this; } else { SocketListener resultSocketListener = new SocketListener() { @Override public void connectionDied() { // Connection to result node died. The node will automatically be removed from ClusterManager and the // connection will automatically be handled. logger.error( "Result node of query {} execution {} ({}) died unexpectedly. It will not receive any " + "results of the execution any more, cancelling execution.", queryUuid, executionUuid, resultAddress); executionUuidsAndResultConnections.remove(queryUuid); queryRegistry.unregisterQueryExecution(queryUuid, executionUuid); executorManager.shutdownEverythingOfQueryExecution(queryUuid, executionUuid); // this will kill our thread! } }; try { resultConnection = connectionPool.reserveConnection(ClusterQueryService.Client.class, ClusterQueryServiceConstants.SERVICE_NAME, resultAddress, resultSocketListener); } catch (ConnectionException | InterruptedException e) { logger.error( "Could not open connection to the result node for query {} execution {} ({}). Will not start " + "executing anything.", queryUuid, executionUuid, resultAddress); return; } resultService = resultConnection.getService(); } executionUuidsAndResultConnections.put(queryUuid, new Pair<>(executionUuid, resultConnection)); RemoteExecutionPlanExecutor executor = new RemoteExecutionPlanExecutor(tableRegistry, executablePlanBuilderFactory, executorManager, queryRegistry, numberOfTableShardsToExecuteConcurrently); // Exception handler that handles exceptions that are thrown during execution (one handler for all TableShards!) // This can also close all resources, if parameters "null,null" are passed. QueryExceptionHandler exceptionHandler = new QueryExceptionHandler() { @Override public void handleException(Throwable t) { if (t != null) { logger.error("Exception while executing query {} execution {}", queryUuid, executionUuid, t); RExecutionException ex = new RExecutionException(); ex.setMessage(t.getMessage()); try { resultService.executionException(remoteQueryUuid, ex); } catch (TException e) { // swallow, the resultSocketListener handles this. } } // shutdown everything for all TableShards. if (resultConnection != null) { synchronized (connSync) { connectionPool.releaseConnection(resultConnection); } } executionUuidsAndResultConnections.remove(queryUuid); queryRegistry.unregisterQueryExecution(queryUuid, executionUuid); executorManager.shutdownEverythingOfQueryExecution(queryUuid, executionUuid); // this will kill our thread! } }; Holder<List<ExecutablePlan>> executablePlansHolder = new Holder<>(); Pair<Runnable, List<ExecutablePlan>> prepareRes = executor.prepareExecution(queryUuid, executionUuid, executionPlan, new RemoteExecutionPlanExecutionCallback() { @Override public void newGroupIntermediaryAggregration(long groupId, String colName, ROldNewIntermediateAggregationResult result, short percentDone) { synchronized (connSync) { try { resultService.groupIntermediateAggregationResultAvailable(remoteQueryUuid, groupId, colName, result, percentDone); } catch (TException e) { logger.error("Could not send new group intermediaries to client for query {}", queryUuid, e); exceptionHandler.handleException(null); } } } @Override public void newColumnValues(String colName, Map<Long, RValue> values, short percentDone) { synchronized (connSync) { try { logger.trace("Constructed final column values, sending them now."); resultService.columnValueAvailable(remoteQueryUuid, colName, values, percentDone); } catch (TException e) { logger.error("Could not send new group intermediaries to client for query {}", queryUuid, e); exceptionHandler.handleException(null); } } } @Override public void executionDone() { // gather final stats queryRegistry.getOrCreateCurrentStatsManager().setCompletedNanos(System.nanoTime()); for (ExecutablePlan plan : executablePlansHolder.getValue()) new ExecutablePlanQueryStatsUtil() .publishQueryStats(queryRegistry.getCurrentStatsManager(), plan); // send stats RClusterQueryStatistics remoteStats = RClusterQueryStatsUtil .createRQueryStats(queryRegistry.getCurrentStatsManager().createQueryStats()); logger.trace("Sending query statistics of {} to query master: {}", queryUuid, remoteStats); synchronized (connSync) { try { resultService.queryStatistics(remoteQueryUuid, remoteStats); } catch (TException e) { logger.error("Could not send statistics to client for query {}", queryUuid, e); } } // update table cache with the results of this query execution. Note that if this query execution loaded // specific columns from the cache, they will be available in the ExecutionEnv as "temporary columns" - and // we will present them to the cache again right away. With this mechanism the cache can actively count the // usages of specific columns and therefore tune what it should cache and what not. WritableColumnShardCache tableCache = tableCacheRegistry .getColumnShardCache(executionPlan.getTable()); if (tableCache != null) { logger.info("Updating the table cache with results of query {}, execution {}", queryUuid, executionUuid); for (ExecutablePlan plan : executablePlansHolder.getValue()) { ExecutionEnvironment env = plan.getDefaultExecutionEnvironment(); Map<String, List<QueryableColumnShard>> tempColShards = env .getAllTemporaryColumnShards(); for (String colName : tempColShards.keySet()) { ColumnShard tempCol = Iterables.getLast(tempColShards.get(colName)) .getDelegate(); tableCache.registerUsageOfColumnShardPossiblyCache(env.getFirstRowIdInShard(), tempCol); } } } synchronized (connSync) { try { resultService.executionDone(remoteQueryUuid); } catch (TException e) { logger.error("Could not send 'done' to client for query {}", queryUuid, e); } } exceptionHandler.handleException(null); } }); if (prepareRes == null) { // we cannot execute anything, probably the TableShards were just unloaded. long now = System.nanoTime(); queryRegistry.getOrCreateCurrentStatsManager().setStartedNanos(now); queryRegistry.getOrCreateCurrentStatsManager().setCompletedNanos(now); synchronized (connSync) { logger.info( "As there's nothing to execute for query {} execution {}, sending empty stats and an executionDone", queryUuid, executionUuid); resultService.queryStatistics(remoteQueryUuid, RClusterQueryStatsUtil .createRQueryStats(queryRegistry.getCurrentStatsManager().createQueryStats())); resultService.executionDone(remoteQueryUuid); } exceptionHandler.handleException(null); return; } executablePlansHolder.setValue(prepareRes.getRight()); // prepare to launch the execution in a different Thread Executor threadPool = executorManager.newQueryFixedThreadPoolWithTimeout(1, "query-remote-master-" + queryUuid + "-%d", queryUuid, executionUuid); queryRegistry.registerQueryExecution(queryUuid, executionUuid, exceptionHandler, false); // start execution of ExecutablePlan(s) asynchronously. queryRegistry.getOrCreateStatsManager(queryUuid, executionUuid).setStartedNanos(System.nanoTime()); threadPool.execute(prepareRes.getLeft()); }
From source file:org.apache.kudu.client.MiniKuduCluster.java
/** * Starts a process using the provided command and configures it to be daemon, * redirects the stderr to stdout, and starts a thread that will read from the process' input * stream and redirect that to LOG.// ww w.j a v a 2 s . co m * @param port RPC port used to identify the process * @param command process and options * @return The started process * @throws Exception Exception if an error prevents us from starting the process, * or if we were able to start the process but noticed that it was then killed (in which case * we'll log the exit value). */ private Process configureAndStartProcess(int port, List<String> command) throws Exception { ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.redirectErrorStream(true); if (miniKdc != null) { processBuilder.environment().putAll(miniKdc.getEnvVars()); } Process proc = processBuilder.start(); ProcessInputStreamLogPrinterRunnable printer = new ProcessInputStreamLogPrinterRunnable( proc.getInputStream()); Thread thread = new Thread(printer); thread.setDaemon(true); thread.setName(Iterables.getLast(Splitter.on(File.separatorChar).split(command.get(0))) + ":" + port); PROCESS_INPUT_PRINTERS.add(thread); thread.start(); Thread.sleep(300); try { int ev = proc.exitValue(); throw new Exception(String.format("We tried starting a process (%s) but it exited with value=%s", command.get(0), ev)); } catch (IllegalThreadStateException ex) { // This means the process is still alive, it's like reverse psychology. } return proc; }
From source file:com.google.api.explorer.client.FullView.java
/** * Generate breadcrumbs into the specified container using the format link > link > text where the * last breadcrumb is always plain text. *///from w w w .j a v a 2s. com private void generateBreadcrumbs(Panel container, List<Title> titles) { container.clear(); // For all of the titles previous to the last, add a link and a separator. for (Title notLast : titles.subList(0, titles.size() - 1)) { container.add(new InlineHyperlink(notLast.getTitle(), notLast.getFragment())); container.add(new InlineLabel(" > ")); } // Append only the text for the last title. Title lastTitle = Iterables.getLast(titles); container.add(new InlineLabel(lastTitle.getTitle())); if (lastTitle.getSubtitle() != null) { Label subtitle = new InlineLabel(" - " + lastTitle.getSubtitle()); subtitle.addStyleName(style.methodSubtitle()); container.add(subtitle); } }
From source file:org.diqube.server.queryremote.query.ClusterQueryServiceHandler.java
/** * Starts executing a {@link RExecutionPlan} on all {@link TableShard}s on this node, which act as "query remote" * node./* w w w . ja v a2s . co m*/ * * Please note that the results of this call will be available through a {@link QueryResultHandler} which can be * registered at {@link QueryRegistry}. */ @Override public void executeOnAllLocalShards(RExecutionPlan executionPlan, RUUID remoteQueryUuid, RNodeAddress resultAddress) throws TException { UUID queryUuid = RUuidUtil.toUuid(remoteQueryUuid); // The executionUuid we will use for the all executors executing something started by this API call. UUID executionUuid = queryUuidProvider.createNewExecutionUuid(queryUuid, "remote-" + queryUuid); SocketListener resultSocketListener = new SocketListener() { @Override public void connectionDied(String cause) { // Connection to result node died. The node will automatically be removed from ClusterManager and the // connection will automatically be handled. logger.error( "Result node of query {} execution {} ({}) died unexpectedly. It will not receive any " + "results of the execution any more, cancelling execution.", queryUuid, executionUuid, resultAddress); executionUuidsAndResultConnections.remove(queryUuid); queryRegistry.unregisterQueryExecution(queryUuid, executionUuid); executorManager.shutdownEverythingOfQueryExecution(queryUuid, executionUuid); // this will kill our thread! } }; ServiceProvider<ClusterQueryService.Iface> resultServiceProv; try { resultServiceProv = connectionOrLocalHelper.getService(ClusterQueryService.Iface.class, resultAddress, resultSocketListener); } catch (ConnectionException | InterruptedException e1) { logger.error( "Could not open connection to the result node for query {} execution {} ({}). Will not start " + "executing anything.", queryUuid, executionUuid, resultAddress); return; } executionUuidsAndResultConnections.put(queryUuid, new Pair<>(executionUuid, resultServiceProv)); RemoteExecutionPlanExecutor executor = new RemoteExecutionPlanExecutor(tableRegistry, executablePlanBuilderFactory, executorManager, queryRegistry, numberOfTableShardsToExecuteConcurrently); // Exception handler that handles exceptions that are thrown during execution (one handler for all TableShards!) // This can also close all resources, if parameters "null,null" are passed. QueryExceptionHandler exceptionHandler = new QueryExceptionHandler() { @Override public void handleException(Throwable t) { if (t != null) { logger.error("Exception while executing query {} execution {}", queryUuid, executionUuid, t); RExecutionException ex = new RExecutionException(); ex.setMessage(t.getMessage()); try { synchronized (resultServiceProv) { resultServiceProv.getService().executionException(remoteQueryUuid, ex); } } catch (TException e) { // swallow, the resultSocketListener handles this. } } // shutdown everything for all TableShards. synchronized (resultServiceProv) { try { resultServiceProv.close(); } catch (IOException e) { logger.warn("Could not close connection"); } } executionUuidsAndResultConnections.remove(queryUuid); queryRegistry.unregisterQueryExecution(queryUuid, executionUuid); executorManager.shutdownEverythingOfQueryExecution(queryUuid, executionUuid); // this will kill our thread! } }; Holder<List<ExecutablePlan>> executablePlansHolder = new Holder<>(); Pair<Runnable, List<ExecutablePlan>> prepareRes = null; try { prepareRes = executor.prepareExecution(queryUuid, executionUuid, executionPlan, new RemoteExecutionPlanExecutionCallback() { @Override public void newGroupIntermediaryAggregration(long groupId, String colName, ROldNewIntermediateAggregationResult result, short percentDone) { synchronized (resultServiceProv) { try { resultServiceProv.getService().groupIntermediateAggregationResultAvailable( remoteQueryUuid, groupId, colName, result, percentDone); } catch (TException e) { logger.error("Could not send new group intermediaries to client for query {}", queryUuid, e); exceptionHandler.handleException(null); } } } @Override public void newColumnValues(String colName, Map<Long, RValue> values, short percentDone) { synchronized (resultServiceProv) { try { logger.trace("Constructed final column values, sending them now."); resultServiceProv.getService().columnValueAvailable(remoteQueryUuid, colName, values, percentDone); } catch (TException e) { logger.error("Could not send new group intermediaries to client for query {}", queryUuid, e); exceptionHandler.handleException(null); } } } @Override public void executionDone() { // gather final stats queryRegistry.getOrCreateCurrentStatsManager().setCompletedNanos(System.nanoTime()); for (ExecutablePlan plan : executablePlansHolder.getValue()) new ExecutablePlanQueryStatsUtil() .publishQueryStats(queryRegistry.getCurrentStatsManager(), plan); // send stats RClusterQueryStatistics remoteStats = RClusterQueryStatsUtil .createRQueryStats(queryRegistry.getCurrentStatsManager().createQueryStats()); logger.trace("Sending query statistics of {} to query master: {}", queryUuid, remoteStats); synchronized (resultServiceProv) { try { resultServiceProv.getService().queryStatistics(remoteQueryUuid, remoteStats); } catch (TException e) { logger.error("Could not send statistics to client for query {}", queryUuid, e); } } // update table cache with the results of this query execution. Note that if this query execution loaded // specific columns from the cache, they will be available in the ExecutionEnv as "temporary columns" - // and we will present them to the cache again right away. With this mechanism the cache can actively // count the usages of specific columns and therefore tune what it should cache and what not. String finalTableName; if (executionPlan.getFromSpec().isSetPlainTableName()) finalTableName = executionPlan.getFromSpec().getPlainTableName(); else { String origTableName = executionPlan.getFromSpec().getFlattened().getTableName(); String flattenBy = executionPlan.getFromSpec().getFlattened().getFlattenBy(); UUID flattenId = RUuidUtil .toUuid(executionPlan.getFromSpec().getFlattened().getFlattenId()); finalTableName = new FlattenedTableNameUtil() .createFlattenedTableName(origTableName, flattenBy, flattenId); } WritableColumnShardCache tableCache = tableCacheRegistry .getColumnShardCache(finalTableName); if (tableCache != null) { logger.info("Updating the table cache with results of query {}, execution {}", queryUuid, executionUuid); for (ExecutablePlan plan : executablePlansHolder.getValue()) { ExecutionEnvironment env = plan.getDefaultExecutionEnvironment(); Map<String, List<QueryableColumnShard>> tempColShards = env .getAllTemporaryColumnShards(); for (String colName : tempColShards.keySet()) { ColumnShard tempCol = Iterables.getLast(tempColShards.get(colName)) .getDelegate(); tableCache.offer(env.getFirstRowIdInShard(), tempCol.getName(), tempCol); } } } synchronized (resultServiceProv) { try { resultServiceProv.getService().executionDone(remoteQueryUuid); } catch (TException e) { logger.error("Could not send 'done' to client for query {}", queryUuid, e); } } exceptionHandler.handleException(null); } }); } catch (ExecutablePlanBuildException e) { // swallow, prepareRes == null, see just below. } if (prepareRes == null) { // we cannot execute anything, probably the TableShards were just unloaded. long now = System.nanoTime(); QueryUuid.setCurrentQueryUuidAndExecutionUuid(queryUuid, executionUuid); try { queryRegistry.getOrCreateCurrentStatsManager().setStartedNanos(now); queryRegistry.getOrCreateCurrentStatsManager().setCompletedNanos(now); synchronized (resultServiceProv) { logger.info( "As there's nothing to execute for query {} execution {}, sending empty stats and an executionDone", queryUuid, executionUuid); resultServiceProv.getService().queryStatistics(remoteQueryUuid, RClusterQueryStatsUtil .createRQueryStats(queryRegistry.getCurrentStatsManager().createQueryStats())); resultServiceProv.getService().executionDone(remoteQueryUuid); } } finally { QueryUuid.clearCurrent(); } exceptionHandler.handleException(null); return; } executablePlansHolder.setValue(prepareRes.getRight()); // prepare to launch the execution in a different Thread Executor threadPool = executorManager.newQueryFixedThreadPoolWithTimeout(1, "query-remote-master-" + queryUuid + "-%d", queryUuid, executionUuid); queryRegistry.registerQueryExecution(queryUuid, executionUuid, exceptionHandler, false); // start execution of ExecutablePlan(s) asynchronously. queryRegistry.getOrCreateStatsManager(queryUuid, executionUuid).setStartedNanos(System.nanoTime()); threadPool.execute(prepareRes.getLeft()); }
From source file:com.android.tools.idea.ui.resourcechooser.StateListPicker.java
@NotNull public static SwatchComponent.SwatchIcon getSwatchIcon(@Nullable String resourceName, @NotNull ResourceResolver resourceResolver, @NotNull RenderTask renderTask) { ResourceValue resValue = resourceResolver.findResValue(resourceName, false); resValue = resourceResolver.resolveResValue(resValue); if (resValue == null || resValue.getResourceType() == ResourceType.COLOR) { final List<Color> colors = ResourceHelper.resolveMultipleColors(resourceResolver, resValue, renderTask.getModule().getProject()); SwatchComponent.SwatchIcon icon; if (colors.isEmpty()) { Color colorValue = ResourceHelper.parseColor(resourceName); if (colorValue != null) { icon = new SwatchComponent.ColorIcon(colorValue); } else { icon = SwatchComponent.WARNING_ICON; }/*www . j a va 2s . c o m*/ } else { icon = new SwatchComponent.ColorIcon(Iterables.getLast(colors)); icon.setIsStack(colors.size() > 1); } return icon; } List<BufferedImage> images = renderTask.renderDrawableAllStates(resValue); SwatchComponent.SwatchIcon icon; if (images.isEmpty()) { icon = SwatchComponent.WARNING_ICON; } else { icon = new SwatchComponent.SquareImageIcon(Iterables.getLast(images)); icon.setIsStack(images.size() > 1); } return icon; }
From source file:edu.harvard.med.screensaver.ui.libraries.LibraryCopyPlateSearchResults.java
@Override protected List<TableColumn<Plate, ?>> buildColumns() { List<TableColumn<Plate, ?>> columns = Lists.newArrayList(); screeningStatisticColumns = Sets.newHashSet(); volumeStatisticColumns = Sets.newHashSet(); columns.add(new IntegerEntityColumn<Plate>(PropertyPath.from(Plate.class).toProperty("plateNumber"), "Plate", "Plate number", TableColumn.UNGROUPED) { @Override//from w w w . ja v a 2 s. c o m public Integer getCellValue(Plate plate) { return plate.getPlateNumber(); } }); columns.add(new TextEntityColumn<Plate>(Plate.copy.toProperty("name"), "Copy", "The library copy containing the plate", TableColumn.UNGROUPED) { @Override public String getCellValue(Plate plate) { return plate.getCopy().getName(); } @Override public boolean isCommandLink() { return true; } @Override public Object cellAction(Plate plate) { return _libraryCopyViewer.viewEntity(plate.getCopy()); } }); Iterables.getLast(columns).setVisible(_mode != Mode.COPY); columns.add(new EnumEntityColumn<Plate, CopyUsageType>(Plate.copy.toProperty("usageType"), "Copy Usage Type", "The usage type of the copy containing the plate", TableColumn.UNGROUPED, CopyUsageType.values()) { @Override public CopyUsageType getCellValue(Plate plate) { return plate.getCopy().getUsageType(); } }); Iterables.getLast(columns).setVisible(false); columns.add(new TextEntityColumn<Plate>(Plate.copy.to(Copy.library).toProperty("libraryName"), "Library", "The library containing the plate", TableColumn.UNGROUPED) { @Override public String getCellValue(Plate plate) { return plate.getCopy().getLibrary().getLibraryName(); } @Override public boolean isCommandLink() { return true; } @Override public Object cellAction(Plate plate) { return _libraryViewer.viewEntity(plate.getCopy().getLibrary()); } }); Iterables.getLast(columns).setVisible(_mode == Mode.ALL); columns.add(new IntegerEntityColumn<Plate>(Plate.stockPlate.toProperty("plateNumber"), "Maps to Library Plate Number", "The stock plate to which this master stock plate maps", TableColumn.UNGROUPED) { @Override public Integer getCellValue(Plate plate) { return plate.getStockPlateMapping() == null ? null : plate.getStockPlateMapping().getPlateNumber(); } }); Iterables.getLast(columns).setVisible(false); columns.add(new EnumEntityColumn<Plate, Quadrant>(Plate.quadrant, "Maps To Library Plate Quadrant", "The quadrant of the stock plate to which this master stock plate maps", TableColumn.UNGROUPED, Quadrant.values()) { @Override public Quadrant getCellValue(Plate plate) { return plate.getStockPlateMapping() == null ? null : plate.getStockPlateMapping().getQuadrant(); } }); Iterables.getLast(columns).setVisible(false); columns.add(new EnumEntityColumn<Plate, ScreenType>(Plate.copy.to(Copy.library).toProperty("screenType"), "Screen Type", "'RNAi' or 'Small Molecule'", TableColumn.UNGROUPED, ScreenType.values()) { @Override public ScreenType getCellValue(Plate plate) { return plate.getCopy().getLibrary().getScreenType(); } }); Iterables.getLast(columns).setVisible(false); columns.add(new EnumEntityColumn<Plate, PlateStatus>(PropertyPath.from(Plate.class).toProperty("status"), "Status", "The plate status", TableColumn.UNGROUPED, PlateStatus.values()) { @Override public PlateStatus getCellValue(Plate plate) { return plate.getStatus(); } }); columns.add(new DateEntityColumn<Plate>( PropertyPath.from(Plate.class).to(Plate.updateActivities).to(Activity.dateOfActivity), "Status Date", "The date on which the status took effect", TableColumn.UNGROUPED) { @Override protected LocalDate getDate(Plate plate) { // note: we call getLastRecordedUpdateActivityOfType() instead of getLastUpdateActivityOfType(), as PlateBatchUpdater may // have created an status update activity with an activity date that is more recent than the current activity's status date return plate.getLastRecordedUpdateActivityOfType(AdministrativeActivityType.PLATE_STATUS_UPDATE) .getDateOfActivity(); } }); columns.add(new UserNameColumn<Plate, ScreensaverUser>( PropertyPath.from(Plate.class).to(Plate.updateActivities).to(Activity.performedBy), "Status Change Performed By", "The person that performed the activity appropriate for the plate status", TableColumn.UNGROUPED, null/* TODO */) { @Override protected ScreensaverUser getUser(Plate plate) { return plate.getLastUpdateActivityOfType(AdministrativeActivityType.PLATE_STATUS_UPDATE) .getPerformedBy(); } }); Iterables.getLast(columns).setVisible(false); columns.add(new TextEntityColumn<Plate>(Plate.location.toProperty("room"), "Room", "The room where the plate is stored", TableColumn.UNGROUPED) { @Override public String getCellValue(Plate plate) { if (plate.getLocation() == null) { return null; } return plate.getLocation().getRoom(); } }); columns.add(new TextEntityColumn<Plate>(Plate.location.toProperty("freezer"), "Freezer", "The freezer where the plate is stored", TableColumn.UNGROUPED) { @Override public String getCellValue(Plate plate) { if (plate.getLocation() == null) { return null; } return plate.getLocation().getFreezer(); } }); columns.add(new TextEntityColumn<Plate>(Plate.location.toProperty("shelf"), "Shelf", "The freezer shelf upon which plate is stored", TableColumn.UNGROUPED) { @Override public String getCellValue(Plate plate) { if (plate.getLocation() == null) { return null; } return plate.getLocation().getShelf(); } }); columns.add(new TextEntityColumn<Plate>(Plate.location.toProperty("bin"), "Bin", "The bin in which the plate is stored", TableColumn.UNGROUPED) { @Override public String getCellValue(Plate plate) { if (plate.getLocation() == null) { return null; } return plate.getLocation().getBin(); } }); columns.add(new EnumEntityColumn<Plate, PlateType>(PropertyPath.from(Plate.class).toProperty("plateType"), "Plate Type", "The plate type", TableColumn.UNGROUPED, PlateType.values()) { @Override public PlateType getCellValue(Plate plate) { return plate.getPlateType(); } }); columns.add(new VolumeEntityColumn<Plate>(PropertyPath.from(Plate.class).toProperty("wellVolume"), "Initial Well Volume", "The volume of each well of the plate when it was created", TableColumn.UNGROUPED) { @Override public Volume getCellValue(Plate plate) { return plate.getWellVolume(); } }); volumeStatisticColumns.add(Iterables.getLast(columns)); columns.add(new VolumeColumn<Plate>("Average Remaining Volume", "The average volume remaining across all wells of this plate", TableColumn.UNGROUPED) { @Override public Volume getCellValue(Plate plate) { return getNullSafeVolumeStatistics(plate).getAverageRemaining(); } }); buildConcentrationColumns(columns); columns.add(new DateEntityColumn<Plate>( PropertyPath.from(Plate.class).to(Plate.updateActivities).to(Activity.dateOfActivity), "Location Transfer Date", "The last time the plate was transfered to a new location", TableColumn.UNGROUPED) { @Override protected LocalDate getDate(Plate plate) { return plate.getLastUpdateActivityOfType(AdministrativeActivityType.PLATE_LOCATION_TRANSFER) .getDateOfActivity(); } }); Iterables.getLast(columns).setVisible(false); columns.add(new UserNameColumn<Plate, ScreensaverUser>( PropertyPath.from(Plate.class).to(Plate.updateActivities).to(Activity.performedBy), "Location Transfer Performed By ", "The person that transfered the plate to a new location", TableColumn.UNGROUPED, null/* TODO */) { @Override protected ScreensaverUser getUser(Plate plate) { return plate.getLastUpdateActivityOfType(AdministrativeActivityType.PLATE_LOCATION_TRANSFER) .getPerformedBy(); } }); Iterables.getLast(columns).setVisible(false); columns.add(new TextEntityColumn<Plate>(PropertyPath.from(Plate.class).toProperty("facilityId"), "Facility ID", "The identifier used by the facility to uniquely identify the plate", TableColumn.UNGROUPED) { @Override public String getCellValue(Plate plate) { return plate.getFacilityId(); } }); columns.add(new DateEntityColumn<Plate>(Plate.platedActivity.toProperty("dateOfActivity"), "Date Plated", "The date the plate was created", TableColumn.UNGROUPED) { @Override protected LocalDate getDate(Plate plate) { return plate.getPlatedActivity() == null ? null : plate.getPlatedActivity().getDateOfActivity(); } }); columns.add(new DateEntityColumn<Plate>(Plate.retiredActivity.toProperty("dateOfActivity"), "Date Retired", "The date the plate was retired", TableColumn.UNGROUPED) { @Override protected LocalDate getDate(Plate plate) { return plate.getRetiredActivity() == null ? null : plate.getRetiredActivity().getDateOfActivity(); } }); columns.add(new IntegerColumn<Plate>("Assay Plate Count", "The number of assay plates screened for this plate", TableColumn.UNGROUPED) { @Override public Integer getCellValue(Plate plate) { return getNullSafeScreeningStatistics(plate).getAssayPlateCount(); } }); screeningStatisticColumns.add(Iterables.getLast(columns)); columns.add(new IntegerColumn<Plate>("Screening Count", "The total number of times this plate has been screened, ignoring replicates", TableColumn.UNGROUPED) { @Override public Integer getCellValue(Plate plate) { return getNullSafeScreeningStatistics(plate).getScreeningCount(); } @Override public boolean isCommandLink() { return true; } @Override public Object cellAction(Plate plate) { _activitiesBrowser.searchLibraryScreeningActivitiesForPlate(plate); return BROWSE_ACTIVITIES; } }); screeningStatisticColumns.add(Iterables.getLast(columns)); columns.add(new DateColumn<Plate>("First Date Screened", "The date the copy was first screened", TableColumn.UNGROUPED) { @Override public LocalDate getDate(Plate plate) { return getNullSafeScreeningStatistics(plate).getFirstDateScreened(); } }); screeningStatisticColumns.add(Iterables.getLast(columns)); columns.add(new DateColumn<Plate>("Last Date Screened", "The date the copy was last screened", TableColumn.UNGROUPED) { @Override public LocalDate getDate(Plate plate) { return getNullSafeScreeningStatistics(plate).getLastDateScreened(); } }); screeningStatisticColumns.add(Iterables.getLast(columns)); columns.add(new IntegerColumn<Plate>("Data Loading Count", "The number of screen results loaded for screens of this copy", TableColumn.UNGROUPED) { @Override public Integer getCellValue(Plate plate) { return getNullSafeScreeningStatistics(plate).getDataLoadingCount(); } }); screeningStatisticColumns.add(Iterables.getLast(columns)); columns.add(new DateColumn<Plate>("First Date Data Loaded", "The date of the first screen result data loading activity", TableColumn.UNGROUPED) { @Override public LocalDate getDate(Plate plate) { return getNullSafeScreeningStatistics(plate).getFirstDateDataLoaded(); } }); screeningStatisticColumns.add(Iterables.getLast(columns)); Iterables.getLast(columns).setVisible(false); columns.add(new DateColumn<Plate>("Last Date Data Loaded", "The date of the last screen result data loading activity", TableColumn.UNGROUPED) { @Override public LocalDate getDate(Plate plate) { return getNullSafeScreeningStatistics(plate).getLastDateDataLoaded(); } }); screeningStatisticColumns.add(Iterables.getLast(columns)); Iterables.getLast(columns).setVisible(false); columns.add(new DateTimeColumn<Plate>("Last Updated", "The date on which the plate's most recent administrative update was recorded", TableColumn.UNGROUPED) { @Override public DateTime getDateTime(Plate plate) { SortedSet<AdministrativeActivity> activities = plate.getUpdateActivities(); if (activities.isEmpty()) { return null; } // TODO: should order by dateCreated, rather than dateOfActivity return activities.last().getDateCreated(); } @Override public boolean isCommandLink() { return true; } @Override public Object cellAction(Plate plate) { _entityUpdateHistoryBrowser.searchForParentEntity(plate); return BROWSE_ENTITY_UPDATE_HISTORY; } }); columns.add(new DateColumn<Plate>("Last Comment Date", "The date of the last comment added on this plate", TableColumn.UNGROUPED) { @Override public LocalDate getDate(Plate plate) { return plate.getLastUpdateActivityOfType(AdministrativeActivityType.COMMENT).getDateOfActivity(); } @Override public boolean isCommandLink() { return true; } @Override public Object cellAction(Plate plate) { _entityUpdateHistoryBrowser.searchForParentEntity(plate); _entityUpdateHistoryBrowser.setTitle("Comments for " + plate); // TODO: need user-friendly toString(), see [#2560] ((TableColumn<AdministrativeActivity, AdministrativeActivityType>) _entityUpdateHistoryBrowser .getColumnManager().getColumn("Update Type")).resetCriteria() .setOperatorAndValue(Operator.EQUAL, AdministrativeActivityType.COMMENT); return BROWSE_ENTITY_UPDATE_HISTORY; } }); columns.add(new TextEntityColumn<Plate>( PropertyPath.from(Plate.class).to(Plate.updateActivities).toProperty("comments"), "Last Comment", "Last Comment", TableColumn.UNGROUPED) { @Override public String getCellValue(Plate plate) { return plate.getLastUpdateActivityOfType(AdministrativeActivityType.COMMENT).getComments(); } }); Iterables.getLast(columns).setVisible(false); return columns; }