Java Code Examples for java.util.List.isEmpty()

The following are Jave code examples for showing how to use isEmpty() of the java.util.List class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: athena   File: DeviceInterfacesListCommand.java   View Source Code Vote up 7 votes
private void printDevice(DeviceService deviceService,
                         DriverService driverService,
                         Device device) {
    super.printDevice(deviceService, device);
    if (!device.is(InterfaceConfig.class)) {
        // The relevant behavior is not supported by the device.
        print(ERROR_RESULT);
        return;
    }
    DriverHandler h = driverService.createHandler(device.id());
    InterfaceConfig interfaceConfig = h.behaviour(InterfaceConfig.class);

    List<DeviceInterfaceDescription> interfaces =
            interfaceConfig.getInterfaces(device.id());
    if (interfaces == null) {
        print(ERROR_RESULT);
    } else if (interfaces.isEmpty()) {
        print(NO_INTERFACES);
    } else {
        interfaces.forEach(this::printInterface);
    }
}
 
Example 2
Project: vertx-spring   File: AbstractDispatchingMetrics.java   View Source Code Vote up 6 votes
protected final <N extends Metrics> N createSubMetrics(
        Function<M, ? extends N> supplier,
        Function<List<? extends N>, ? extends N> dispatchingMetricsSupplier) {
    List<N> allSubMetrics = new ArrayList<>(delegates.size());
    for (M delegate : delegates) {
        N subMetrics = supplier.apply(delegate);
        if (subMetrics != null) {
            allSubMetrics.add(subMetrics);
        }
    }
    if (allSubMetrics.isEmpty()) {
        return null;
    } else if (allSubMetrics.size() == 1) {
        return allSubMetrics.get(0);
    } else {
        return dispatchingMetricsSupplier.apply(allSubMetrics);
    }
}
 
Example 3
Project: cascade   File: SelectorParser.java   View Source Code Vote up 6 votes
private Matcher parseSequence() {
    List<Matcher> matchers = new ArrayList<>();
    int index = 0;
    Token token = nextNonSpaceToken();
    Matcher matcher;
    while ((matcher = parseSimpleSelector(token, index++, false)) != null) {
        matchers.add(matcher);
        token = peekToken();
        if (token.isEndOfSequence()) {
            break;
        } else {
            token = nextToken();
        }
    }
    if (matchers.isEmpty()) {
        return null;
    }
    if (!matchers.get(0).getType().representsType()) {
        matchers.add(0, newUniversalSelector());
    }
    return Matchers.allOf(matchers);
}
 
Example 4
Project: jsf-core   File: ScanClientManagerImpl.java   View Source Code Vote up 5 votes
@Override
public int updateStatusOffline(List<Client> clientList) throws Exception {
    List<Integer> idList = getIdList(clientList);
    if(idList != null && !idList.isEmpty()){
        return scanClientDao.updateStatusOffline(idList, InstanceStatus.offline.value().intValue());
    }
    return 0;
}
 
Example 5
Project: OpenYOLO-Android   File: CredentialClient.java   View Source Code Vote up 5 votes
@Nullable
private ComponentName getPreferredProvider(@NonNull List<ComponentName> providers) {
    // In the future, the user will be able to explicitly set their preferred provider in
    // their device settings. For now, we heuristically determine the preferred provider based
    // on the following rules:

    // 1. If there are any unknown providers on the device, there is no preferred provider.
    List<ComponentName> knownProviders = filterToKnownProviders(providers);
    if (knownProviders.size() != providers.size()) {
        return null;
    }

    // 2. If there are no known providers, then there is no preferred provider. Unknown
    // providers are not trusted for automatic usage.
    if (knownProviders.isEmpty()) {
        return null;
    }

    // 3. If there is exactly one provider on the device and it is known,
    // it is the preferred provider.
    if (knownProviders.size() == 1) {
        return knownProviders.get(0);
    }

    // 3. If there are exactly two known providers on the device, and one of them is Google,
    // choose the other one.
    // This reflects the reality that Google is pre-installed on most devices, whereas a second
    // provider would likely have been explicitly installed by the user - it is likely that
    // their intent is to use this other provider.
    providers = filterOutGoogle(knownProviders);
    if (providers.size() == 1) {
        return knownProviders.get(0);
    }

    // 4. Otherwise, there is no preferred provider.
    return null;
}
 
Example 6
Project: pub-service   File: StringUtil.java   View Source Code Vote up 5 votes
/**
 * 将一个list转为以split分隔的string
 * 
 * @param list
 * @param split
 * @return
 */
public static String listToString(List list, String split) {
	if (list == null || list.isEmpty())
		return "";
	StringBuffer sb = new StringBuffer();
	for (Object obj : list) {
		if (sb.length() != 0) {
			sb.append(split);
		}
		sb.append(obj.toString());
	}
	return sb.toString();
}
 
Example 7
Project: time4sys   File: DesignEditor.java   View Source Code Vote up 5 votes
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
public void gotoMarker(IMarker marker) {
	List<?> targetObjects = markerHelper.getTargetObjects(editingDomain, marker);
	if (!targetObjects.isEmpty()) {
		setSelectionToViewer(targetObjects);
	}
}
 
Example 8
Project: FreeCol   File: DebugUtils.java   View Source Code Vote up 5 votes
/**
 * Debug action to dump a players units/iterators to stderr.
 *
 * Called from the debug menu.
 * TODO: missing i18n
 *
 * @param freeColClient The {@code FreeColClient} for the game.
 */
public static void displayUnits(final FreeColClient freeColClient) {
    final Player player = freeColClient.getMyPlayer();
    List<Unit> all = player.getUnitList();
    LogBuilder lb = new LogBuilder(256);
    lb.add("\nActive units:\n");

    Unit u, first = player.getNextActiveUnit();
    if (first != null) {
        lb.add(first.toString(), "\nat ", first.getLocation(), "\n");
        all.remove(first);
        while (player.hasNextActiveUnit()
            && (u = player.getNextActiveUnit()) != first) {
            lb.add(u, "\nat ", u.getLocation(), "\n");
            all.remove(u);
        }
    }
    lb.add("Going-to units:\n");
    first = player.getNextGoingToUnit();
    if (first != null) {
        all.remove(first);
        lb.add(first, "\nat ", first.getLocation(), "\n");
        while (player.hasNextGoingToUnit()
            && (u = player.getNextGoingToUnit()) != first) {
            lb.add(u, "\nat ", u.getLocation(), "\n");
            all.remove(u);
        }
    }
    lb.add("Remaining units:\n");
    while (!all.isEmpty()) {
        u = all.remove(0);
        lb.add(u, "\nat ", u.getLocation(), "\n");
    }

    freeColClient.getGUI().showInformationMessage(lb.toString());
}
 
Example 9
Project: FreeCol   File: ServerColony.java   View Source Code Vote up 5 votes
/**
 * Builds a building from a build queue.
 *
 * @param buildQueue The {@code BuildQueue} to build from.
 * @param cs A {@code ChangeSet} to update.
 * @return True if the build succeeded.
 */
private boolean csBuildBuilding(BuildQueue<? extends BuildableType> buildQueue,
                                ChangeSet cs) {
    BuildingType type = (BuildingType) buildQueue.getCurrentlyBuilding();
    Tile copied = getTile().getTileToCache();
    BuildingType from = type.getUpgradesFrom();
    boolean success;
    if (from == null) {
        success = buildBuilding(new ServerBuilding(getGame(), this, type));//-til
    } else {
        Building building = getBuilding(from);
        List<Unit> eject = building.upgrade();//-til
        success = eject != null;
        if (success) {
            ejectUnits(building, eject);//-til
            if (!eject.isEmpty()) getTile().cacheUnseen(copied);//+til
        } else {
            cs.addMessage(owner, getUnbuildableMessage(type));
        }
    }
    if (success) {
        cs.addMessage(owner,
            new ModelMessage(MessageType.BUILDING_COMPLETED,
                             "model.colony.buildingReady", this)
                .addName("%colony%", getName())
                .addNamed("%building%", type));
        if (owner.isAI()) {
            firePropertyChange(REARRANGE_COLONY, true, false);
        }
        logger.info("New building in " + getName()
            + ": " + type.getSuffix());
    }
    return success;
}
 
Example 10
Project: testee.fi   File: IteratorUtils.java   View Source Code Vote up 5 votes
/**
 * Creates a composite iterator.
 *
 * @param items      the list items from which iterators can be retrieved.
 * @param toIterator the function to retrieve an iterator from a list item.
 * @param <T>        the type of the list items.
 * @param <S>        the iterated type.
 * @return a composite iterator.
 */
public static <T, S> Iterator<S> composite(
        final List<T> items,
        final Function<T, Iterator<S>> toIterator
) {
    final MutableContainer<Iterator<S>> container = new MutableContainer<>();
    return new Iterator<S>() {
        @Override
        public boolean hasNext() {
            if (container.getObject() == null || !container.getObject().hasNext()) {
                if (items.isEmpty()) {
                    return false;
                }
                container.setObject(toIterator.apply(items.remove(0)));
            } else {
                return true;
            }
            return hasNext();
        }

        @Override
        public S next() {
            if (!hasNext()) {
                return null;
            }
            return container.getObject().next();
        }
    };
}
 
Example 11
Project: fpm   File: Tomtom2Osm.java   View Source Code Vote up 5 votes
public Optional<String> run() throws IOException {
    Stopwatch stopwatch = Stopwatch.createStarted();
    log.info("Start generating {}", outputZone);
    new File(outputZone).mkdirs();

    List<String> profileShapeFiles = newArrayList();

    for (ClassInfo clazz : shapefiles()) {
        log.info("Converting {}", clazz.getSimpleName());
        TomtomShapefile shapefile = (TomtomShapefile) injector.getInstance(clazz.load());
        if (shapefile.getFile().exists()) {
            shapefile.serialize(outputZone);
            profileShapeFiles.add(shapefile.getOutputFile());
        } else {
            log.info("No input file found");
        }
    }

    if (profileShapeFiles.isEmpty()) {
        return empty();
    }

    osmMerger.merge(profileShapeFiles, outputZone + OSM_SUFFIX);
    log.info("Done generating {} in {}", outputZone + OSM_SUFFIX, stopwatch);

    stopwatch.reset();
    stopwatch.start();

    splitter.run();
    log.info("Done splitting {} in {}", outputZone, stopwatch);

    return of(outputZone + OSM_SUFFIX);
}
 
Example 12
Project: incubator-netbeans   File: PullAction.java   View Source Code Vote up 5 votes
@Override
public Void call () throws HgException {
    OutputLogger logger = supp.getLogger();
    topPatch = FetchAction.selectPatch(root);
    if (topPatch != null) {
        supp.setDisplayName(Bundle.MSG_PullAction_popingPatches());
        SystemAction.get(QGoToPatchAction.class).popAllPatches(root, logger);
        supp.setDisplayName(Bundle.MSG_PullAction_pulling());
        logger.output(""); // NOI18N
    }
    if (supp.isCanceled()) {
        return null;
    }
    List<String> list;
    if(type == PullType.LOCAL){
        supp.setDisplayName(Bundle.MSG_PullAction_progress_pullingFromLocal());
        list = HgCommand.doPull(root, revision, branch, logger);
    }else{
        supp.setDisplayName(Bundle.MSG_PullAction_progress_unbundling());
        list = HgCommand.doUnbundle(root, fileToUnbundle, false, logger);
    }
    if (list != null && !list.isEmpty()) {
        annotateChangeSets(HgUtils.replaceHttpPassword(listIncoming), PullAction.class, "MSG_CHANGESETS_TO_PULL", logger); // NOI18N
        handlePulledChangesets(list);
    }

    return null;
}
 
Example 13
Project: dremio-oss   File: S3PluginConfig.java   View Source Code Vote up 5 votes
/**
 * Helper method to get configuration for S3 implementation of {@link FileSystem} from
 * given S3 access credentials and property list.
 */
private static Map<String, String> getConfig(final String accessKey, final String accessSecret,
    final boolean secure, List<String> externalBuckets, final Map<String, String> properties) {
  final Map<String, String> finalProperties = Maps.newHashMap();
  finalProperties.put(FileSystem.FS_DEFAULT_NAME_KEY, "dremioS3:///");
  finalProperties.put("fs.dremioS3.impl", S3FileSystem.class.getName());
  finalProperties.put(MAXIMUM_CONNECTIONS, String.valueOf(DEFAULT_MAX_CONNECTIONS));
  if(accessKey != null){
    finalProperties.put(ACCESS_KEY, accessKey);
    finalProperties.put(SECRET_KEY, accessSecret);
  } else {
    // don't use Constants here as it breaks when using older MapR/AWS files.
    finalProperties.put("fs.s3a.aws.credentials.provider", "org.apache.hadoop.fs.s3a.AnonymousAWSCredentialsProvider");
  }

  if (properties != null && !properties.isEmpty()) {
    for (Entry<String, String> property : properties.entrySet()) {
      finalProperties.put(property.getKey(), property.getValue());
    }
  }


  finalProperties.put(SECURE_CONNECTIONS, String.valueOf(secure));
  if(externalBuckets != null && !externalBuckets.isEmpty()){
    finalProperties.put(EXTERNAL_BUCKETS, Joiner.on(",").join(externalBuckets));
  }else {
    if(accessKey == null){
      throw UserException.validationError()
        .message("Failure creating S3 connection. You must provide at least one of: (1) access key and secret key or (2) one or more external buckets.")
        .build(logger);
    }
  }

  return finalProperties;
}
 
Example 14
Project: incubator-netbeans   File: MultiViewTopComponent.java   View Source Code Vote up 5 votes
/**
 * merge action for the topcomponent and the enclosed MultiViewElement..
 * 
 */
@Override
public Action[] getActions() {
    //TEMP don't delegate to element's actions..
    Action[] superActions = superActions4Tests == null ? super.getActions() : superActions4Tests;
    List<Action> acts = new ArrayList<Action>(Arrays.asList(peer.peerGetActions(superActions)));
    if( !acts.isEmpty() )
        acts.add(null);
    acts.add(new EditorsAction());
    if( canSplit() ) {
        acts.add(new SplitAction(true));
    }
    return acts.toArray(new Action[acts.size()]);
}
 
Example 15
Project: n4js   File: N4HeadlessCompiler.java   View Source Code Vote up 4 votes
/**
 * Collects the projects to compile and finds their dependencies in the given search paths and registers them with
 * the file-based workspace.
 *
 * @param searchPaths
 *            where to search for dependent projects.
 * @param projectPaths
 *            the projects to compile. the base folder of each project must be provided.
 * @param singleSourceFiles
 *            if non-empty limit compilation to the sources files listed here
 * @return an instance of {@link BuildSet} containing the collected projects and a filter to apply if single source
 *         files were requested to be compiled
 * @throws N4JSCompileException
 *             if an error occurs while registering the projects
 */
private BuildSet collectAndRegisterProjects(List<File> searchPaths, List<File> projectPaths,
		List<File> singleSourceFiles) throws N4JSCompileException {

	// Make absolute, since downstream URI conversion doesn't work if relative dir only.
	List<File> absSearchPaths = HeadlessHelper.toAbsoluteFileList(searchPaths);
	List<File> absProjectPaths = HeadlessHelper.toAbsoluteFileList(projectPaths);
	List<File> absSingleSourceFiles = HeadlessHelper.toAbsoluteFileList(singleSourceFiles);

	// Discover projects in search paths.
	List<File> discoveredProjectLocations = HeadlessHelper.collectAllProjectPaths(absSearchPaths);

	// Discover projects for single source files.
	List<File> singleSourceProjectLocations = findProjectsForSingleFiles(absSingleSourceFiles);

	// Register single-source projects as to be compiled as well.
	List<File> absRequestedProjectLocations = Collections2.concatUnique(absProjectPaths,
			singleSourceProjectLocations);

	// Convert absolute locations to file URIs.
	List<URI> requestedProjectURIs = createFileURIs(absRequestedProjectLocations);
	List<URI> discoveredProjectURIs = createFileURIs(discoveredProjectLocations);

	// Obtain the projects and store them.
	List<N4JSProject> requestedProjects = getN4JSProjects(requestedProjectURIs);
	List<N4JSProject> discoveredProjects = getN4JSProjects(discoveredProjectURIs);

	// Register all projects with the file based workspace.
	registerProjectsToFileBasedWorkspace(Iterables.concat(requestedProjectURIs, discoveredProjectURIs));

	// Create a filter that applies only to the given single source files if any were requested to be compiled.
	Predicate<URI> resourceFilter;
	if (absSingleSourceFiles.isEmpty()) {
		resourceFilter = u -> true;
	} else {
		Set<URI> singleSourceURIs = new HashSet<>(createFileURIs(absSingleSourceFiles));
		resourceFilter = u -> singleSourceURIs.contains(u);
	}

	return new BuildSet(requestedProjects, discoveredProjects, resourceFilter);
}
 
Example 16
Project: incubator-netbeans   File: TryCatchFinally.java   View Source Code Vote up 4 votes
@Hint(category = "bugs",
      displayName = "#DN_TryCatchFinally_finallyDiscardsException", // NOI18N
      description = "#DESC_TryCatchFinally_finallyDiscardsException", // NOI18N
      suppressWarnings={"FinallyDiscardsException", "", "ReturnFromFinallyBlock", "ContinueOrBreakFromFinallyBlock"}, 
      options= Hint.Options.QUERY
)
@TriggerPattern("try { $smts$; } catch $catches$ finally { $handler$; }") // NOI18N
public static List<ErrorDescription> finallyDiscardsException(HintContext ctx) {
    List<TreePath>  trees = new ArrayList<TreePath>(3);
    ExitsFromBranches efab = new ExitsFromBranches(ctx.getInfo());
    Collection<? extends TreePath> paths = ctx.getMultiVariables().get("$handler$"); // NOI18N
    
    for (TreePath tp : paths) {
        efab.scan(tp, trees);
    }
    if (trees.isEmpty()) {
        return null;
    }
    List<ErrorDescription> errs = new ArrayList<ErrorDescription>(trees.size());
    for (TreePath p : trees) {
        Tree stmt = p.getLeaf();
        final String stmtName;
        switch (stmt.getKind()) {
            case CONTINUE:
                stmtName = "continue"; // NOI18N
                break;
            case BREAK:
                stmtName = "break"; // NOI18N
                break;
            case RETURN:
                stmtName = "return"; // NOI18N
                break;
            default:
                LOG.log(Level.WARNING, "Unexpected statement kind: {0}", stmt.getKind()); // NOI18N
                continue;
        }
        
        errs.add(ErrorDescriptionFactory.forTree(ctx, stmt, TEXT_returnBreakContinueInFinallyBlock(stmtName)));
    }
    return errs;
}
 
Example 17
Project: IOTAFaucet   File: MongoDatabaseProvider.java   View Source Code Vote up 4 votes
@Override
public StoredBundle getLastBundle() {
    List<StoredBundle> bundles = datastore.createQuery(StoredBundle.class).order(Sort.descending("bundleId")).asList(new FindOptions().limit(1));
    return bundles.isEmpty() ? null : bundles.get(0);
}
 
Example 18
Project: monarch   File: DataCommands.java   View Source Code Vote up 4 votes
boolean checkResultList(CompositeResultData rebalanceResulteData, List resultList,
    DistributedMember member) {
  boolean toContinueForOtherMembers = false;

  if (resultList != null && !resultList.isEmpty()) {
    for (int i = 0; i < resultList.size(); i++) {
      Object object = resultList.get(i);
      if (object instanceof Exception) {

        rebalanceResulteData.addSection().addData(
            CliStrings.format(CliStrings.REBALANCE__MSG__NO_EXECUTION, member.getId()),
            ((Exception) object).getMessage());

        LogWrapper.getInstance().info(CliStrings.REBALANCE__MSG__NO_EXECUTION + member.getId()
            + " exception=" + ((Throwable) object).getMessage(), ((Throwable) object));

        toContinueForOtherMembers = true;
        break;
      } else if (object instanceof Throwable) {
        rebalanceResulteData.addSection().addData(
            CliStrings.format(CliStrings.REBALANCE__MSG__NO_EXECUTION, member.getId()),
            ((Throwable) object).getMessage());

        LogWrapper.getInstance().info(CliStrings.REBALANCE__MSG__NO_EXECUTION + member.getId()
            + " exception=" + ((Throwable) object).getMessage(), ((Throwable) object));

        toContinueForOtherMembers = true;
        break;
      }
    }
  } else {
    LogWrapper.getInstance().info(
        "Rebalancing for member=" + member.getId() + ", resultList is either null or empty");
    rebalanceResulteData.addSection().addData("Rebalancing for member=" + member.getId(),
        ", resultList is either null or empty");
    toContinueForOtherMembers = true;
  }

  return toContinueForOtherMembers;

}
 
Example 19
Project: osc-core   File: PluginResolveContext.java   View Source Code Vote up 4 votes
boolean isInitialResource(Resource resource) {
	List<Capability> markerCaps = resource.getCapabilities(INITIAL_RESOURCE_CAPABILITY_NAMESPACE);
	return markerCaps != null && !markerCaps.isEmpty();
}
 
Example 20
Project: freecol   File: Player.java   View Source Code Vote up 3 votes
/**
 * The second and third cases of buildOnNative land need to test
 * if the player has no settlements yet.  We can not just check
 * that the number of settlement is zero because by the time the
 * settlement is being placed and we are collecting the tiles to
 * claim, the settlement already exists and thus there will
 * already be one settlement--- so we have to check if that one
 * settlement is on the map yet.
 *
 * @return True if the player has no settlements (on the map) yet.
 */
private boolean hasZeroSettlements() {
    List<Settlement> settlements = getSettlementList();
    return settlements.isEmpty()
        || (settlements.size() == 1
            && settlements.get(0).getTile().getSettlement() == null);
}