Example usage for java.util ArrayList isEmpty

List of usage examples for java.util ArrayList isEmpty

Introduction

In this page you can find the example usage for java.util ArrayList isEmpty.

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if this list contains no elements.

Usage

From source file:chanupdater.ChanUpdater.java

private void getChanListFiles() throws IOException, NoSuchAlgorithmException, LdvTableException {
    for (ChanListSummary cls : cLists) {
        int cnt = cls.getCount();
        if (cnt > 0) {
            String srv = "";
            String ctypStr = "";
            try {
                srv = cls.getServer();//from   w  w  w.  j  a v a2 s .c o m
                ctypStr = cls.getcType();
                if (verbose > 1) {
                    System.out.format("Get channel list from %1$s for type: %2$s%n", srv, ctypStr);
                }
                nds = new NDSProxyClient(srv);
                nds.connect(600000);
                ArrayList<ChanInfo> channelList = nds.getChanList(ctypStr);
                if (channelList != null && !channelList.isEmpty()) {
                    Collections.sort(channelList);
                    cls.dumpFile(channelList);
                }
            } catch (NDSException ex) {
                System.err.format("Error with %1$s type at %2$s: %3$s - %4$s", ctypStr, srv,
                        ex.getClass().getSimpleName(), ex.getLocalizedMessage());
            }
            try {
                if (nds != null) {
                    nds.bye();
                }
            } catch (NDSException ex) {
                System.out.format("Server: %1$s, error on disconnect: %2$s%n", srv, ex.getLocalizedMessage());
            }
            cls.printSummary();
        }
    }
}

From source file:edu.isi.wings.catalog.component.api.impl.kb.ComponentCreationKB.java

private ComponentTree createComponentHierarchy(String classid, boolean details) {
    ComponentHolder rootitem = new ComponentHolder(classid);
    ComponentTreeNode rootnode = new ComponentTreeNode(rootitem);
    ArrayList<ComponentTreeNode> queue = new ArrayList<ComponentTreeNode>();
    queue.add(rootnode);/*  w  w  w.j  a  v  a2  s .  c  o m*/

    while (!queue.isEmpty()) {
        ComponentTreeNode node = queue.remove(0);
        ComponentHolder cls = node.getCls();
        if (cls.getID() == null)
            continue;

        KBObject clsobj = kb.getConcept(cls.getID());
        if (clsobj == null)
            continue;

        ArrayList<KBObject> compobjs = kb.getInstancesOfClass(clsobj, true);
        for (KBObject compobj : compobjs) {
            if (cls.getID().equals(this.topclass)) {
                // The top class cannot be used as a holder. If we find any
                // components having the top class as the holder, we delete them
                this.removeComponent(compobj.getID(), true, true);
            } else {
                // Add the component as the holder's component
                cls.setComponent(this.getComponent(compobj.getID(), details));
            }
        }

        ArrayList<KBObject> subclasses = this.kb.getSubClasses(clsobj, true);
        for (KBObject subcls : subclasses) {
            if (!subcls.getNamespace().equals(this.pcdomns) && !subcls.getNamespace().equals(this.pcns))
                continue;
            ComponentHolder clsitem = new ComponentHolder(subcls.getID());
            ComponentTreeNode childnode = new ComponentTreeNode(clsitem);
            node.addChild(childnode);
            queue.add(childnode);
        }
    }
    ComponentTree tree = new ComponentTree(rootnode);
    return tree;
}

From source file:edu.oregonstate.eecs.mcplan.domains.voyager.policies.AggressivePolicy.java

@Override
public VoyagerAction getAction() {
    // Locate a large friendly force
    final ArrayList<Planet> friendly = Voyager.playerPlanets(s_, player_);
    Collections.sort(friendly, new Comparator<Planet>() {
        @Override//from   ww w. ja  v  a 2s . c  o m
        public int compare(final Planet a, final Planet b) {
            return b.population(Unit.Soldier) - a.population(Unit.Soldier);
        }
    });

    final Planet primary = (friendly.isEmpty() ? null : friendly.get(0));
    final Planet secondary = (friendly.size() <= 1 ? null : friendly.get(1));
    final int primary_force = (primary != null ? primary.population(Unit.Soldier) - garrison_ : 0);
    final int secondary_force = (secondary != null ? secondary.population(Unit.Soldier) - garrison_ : 0);
    final int force = primary_force + secondary_force;

    if (primary != null) {
        // Sort enemy planets by defense strength per worker
        final ArrayList<Planet> enemy = Voyager.playerPlanets(s_, player_.enemy());
        Collections.sort(enemy, new Comparator<Planet>() {
            @Override
            public int compare(final Planet a, final Planet b) {
                final int[] apop = Voyager.effectivePopulation(s_, a, player_.enemy());
                final int[] bpop = Voyager.effectivePopulation(s_, b, player_.enemy());
                final double aratio = apop[Unit.Worker.ordinal()] > 0
                        ? Voyager.defense_strength(apop) / apop[Unit.Worker.ordinal()]
                        : Double.MAX_VALUE;
                final double bratio = bpop[Unit.Worker.ordinal()] > 0
                        ? Voyager.defense_strength(bpop) / bpop[Unit.Worker.ordinal()]
                        : Double.MAX_VALUE;
                return (int) Math.signum(aratio - bratio);
            }
        });
        // Find the enemy Planet with the best worker ratio that we have
        // enough forces to take over.
        for (final Planet p : enemy) {
            final int[] pop = Voyager.effectivePopulation(s_, p, player_.enemy());
            final int d = Voyager.defense_strength(pop);
            final int a = Voyager.attack_strength(new int[] { 0, primary_force });
            if (a > d) {
                return new LaunchAction(primary, p, new int[] { 0, primary_force });
            }
        }

        // If there isn't a promising attack available, shift some soldiers
        for (final Planet p : friendly) {
            if (!p.equals(primary) && !p.equals(secondary)) {
                final int soldiers = p.population(Unit.Soldier) - garrison_;
                if (soldiers > 0) {
                    return new LaunchAction(p, primary, new int[] { 0, soldiers });
                }
            }
        }
    }

    // If there are no soldiers to shift, optimize production
    for (final Planet p : friendly) {
        if (p.nextProduced() == Unit.Worker && p.population(Unit.Worker) >= p.capacity) {
            return new SetProductionAction(p, Unit.Soldier);
        }
    }

    return new NothingAction();
}

From source file:org.khmeracademy.btb.auc.pojo.controller.Auction_controller.java

@RequestMapping(value = "/search-product/{pro_name}", method = RequestMethod.GET, produces = "application/json")
@ResponseBody/*w ww. ja  va 2s  .com*/
public ResponseEntity<Map<String, Object>> searchAuctionByProductName(
        @RequestParam(value = "page", required = false, defaultValue = "1") int page,
        @RequestParam(value = "limit", required = false, defaultValue = "6") int limit,
        @PathVariable("pro_name") String pro_name) {
    Map<String, Object> map = new HashMap<String, Object>();
    try {
        Pagination pagination = new Pagination();
        pagination.setLimit(limit);
        pagination.setPage(page);
        pagination.setTotalCount(auc_service.countAuctionByProductName(pro_name));
        ArrayList<Auction_Detail> auction = auc_service.searchAuctionByProductName(pagination, pro_name);
        if (!auction.isEmpty()) {
            map.put("DATA", auction);
            map.put("STATUS", true);
            map.put("MESSAGE", "DATA FOUND!");
            map.put("PAGINATION", pagination);
        } else {
            map.put("STATUS", true);
            map.put("MESSAGE", "DATA NOT FOUND");
        }
    } catch (Exception e) {
        map.put("STATUS", false);
        map.put("MESSAGE", "Error!");
        e.printStackTrace();
    }
    return new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK);
}

From source file:feedsplugin.FeedsPlugin.java

@Override
public ActionMenu getButtonAction() {
    if (mSettings == null) {
        return null;
    }/*from  w  ww  .j  a  v a2 s .com*/
    ArrayList<String> feedTitles = mSettings.getCachedFeedTitles();
    if (feedTitles.isEmpty()) {
        return null;
    }
    ContextMenuAction mainAction = new ContextMenuAction(mLocalizer.msg("name", "Feeds"), getPluginIcon());
    ArrayList<AbstractAction> list = new ArrayList<AbstractAction>(feedTitles.size());
    for (int i = 0; i < feedTitles.size(); i++) {
        final String title = feedTitles.get(i);
        final int feedIndex = i;
        list.add(new AbstractAction(title) {

            public void actionPerformed(ActionEvent e) {
                SyndFeed selectedFeed = mFeeds.get(feedIndex);
                if (selectedFeed != null) {
                    List entries = selectedFeed.getEntries();
                    showFeedsDialog(new FeedsDialog(getParentFrame(), entries));
                }
            }
        });
    }
    Collections.sort(list, new Comparator<AbstractAction>() {

        public int compare(AbstractAction o1, AbstractAction o2) {
            return ((String) o1.getValue(AbstractAction.NAME))
                    .compareTo((String) o2.getValue(AbstractAction.NAME));
        }
    });
    return new ActionMenu(mainAction, list.toArray(new AbstractAction[list.size()]));
}

From source file:org.khmeracademy.btb.auc.pojo.controller.Auction_controller.java

@RequestMapping(value = "/get-all", method = RequestMethod.GET, produces = "application/json")
@ApiImplicitParams({ @ApiImplicitParam(name = "page", paramType = "query", defaultValue = "1"),
        @ApiImplicitParam(name = "limit", paramType = "query", defaultValue = "10"),
        @ApiImplicitParam(name = "name", paramType = "query", defaultValue = ""),
        @ApiImplicitParam(name = "categoryId", paramType = "query", defaultValue = "") })
@ResponseBody/*from w  ww.j  a v  a 2s.  c  o m*/
public ResponseEntity<Map<String, Object>> findAll(@ApiIgnore AuctionFilter filter,
        @ApiIgnore Pagination pagination) {
    Map<String, Object> map = new HashMap<String, Object>();
    try {
        pagination.setTotalCount(auc_service.count(filter));
        ArrayList<Auction_Detail> auction = (ArrayList<Auction_Detail>) auc_service.findAll(filter, pagination);
        if (!auction.isEmpty()) {
            map.put("DATA", auction);
            map.put("STATUS", true);
            map.put("MESSAGE", "DATA FOUND!");
            map.put("PAGINATION", pagination);
        } else {
            map.put("STATUS", true);
            map.put("MESSAGE", "DATA NOT FOUND");
        }
    } catch (Exception e) {
        map.put("STATUS", false);
        map.put("MESSAGE", "Error!");
        e.printStackTrace();
    }
    return new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK);
}

From source file:com.chiorichan.http.Route.java

public String match(String domain, String subdomain, String uri) {
    String prop = params.get("pattern");

    if (prop == null)
        prop = params.get("page");

    if (prop == null) {
        Log.get().warning("The `pattern` attribute was null for route '" + this + "'. Unusable!");
        return null;
    }//  w w w.j  a  va2  s .  c o  m

    prop = StringUtils.trimToEmpty(prop);
    uri = StringUtils.trimToEmpty(uri);

    if (prop.startsWith("/")) {
        prop = prop.substring(1);
        params.put("pattern", prop);
    }

    if (!StringUtils.trimToEmpty(params.get("subdomain")).equals("*")
            && !subdomain.equals(params.get("subdomain"))) {
        Log.get().finer("The subdomain does not match for " + uri + " on route " + this);
        return null;
    }

    String[] propsRaw = prop.split("[.//]");
    String[] urisRaw = uri.split("[.//]");

    ArrayList<String> props = Lists.newArrayList();
    ArrayList<String> uris = Lists.newArrayList();

    for (String s : propsRaw)
        if (s != null && !s.isEmpty())
            props.add(s);

    for (String s : urisRaw)
        if (s != null && !s.isEmpty())
            uris.add(s);

    if (uris.isEmpty())
        uris.add("");

    if (props.isEmpty())
        props.add("");

    if (props.size() > uris.size()) {
        Log.get().finer("The length of elements in route " + this
                + " is LONGER then the length of elements on the uri; " + uris);
        return null;
    }

    if (props.size() < uris.size()) {
        Log.get().finer("The length of elements in route " + this
                + " is SHORTER then the length of elements on the uri; " + uris);
        return null;
    }

    String weight = StringUtils.repeat("?", Math.max(props.size(), uris.size()));

    boolean match = true;
    for (int i = 0; i < Math.max(props.size(), uris.size()); i++)
        try {
            Log.get().finest(prop + " --> " + props.get(i) + " == " + uris.get(i));

            if (props.get(i).matches("\\[([a-zA-Z0-9]+)=\\]")) {
                weight = StringFunc.replaceAt(weight, i, "Z");

                String key = props.get(i).replaceAll("[\\[\\]=]", "");
                String value = uris.get(i);

                rewrites.put(key, value);

                // PREG MATCH
                Log.get().finer("Found a PREG match for " + prop + " on route " + this);
            } else if (props.get(i).equals(uris.get(i))) {
                weight = StringFunc.replaceAt(weight, i, "A");

                Log.get().finer("Found a match for " + prop + " on route " + this);
                // MATCH
            } else {
                match = false;
                Log.get().finer("Found no match for " + prop + " on route " + this);
                break;
                // NO MATCH
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            match = false;
            break;
        }

    return match ? weight : null;
}

From source file:com.aliyun.odps.ship.upload.DshipUpload.java

private void uploadBlock() throws IOException, TunnelException, ParseException {
    int threads = Integer.valueOf(DshipContext.INSTANCE.get(Constants.THREADS));
    ExecutorService executors = Executors.newFixedThreadPool(threads);
    ArrayList<Callable<Long>> callList = new ArrayList<Callable<Long>>();
    for (BlockInfo block : blockIndex) {
        final BlockUploader uploader = new BlockUploader(block, tunnelUploadSession, sessionHistory);
        Callable<Long> call = new Callable<Long>() {
            @Override//from w w  w .  j a  v a 2  s.  com
            public Long call() throws Exception {
                uploader.upload();
                return 0L;
            }
        };

        callList.add(call);
    }

    try {
        List<Future<Long>> futures = executors.invokeAll(callList);
        ArrayList<String> failedBlock = new ArrayList<String>();
        for (int i = 0; i < futures.size(); ++i) {
            try {
                futures.get(i).get();
            } catch (ExecutionException e) {
                e.printStackTrace();
                failedBlock.add(String.valueOf(i));
            }
        }
        if (!failedBlock.isEmpty()) {
            throw new TunnelException("Block ID:" + StringUtils.join(failedBlock, ",") + " Failed.");
        }
    } catch (InterruptedException e) {
        throw new UserInterruptException(e.getMessage());
    }
}

From source file:org.bishoph.oxdemo.OXDemo.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.v("OXDemo", "onActivityResult " + resultCode + " // " + RESULT_OK);
    if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
        ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
        Log.v("OXDemo", "All text reconition: " + matches);
        if (matches != null && !matches.isEmpty()) {
            String bestResult = matches.get(0).toString();
            if (bestResult != null && bestResult.length() > 0) {
                Log.v("OXDemo", "Best result from text reconition: " + bestResult);
                if (folder_id > -1) {
                    createTask(folder_id, bestResult);
                }/* w w w .j a v a 2s .  c om*/
            }
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}

From source file:com.fitbur.testify.junit.system.SpringBootSystemTest.java

@Override
protected Statement methodBlock(FrameworkMethod method) {
    TestClass testClass = getTestClass();
    Class<?> javaClass = testClass.getJavaClass();

    Object testInstance;//from www  . j  a v a2s  .co m

    try {
        testInstance = createTest();
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    TestContext testContext = getTestContext(javaClass);
    testContext.setTestInstance(testInstance);

    Optional<App> appOptional = testContext.getAnnotation(App.class);
    checkState(appOptional.isPresent(), "Test class '%s' is not annotated with @App annotation.",
            testClass.getName());

    App app = appOptional.get();
    Set<Class<?>> modules = testContext.getAnnotations(Module.class).parallelStream().map(p -> p.value())
            .collect(toSet());

    Set<Object> sources = new LinkedHashSet<>();
    sources.add(app.value());
    sources.addAll(modules);

    application = new SpringApplicationBuilder(sources.toArray()).bannerMode(Banner.Mode.OFF).build();

    APPLICATION_TEST_CONTEXTS.computeIfAbsent(application, p -> testContext);

    application.run();

    SpringBootDescriptor descriptor = APPLICATION_DESCRIPTORS.get(application);

    ServiceLocator serviceLocator = descriptor.getServiceLocator();
    serviceLocator.addConstant(descriptor.getClass().getSimpleName(), descriptor);

    try {
        URI baseURI = new URI("http", null, "0.0.0.0", descriptor.getServletContainer().getPort(),
                descriptor.getServletContext().getContextPath(), null, null);

        SpringBootClientDescriptor clientDescriptor = new SpringBootClientDescriptor(app, testContext, baseURI);
        ServiceLoader<ClientProvider> clientProviderLoader = ServiceLoader.load(ClientProvider.class);
        ArrayList<ClientProvider> clientProviders = Lists.newArrayList(clientProviderLoader);

        checkState(!clientProviders.isEmpty(), "ClientInstance provider not found in the classpath");
        checkState(clientProviders.size() == 1, "Multiple ClientInstance provider found in the classpath. "
                + "Please insure there is only one ClientInstance provider in the classpath.");

        ClientProvider clientProvider = clientProviders.get(0);
        Object context = clientProvider.configuration(clientDescriptor);

        testContext.getConfigMethod(context.getClass()).map(m -> m.getMethod()).ifPresent(m -> {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                try {
                    m.setAccessible(true);
                    m.invoke(testInstance, context);
                } catch (Exception e) {
                    checkState(false, "Call to config method '%s' in test class '%s' failed due to: ",
                            m.getName(), clientDescriptor.getTestClassName(), e.getMessage());
                }

                return null;
            });
        });

        serverInstance = new SpringBootServerInstance(descriptor.getServletContainer(), baseURI);
        serviceLocator.addConstant(serverInstance.getClass().getSimpleName(), serverInstance);

        clientInstance = clientProvider.init(clientDescriptor, context);
        serviceLocator.addConstant(clientInstance.getClass().getSimpleName(), clientInstance);

        TestCaseInstance testCaseInstance = new TestCaseInstance(method.getName(), testInstance);
        serviceLocator.addConstant(testCaseInstance.getTestName(), testCaseInstance);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    SystemTestReifier reifier = new SystemTestReifier(testContext, serviceLocator, testInstance);
    SystemTestCreator creator = new SystemTestCreator(testContext, reifier, serviceLocator);

    if (testContext.getCutDescriptor() != null) {
        creator.cut();
    }

    Set<FieldDescriptor> real = testContext.getFieldDescriptors().values().parallelStream()
            .filter(p -> !p.getInstance().isPresent())
            .filter(p -> p.hasAnnotations(descriptor.getServiceAnnotations().getInjectors())).collect(toSet());

    creator.real(real);

    SystemTestVerifier verifier = new SystemTestVerifier(testContext, LOGGER);
    verifier.wiring();

    Statement statement = methodInvoker(method, testInstance);
    statement = possiblyExpectingExceptions(method, testInstance, statement);
    statement = withBefores(method, testInstance, statement);
    statement = withAfters(method, testInstance, statement);
    statement = withRules(method, testInstance, statement);

    return statement;
}