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:com.qwazr.server.configuration.ServerConfiguration.java

private static String findPublicAddress(final String addressPattern, final String listenAddress)
        throws SocketException {
    if (StringUtils.isEmpty(addressPattern))
        return StringUtils.isEmpty(listenAddress) || DEFAULT_LISTEN_ADDRESS.equals(listenAddress)
                ? getLocalHostAddress()// w ww. j a va  2  s.  co  m
                : listenAddress;
    final ArrayList<String> list = new ArrayList<>();
    findMatchingAddress(addressPattern, list);
    if (list.isEmpty())
        throw new SocketException("Failed in finding a matching public IP address. Pattern: " + addressPattern);
    if (list.size() > 1)
        LOGGER.warning(() -> "Several matching IP adresses where found (" + list.size() + ')');
    return list.get(0);
}

From source file:com.github.chenxiaolong.dualbootpatcher.patcher.PatcherUtils.java

public synchronized static Device[] getDevices(Context context) {
    ThreadUtils.enforceExecutionOnNonMainThread();
    initializePatcher(context);//www.  j  av  a 2s.c  o m

    if (sDevices == null) {
        File path = new File(getTargetDirectory(context) + File.separator + "devices.json");
        try {
            String json = org.apache.commons.io.FileUtils.readFileToString(path, Charsets.UTF_8);

            Device[] devices = Device.newListFromJson(json);
            ArrayList<Device> validDevices = new ArrayList<>();

            if (devices != null) {
                for (Device d : devices) {
                    if (d.validate() == 0) {
                        validDevices.add(d);
                    }
                }
            }

            if (!validDevices.isEmpty()) {
                sDevices = validDevices.toArray(new Device[validDevices.size()]);
            }
        } catch (IOException e) {
            Log.w(TAG, "Failed to read " + path, e);
        }
    }

    return sDevices;
}

From source file:com.qwazr.server.configuration.ServerConfiguration.java

private static String findListenAddress(final String addressPattern) {
    if (StringUtils.isEmpty(addressPattern))
        return DEFAULT_LISTEN_ADDRESS;
    try {/*from   www.j a  v  a  2  s  . c  om*/
        final ArrayList<String> list = new ArrayList<>();
        findMatchingAddress(addressPattern, list);
        return list.isEmpty() ? DEFAULT_LISTEN_ADDRESS : list.get(0);
    } catch (SocketException e) {
        LOGGER.log(Level.WARNING, e,
                () -> "Failed in extracting IP informations. Listen address set to default ("
                        + DEFAULT_LISTEN_ADDRESS + ")");
        return DEFAULT_LISTEN_ADDRESS;
    }
}

From source file:gov.usgs.anss.query.MultiplexedMSOutputer.java

/**
 * This does the hard work of sorting - called as a shutdown hook.
 * TODO: consider recursion./*w  ww  .ja v a 2 s  .  c om*/
 * @param outputName name for the output file.
 * @param files list of MiniSEED files to multiplex.
 * @param cleanup flag indicating whether to cleanup after ourselves or not.
 * @throws IOException
 */
public static void multiplexFiles(String outputName, List<File> files, boolean cleanup, boolean allowEmpty)
        throws IOException {
    ArrayList<File> cleanupFiles = new ArrayList<File>(files);
    ArrayList<File> moreFiles = new ArrayList<File>();

    File outputFile = new File(outputName);
    File tempOutputFile = new File(outputName + ".tmp");

    do {
        // This checks if we're in a subsequent (i.e. not the first) iteration and if there are any more files to process...?
        if (!moreFiles.isEmpty()) {
            logger.info("more files left to multiplex...");
            FileUtils.deleteQuietly(tempOutputFile);
            FileUtils.moveFile(outputFile, tempOutputFile);

            cleanupFiles.add(tempOutputFile);
            moreFiles.add(tempOutputFile);
            files = moreFiles;
            moreFiles = new ArrayList<File>();
        }

        logger.log(Level.FINE, "Multiplexing blocks from {0} temp files to {1}",
                new Object[] { files.size(), outputName });
        BufferedOutputStream out = new BufferedOutputStream(FileUtils.openOutputStream(outputFile));

        // The hard part, sorting the temp files...
        TreeMap<MiniSeed, FileInputStream> blks = new TreeMap<MiniSeed, FileInputStream>(
                new MiniSeedTimeOnlyComparator());
        // Prime the TreeMap
        logger.log(Level.FINEST, "Priming the TreeMap with files: {0}", files);
        for (File file : files) {
            logger.log(Level.INFO, "Reading first block from {0}", file.toString());
            try {
                FileInputStream fs = FileUtils.openInputStream(file);
                MiniSeed ms = getNextValidMiniSeed(fs, allowEmpty);
                if (ms != null) {
                    blks.put(ms, fs);
                } else {
                    logger.log(Level.WARNING, "Failed to read valid MiniSEED block from {0}", file.toString());
                }
            } catch (IOException ex) {
                // Catch "Too many open files" i.e. hitting ulimit, throw anything else.
                if (ex.getMessage().contains("Too many open files")) {
                    logger.log(Level.INFO, "Too many open files - {0} deferred.", file.toString());
                    moreFiles.add(file);
                } else
                    throw ex;
            }
        }

        while (!blks.isEmpty()) {
            MiniSeed next = blks.firstKey();
            out.write(next.getBuf(), 0, next.getBlockSize());

            FileInputStream fs = blks.remove(next);
            next = getNextValidMiniSeed(fs, allowEmpty);
            if (next != null) {
                blks.put(next, fs);
            } else {
                fs.close();
            }
        }

        out.close();
    } while (!moreFiles.isEmpty());

    if (cleanup) {
        logger.log(Level.INFO, "Cleaning up...");
        for (File file : cleanupFiles) {
            FileUtils.deleteQuietly(file);
        }
    }
}

From source file:fredboat.command.music.control.SelectCommand.java

static void select(CommandContext context) {
    Member invoker = context.invoker;
    GuildPlayer player = PlayerRegistry.getOrCreate(context.guild);
    VideoSelection selection = VideoSelection.get(invoker);
    if (selection == null) {
        context.reply(context.i18n("selectSelectionNotGiven"));
        return;//from   w ww .  ja v  a  2  s.  c o  m
    }

    try {
        //Step 1: Parse the issued command for numbers

        // LinkedHashSet to handle order of choices + duplicates
        LinkedHashSet<Integer> requestChoices = new LinkedHashSet<>();

        // Combine all args and the command trigger. if the trigger is not a number it will be sanitized away
        String commandOptions = (context.trigger + " " + context.rawArgs).trim();
        String sanitizedQuery = sanitizeQueryForMultiSelect(commandOptions).trim();

        if (StringUtils.isNumeric(commandOptions)) {
            requestChoices.add(Integer.valueOf(commandOptions));
        } else if (TextUtils.isSplitSelect(sanitizedQuery)) {
            // Remove all non comma or number characters
            String[] querySplit = sanitizedQuery.split(",|\\s");

            for (String value : querySplit) {
                if (StringUtils.isNumeric(value)) {
                    requestChoices.add(Integer.valueOf(value));
                }
            }
        }

        //Step 2: Use only valid numbers (usually 1-5)

        ArrayList<Integer> validChoices = new ArrayList<>();
        // Only include valid values which are 1 to <size> of the offered selection
        for (Integer value : requestChoices) {
            if (1 <= value && value <= selection.choices.size()) {
                validChoices.add(value);
            }
        }

        //Step 3: Make a selection based on the order of the valid numbers

        // any valid choices at all?
        if (validChoices.isEmpty()) {
            throw new NumberFormatException();
        } else {
            AudioTrack[] selectedTracks = new AudioTrack[validChoices.size()];
            StringBuilder outputMsgBuilder = new StringBuilder();

            for (int i = 0; i < validChoices.size(); i++) {
                selectedTracks[i] = selection.choices.get(validChoices.get(i) - 1);

                String msg = context.i18nFormat("selectSuccess", validChoices.get(i),
                        selectedTracks[i].getInfo().title,
                        TextUtils.formatTime(selectedTracks[0].getInfo().length));
                if (i < validChoices.size()) {
                    outputMsgBuilder.append("\n");
                }
                outputMsgBuilder.append(msg);

                player.queue(new AudioTrackContext(selectedTracks[i], invoker));
            }

            VideoSelection.remove(invoker);
            TextChannel tc = FredBoat.getTextChannelById(selection.channelId);
            if (tc != null) {
                CentralMessaging.editMessage(tc, selection.outMsgId,
                        CentralMessaging.from(outputMsgBuilder.toString()));
            }

            player.setPause(false);
            context.deleteMessage();
        }
    } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
        context.reply(context.i18nFormat("selectInterval", selection.choices.size()));
    }
}

From source file:edu.gsgp.utils.Utils.java

/**
 * Generates an array with a number of folds defined by the user. Each fold
 * contains dataset.size() / numFolds instances.
 * @param numFolds Number of folds/*from w  w w  .  j  a v  a2s.c o m*/
 * @param dataset Input datase
 * @param rnd Random number generator
 * @return An array of folds
 */
public static Dataset[] getFoldSampling(int numFolds, Dataset dataset, MersenneTwister rnd) {
    Dataset[] folds = new Dataset[numFolds];
    ArrayList<Instance> dataCopy = dataset.softClone();
    int foldIndex = 0;
    if (rnd == null) {
        Iterator<Instance> it = dataCopy.iterator();
        while (it.hasNext()) {
            if (folds[foldIndex] == null)
                folds[foldIndex] = new Dataset();
            folds[foldIndex].add(it.next());
            it.remove();
            if (foldIndex < numFolds - 1)
                foldIndex++;
            else
                foldIndex = 0;
        }
    } else {
        while (!dataCopy.isEmpty()) {
            if (folds[foldIndex] == null)
                folds[foldIndex] = new Dataset();
            folds[foldIndex].add(dataCopy.remove(rnd.nextInt(dataCopy.size())));
            if (foldIndex < numFolds - 1)
                foldIndex++;
            else
                foldIndex = 0;
        }
    }
    return folds;
}

From source file:net.opentsdb.meta.UIDMeta.java

/**
 * Verifies the UID object exists, then attempts to fetch the meta from 
 * storage and if not found, returns a default object.
 * <p>/*from  w  ww.ja va  2s .c om*/
 * The reason for returning a default object (with the type, uid and name set)
 * is due to users who may have just enabled meta data or have upgraded; we 
 * want to return valid data. If they modify the entry, it will write to 
 * storage. You can tell it's a default if the {@code created} value is 0. If
 * the meta was generated at UID assignment or updated by the meta sync CLI
 * command, it will have a valid created timestamp.
 * @param tsdb The TSDB to use for storage access
 * @param type The type of UID to fetch
 * @param uid The ID of the meta to fetch
 * @return A UIDMeta from storage or a default
 * @throws HBaseException if there was an issue fetching
 * @throws NoSuchUniqueId If the UID does not exist
 */
public static Deferred<UIDMeta> getUIDMeta(final TSDB tsdb, final UniqueIdType type, final byte[] uid) {

    /**
     * Callback used to verify that the UID to name mapping exists. Uses the TSD
     * for verification so the name may be cached. If the name does not exist
     * it will throw a NoSuchUniqueId and the meta data will not be returned. 
     * This helps in case the user deletes a UID but the meta data is still 
     * stored. The fsck utility can be used later to cleanup orphaned objects.
     */
    class NameCB implements Callback<Deferred<UIDMeta>, String> {

        /**
         * Called after verifying that the name mapping exists
         * @return The results of {@link #FetchMetaCB}
         */
        @Override
        public Deferred<UIDMeta> call(final String name) throws Exception {

            /**
             * Inner class called to retrieve the meta data after verifying that the
             * name mapping exists. It requires the name to set the default, hence
             * the reason it's nested.
             */
            class FetchMetaCB implements Callback<Deferred<UIDMeta>, ArrayList<KeyValue>> {

                /**
                 * Called to parse the response of our storage GET call after 
                 * verification
                 * @return The stored UIDMeta or a default object if the meta data
                 * did not exist 
                 */
                @Override
                public Deferred<UIDMeta> call(ArrayList<KeyValue> row) throws Exception {

                    if (row == null || row.isEmpty()) {
                        // return the default
                        final UIDMeta meta = new UIDMeta();
                        meta.uid = UniqueId.uidToString(uid);
                        meta.type = type;
                        meta.name = name;
                        return Deferred.fromResult(meta);
                    }
                    final UIDMeta meta = JSON.parseToObject(row.get(0).value(), UIDMeta.class);

                    // overwrite the name and UID
                    meta.name = name;
                    meta.uid = UniqueId.uidToString(uid);

                    // fix missing types
                    if (meta.type == null) {
                        final String qualifier = new String(row.get(0).qualifier(), CHARSET);
                        meta.type = UniqueId
                                .stringToUniqueIdType(qualifier.substring(0, qualifier.indexOf("_meta")));
                    }
                    meta.initializeChangedMap();
                    return Deferred.fromResult(meta);
                }

            }

            final GetRequest get = new GetRequest(tsdb.uidTable(), uid);
            get.family(FAMILY);
            get.qualifier((type.toString().toLowerCase() + "_meta").getBytes(CHARSET));
            return tsdb.getClient().get(get).addCallbackDeferring(new FetchMetaCB());
        }
    }

    // verify that the UID is still in the map before fetching from storage
    return tsdb.getUidName(type, uid).addCallbackDeferring(new NameCB());
}

From source file:org.apache.taverna.activities.rest.HTTPRequestHandler.java

/**
 * TODO - REDIRECTION output:: if there was no redirection, should just show
 * the actual initial URL?/*ww w . j a  v  a2s  . c om*/
 *
 * @param httpRequest
 * @param acceptHeaderValue
 */
private static HTTPRequestResponse performHTTPRequest(ClientConnectionManager connectionManager,
        HttpRequestBase httpRequest, RESTActivityConfigurationBean configBean,
        Map<String, String> urlParameters, CredentialsProvider credentialsProvider) {
    // headers are set identically for all HTTP methods, therefore can do
    // centrally - here

    // If the user wants to set MIME type for the 'Accepts' header
    String acceptsHeaderValue = configBean.getAcceptsHeaderValue();
    if ((acceptsHeaderValue != null) && !acceptsHeaderValue.isEmpty()) {
        httpRequest.setHeader(ACCEPT_HEADER_NAME, URISignatureHandler.generateCompleteURI(acceptsHeaderValue,
                urlParameters, configBean.getEscapeParameters()));
    }

    // See if user wanted to set any other HTTP headers
    ArrayList<ArrayList<String>> otherHTTPHeaders = configBean.getOtherHTTPHeaders();
    if (!otherHTTPHeaders.isEmpty())
        for (ArrayList<String> httpHeaderNameValuePair : otherHTTPHeaders)
            if (httpHeaderNameValuePair.get(0) != null && !httpHeaderNameValuePair.get(0).isEmpty()) {
                String headerParameterizedValue = httpHeaderNameValuePair.get(1);
                String headerValue = URISignatureHandler.generateCompleteURI(headerParameterizedValue,
                        urlParameters, configBean.getEscapeParameters());
                httpRequest.setHeader(httpHeaderNameValuePair.get(0), headerValue);
            }

    try {
        HTTPRequestResponse requestResponse = new HTTPRequestResponse();
        DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, null);
        ((DefaultHttpClient) httpClient).setCredentialsProvider(credentialsProvider);
        HttpContext localContext = new BasicHttpContext();

        // Set the proxy settings, if any
        if (System.getProperty(PROXY_HOST) != null && !System.getProperty(PROXY_HOST).isEmpty()) {
            // Instruct HttpClient to use the standard
            // JRE proxy selector to obtain proxy information
            ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                    httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
            httpClient.setRoutePlanner(routePlanner);
            // Do we need to authenticate the user to the proxy?
            if (System.getProperty(PROXY_USERNAME) != null && !System.getProperty(PROXY_USERNAME).isEmpty())
                // Add the proxy username and password to the list of
                // credentials
                httpClient.getCredentialsProvider().setCredentials(
                        new AuthScope(System.getProperty(PROXY_HOST),
                                Integer.parseInt(System.getProperty(PROXY_PORT))),
                        new UsernamePasswordCredentials(System.getProperty(PROXY_USERNAME),
                                System.getProperty(PROXY_PASSWORD)));
        }

        // execute the request
        HttpResponse response = httpClient.execute(httpRequest, localContext);

        // record response code
        requestResponse.setStatusCode(response.getStatusLine().getStatusCode());
        requestResponse.setReasonPhrase(response.getStatusLine().getReasonPhrase());

        // record header values for Content-Type of the response
        requestResponse.setResponseContentTypes(response.getHeaders(CONTENT_TYPE_HEADER_NAME));

        // track where did the final redirect go to (if there was any)
        HttpHost targetHost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest targetRequest = (HttpUriRequest) localContext
                .getAttribute(ExecutionContext.HTTP_REQUEST);
        requestResponse.setRedirectionURL("" + targetHost + targetRequest.getURI());
        requestResponse.setRedirectionHTTPMethod(targetRequest.getMethod());
        requestResponse.setHeaders(response.getAllHeaders());

        /* read and store response body
         (check there is some content - negative length of content means
         unknown length;
         zero definitely means no content...)*/
        // TODO - make sure that this test is sufficient to determine if
        // there is no response entity
        if (response.getEntity() != null && response.getEntity().getContentLength() != 0)
            requestResponse.setResponseBody(readResponseBody(response.getEntity()));

        // release resources (e.g. connection pool, etc)
        httpClient.getConnectionManager().shutdown();
        return requestResponse;
    } catch (Exception ex) {
        return new HTTPRequestResponse(ex);
    }
}

From source file:axiom.util.Logging.java

/**
 * Rotate log files on all registered logs
 *///  w  ww.ja  va 2  s .  c o m
static void rotateLogs() {
    int nloggers = loggers.size();
    ArrayList files = new ArrayList(nloggers);

    for (int i = nloggers - 1; i >= 0; i--) {
        FileLogger log = (FileLogger) loggers.get(i);

        try {
            File file = log.rotateLogFile();
            if (file != null) {
                files.add(file);
            }
        } catch (IOException io) {
            System.err.println("Error rotating log " + log.getName() + ": " + io.toString());
        }
    }

    if (!files.isEmpty()) {
        new FileLogger.GZipper(files).start();
    }
}

From source file:levelBuilder.DialogMaker.java

/**
 * Saves graph to file./*w w w  . j  a  v a 2  s  . c o  m*/
 */
private static void saveGraph() {
    //Checks for errors
    ArrayList<String> errorList = new ArrayList<String>();
    errorList = dg.check();
    if (errorList.isEmpty()) {
        //Save popup.
        String filePath = null;
        File savesFolder = new File(saveDir);
        if (!savesFolder.exists())
            savesFolder.mkdir();
        String[] saveNames = new String[savesFolder.list(fileFilter).length + 1];
        for (int i = 0; i < saveNames.length - 1; i++) {
            saveNames[i] = savesFolder.list(fileFilter)[i];
        }
        saveNames[saveNames.length - 1] = "New File";

        if (saveNames.length > 0) {
            saveName = (String) JOptionPane.showInputDialog(null, "Choose file to overwrite, or a new file",
                    "Choose!", JOptionPane.PLAIN_MESSAGE, null, saveNames, saveName);
            if (saveName == "New File") {
                filePath = JOptionPane.showInputDialog(null, "New file name", "Write!",
                        JOptionPane.PLAIN_MESSAGE);
                filePath = saveDir + filePath + ".xml";
            } else if (saveName == null) {
                return;
            } else {
                filePath = saveDir + saveName;
            }

            //            //Saves position of each node.
            //            for (DialogNode n : nodeMap.values()) {
            //               n.setX(((AbstractLayout<DialogNode, Double>) layout).getX(n));
            //               n.setY(((AbstractLayout<DialogNode, Double>) layout).getY(n));
            //            }   

            //Saves graph
            dg.save(filePath);
        }
    }
    //Display errors
    else {
        JPanel panel = new JPanel(new GridLayout(0, 1, 0, 0));
        for (String error : errorList)
            panel.add(new JLabel(error));
        JOptionPane.showMessageDialog(null, panel, "Errors. Fix these to continue.", JOptionPane.PLAIN_MESSAGE);
    }
}