Example usage for java.util LinkedList addLast

List of usage examples for java.util LinkedList addLast

Introduction

In this page you can find the example usage for java.util LinkedList addLast.

Prototype

public void addLast(E e) 

Source Link

Document

Appends the specified element to the end of this list.

Usage

From source file:org.apache.rocketmq.example.benchmark.Consumer.java

public static void main(String[] args) throws MQClientException, IOException {
    Options options = ServerUtil.buildCommandlineOptions(new Options());
    CommandLine commandLine = ServerUtil.parseCmdLine("benchmarkConsumer", args,
            buildCommandlineOptions(options), new PosixParser());
    if (null == commandLine) {
        System.exit(-1);/*from   w  ww.  j a v  a2s.c o m*/
    }

    final String topic = commandLine.hasOption('t') ? commandLine.getOptionValue('t').trim() : "BenchmarkTest";
    final String groupPrefix = commandLine.hasOption('g') ? commandLine.getOptionValue('g').trim()
            : "benchmark_consumer";
    final String isPrefixEnable = commandLine.hasOption('p') ? commandLine.getOptionValue('p').trim() : "true";
    final String filterType = commandLine.hasOption('f') ? commandLine.getOptionValue('f').trim() : null;
    final String expression = commandLine.hasOption('e') ? commandLine.getOptionValue('e').trim() : null;
    String group = groupPrefix;
    if (Boolean.parseBoolean(isPrefixEnable)) {
        group = groupPrefix + "_" + Long.toString(System.currentTimeMillis() % 100);
    }

    System.out.printf("topic: %s, group: %s, prefix: %s, filterType: %s, expression: %s%n", topic, group,
            isPrefixEnable, filterType, expression);

    final StatsBenchmarkConsumer statsBenchmarkConsumer = new StatsBenchmarkConsumer();

    final Timer timer = new Timer("BenchmarkTimerThread", true);

    final LinkedList<Long[]> snapshotList = new LinkedList<Long[]>();

    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            snapshotList.addLast(statsBenchmarkConsumer.createSnapshot());
            if (snapshotList.size() > 10) {
                snapshotList.removeFirst();
            }
        }
    }, 1000, 1000);

    timer.scheduleAtFixedRate(new TimerTask() {
        private void printStats() {
            if (snapshotList.size() >= 10) {
                Long[] begin = snapshotList.getFirst();
                Long[] end = snapshotList.getLast();

                final long consumeTps = (long) (((end[1] - begin[1]) / (double) (end[0] - begin[0])) * 1000L);
                final double averageB2CRT = (end[2] - begin[2]) / (double) (end[1] - begin[1]);
                final double averageS2CRT = (end[3] - begin[3]) / (double) (end[1] - begin[1]);

                System.out.printf(
                        "Consume TPS: %d Average(B2C) RT: %7.3f Average(S2C) RT: %7.3f MAX(B2C) RT: %d MAX(S2C) RT: %d%n",
                        consumeTps, averageB2CRT, averageS2CRT, end[4], end[5]);
            }
        }

        @Override
        public void run() {
            try {
                this.printStats();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, 10000, 10000);

    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(group);
    consumer.setInstanceName(Long.toString(System.currentTimeMillis()));

    if (filterType == null || expression == null) {
        consumer.subscribe(topic, "*");
    } else {
        if (ExpressionType.TAG.equals(filterType)) {
            String expr = MixAll.file2String(expression);
            System.out.printf("Expression: %s%n", expr);
            consumer.subscribe(topic, MessageSelector.byTag(expr));
        } else if (ExpressionType.SQL92.equals(filterType)) {
            String expr = MixAll.file2String(expression);
            System.out.printf("Expression: %s%n", expr);
            consumer.subscribe(topic, MessageSelector.bySql(expr));
        } else {
            throw new IllegalArgumentException("Not support filter type! " + filterType);
        }
    }

    consumer.registerMessageListener(new MessageListenerConcurrently() {
        @Override
        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                ConsumeConcurrentlyContext context) {
            MessageExt msg = msgs.get(0);
            long now = System.currentTimeMillis();

            statsBenchmarkConsumer.getReceiveMessageTotalCount().incrementAndGet();

            long born2ConsumerRT = now - msg.getBornTimestamp();
            statsBenchmarkConsumer.getBorn2ConsumerTotalRT().addAndGet(born2ConsumerRT);

            long store2ConsumerRT = now - msg.getStoreTimestamp();
            statsBenchmarkConsumer.getStore2ConsumerTotalRT().addAndGet(store2ConsumerRT);

            compareAndSetMax(statsBenchmarkConsumer.getBorn2ConsumerMaxRT(), born2ConsumerRT);

            compareAndSetMax(statsBenchmarkConsumer.getStore2ConsumerMaxRT(), store2ConsumerRT);

            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
    });

    consumer.start();

    System.out.printf("Consumer Started.%n");
}

From source file:com.damon.rocketmq.example.benchmark.Producer.java

public static void main(String[] args) throws MQClientException, UnsupportedEncodingException {

    Options options = ServerUtil.buildCommandlineOptions(new Options());
    CommandLine commandLine = ServerUtil.parseCmdLine("benchmarkProducer", args,
            buildCommandlineOptions(options), new PosixParser());
    if (null == commandLine) {
        System.exit(-1);//  ww w .j  a  va 2s  . c  o m
    }

    final String topic = commandLine.hasOption('t') ? commandLine.getOptionValue('t').trim() : "BenchmarkTest";
    final int threadCount = commandLine.hasOption('w') ? Integer.parseInt(commandLine.getOptionValue('w')) : 64;
    final int messageSize = commandLine.hasOption('s') ? Integer.parseInt(commandLine.getOptionValue('s'))
            : 128;
    final boolean keyEnable = commandLine.hasOption('k')
            && Boolean.parseBoolean(commandLine.getOptionValue('k'));

    System.out.printf("topic %s threadCount %d messageSize %d keyEnable %s%n", topic, threadCount, messageSize,
            keyEnable);

    final Logger log = ClientLogger.getLog();

    final Message msg = buildMessage(messageSize, topic);

    final ExecutorService sendThreadPool = Executors.newFixedThreadPool(threadCount);

    final StatsBenchmarkProducer statsBenchmark = new StatsBenchmarkProducer();

    final Timer timer = new Timer("BenchmarkTimerThread", true);

    final LinkedList<Long[]> snapshotList = new LinkedList<Long[]>();

    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            snapshotList.addLast(statsBenchmark.createSnapshot());
            if (snapshotList.size() > 10) {
                snapshotList.removeFirst();
            }
        }
    }, 1000, 1000);

    timer.scheduleAtFixedRate(new TimerTask() {
        private void printStats() {
            if (snapshotList.size() >= 10) {
                Long[] begin = snapshotList.getFirst();
                Long[] end = snapshotList.getLast();

                final long sendTps = (long) (((end[3] - begin[3]) / (double) (end[0] - begin[0])) * 1000L);
                final double averageRT = (end[5] - begin[5]) / (double) (end[3] - begin[3]);

                System.out.printf(
                        "Send TPS: %d Max RT: %d Average RT: %7.3f Send Failed: %d Response Failed: %d%n",
                        sendTps, statsBenchmark.getSendMessageMaxRT().get(), averageRT, end[2], end[4]);
            }
        }

        @Override
        public void run() {
            try {
                this.printStats();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, 10000, 10000);

    final DefaultMQProducer producer = new DefaultMQProducer("benchmark_producer");
    producer.setInstanceName(Long.toString(System.currentTimeMillis()));

    if (commandLine.hasOption('n')) {
        String ns = commandLine.getOptionValue('n');
        producer.setNamesrvAddr(ns);
    }

    producer.setCompressMsgBodyOverHowmuch(Integer.MAX_VALUE);

    producer.start();

    for (int i = 0; i < threadCount; i++) {
        sendThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        final long beginTimestamp = System.currentTimeMillis();
                        if (keyEnable) {
                            msg.setKeys(String.valueOf(beginTimestamp / 1000));
                        }
                        producer.send(msg);
                        statsBenchmark.getSendRequestSuccessCount().incrementAndGet();
                        statsBenchmark.getReceiveResponseSuccessCount().incrementAndGet();
                        final long currentRT = System.currentTimeMillis() - beginTimestamp;
                        statsBenchmark.getSendMessageSuccessTimeTotal().addAndGet(currentRT);
                        long prevMaxRT = statsBenchmark.getSendMessageMaxRT().get();
                        while (currentRT > prevMaxRT) {
                            boolean updated = statsBenchmark.getSendMessageMaxRT().compareAndSet(prevMaxRT,
                                    currentRT);
                            if (updated)
                                break;

                            prevMaxRT = statsBenchmark.getSendMessageMaxRT().get();
                        }
                    } catch (RemotingException e) {
                        statsBenchmark.getSendRequestFailedCount().incrementAndGet();
                        log.error("[BENCHMARK_PRODUCER] Send Exception", e);

                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException ignored) {
                        }
                    } catch (InterruptedException e) {
                        statsBenchmark.getSendRequestFailedCount().incrementAndGet();
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e1) {
                        }
                    } catch (MQClientException e) {
                        statsBenchmark.getSendRequestFailedCount().incrementAndGet();
                        log.error("[BENCHMARK_PRODUCER] Send Exception", e);
                    } catch (MQBrokerException e) {
                        statsBenchmark.getReceiveResponseFailedCount().incrementAndGet();
                        log.error("[BENCHMARK_PRODUCER] Send Exception", e);
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException ignored) {
                        }
                    }
                }
            }
        });
    }
}

From source file:com.alibaba.rocketmq.example.benchmark.Producer.java

public static void main(String[] args) throws MQClientException, UnsupportedEncodingException {

    Options options = ServerUtil.buildCommandlineOptions(new Options());
    CommandLine commandLine = ServerUtil.parseCmdLine("producer", args, buildCommandlineOptions(options),
            new PosixParser());
    if (null == commandLine) {
        System.exit(-1);//from www  .  j  a  va  2s .  c  o m
    }

    final int threadCount = commandLine.hasOption('t') ? Integer.parseInt(commandLine.getOptionValue('t')) : 64;
    final int messageSize = commandLine.hasOption('s') ? Integer.parseInt(commandLine.getOptionValue('s'))
            : 128;
    final boolean keyEnable = commandLine.hasOption('k') ? Boolean.parseBoolean(commandLine.getOptionValue('k'))
            : false;

    System.out.printf("threadCount %d messageSize %d keyEnable %s%n", threadCount, messageSize, keyEnable);

    final Logger log = ClientLogger.getLog();

    final Message msg = buildMessage(messageSize);

    final ExecutorService sendThreadPool = Executors.newFixedThreadPool(threadCount);

    final StatsBenchmarkProducer statsBenchmark = new StatsBenchmarkProducer();

    final Timer timer = new Timer("BenchmarkTimerThread", true);

    final LinkedList<Long[]> snapshotList = new LinkedList<Long[]>();

    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            snapshotList.addLast(statsBenchmark.createSnapshot());
            if (snapshotList.size() > 10) {
                snapshotList.removeFirst();
            }
        }
    }, 1000, 1000);

    timer.scheduleAtFixedRate(new TimerTask() {
        private void printStats() {
            if (snapshotList.size() >= 10) {
                Long[] begin = snapshotList.getFirst();
                Long[] end = snapshotList.getLast();

                final long sendTps = (long) (((end[3] - begin[3]) / (double) (end[0] - begin[0])) * 1000L);
                final double averageRT = ((end[5] - begin[5]) / (double) (end[3] - begin[3]));

                System.out.printf(
                        "Send TPS: %d Max RT: %d Average RT: %7.3f Send Failed: %d Response Failed: %d%n"//
                , sendTps//
                , statsBenchmark.getSendMessageMaxRT().get()//
                , averageRT//
                , end[2]//
                , end[4]//
                );
            }
        }

        @Override
        public void run() {
            try {
                this.printStats();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, 10000, 10000);

    final DefaultMQProducer producer = new DefaultMQProducer("benchmark_producer");
    producer.setInstanceName(Long.toString(System.currentTimeMillis()));

    if (commandLine.hasOption('n')) {
        String ns = commandLine.getOptionValue('n');
        producer.setNamesrvAddr(ns);
    }

    producer.setCompressMsgBodyOverHowmuch(Integer.MAX_VALUE);

    producer.start();

    for (int i = 0; i < threadCount; i++) {
        sendThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        final long beginTimestamp = System.currentTimeMillis();
                        if (keyEnable) {
                            msg.setKeys(String.valueOf(beginTimestamp / 1000));
                        }
                        producer.send(msg);
                        statsBenchmark.getSendRequestSuccessCount().incrementAndGet();
                        statsBenchmark.getReceiveResponseSuccessCount().incrementAndGet();
                        final long currentRT = System.currentTimeMillis() - beginTimestamp;
                        statsBenchmark.getSendMessageSuccessTimeTotal().addAndGet(currentRT);
                        long prevMaxRT = statsBenchmark.getSendMessageMaxRT().get();
                        while (currentRT > prevMaxRT) {
                            boolean updated = statsBenchmark.getSendMessageMaxRT().compareAndSet(prevMaxRT,
                                    currentRT);
                            if (updated)
                                break;

                            prevMaxRT = statsBenchmark.getSendMessageMaxRT().get();
                        }
                    } catch (RemotingException e) {
                        statsBenchmark.getSendRequestFailedCount().incrementAndGet();
                        log.error("[BENCHMARK_PRODUCER] Send Exception", e);

                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e1) {
                        }
                    } catch (InterruptedException e) {
                        statsBenchmark.getSendRequestFailedCount().incrementAndGet();
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e1) {
                        }
                    } catch (MQClientException e) {
                        statsBenchmark.getSendRequestFailedCount().incrementAndGet();
                        log.error("[BENCHMARK_PRODUCER] Send Exception", e);
                    } catch (MQBrokerException e) {
                        statsBenchmark.getReceiveResponseFailedCount().incrementAndGet();
                        log.error("[BENCHMARK_PRODUCER] Send Exception", e);
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e1) {
                        }
                    }
                }
            }
        });
    }
}

From source file:org.dbpedia.spotlight.evaluation.SpotterMemoryEvaluator.java

public static void main(String[] args) throws IOException, JSONException, ConfigurationException,
        InitializationException, org.json.JSONException, SpottingException {

    File dictionary = new File(
            "/Users/jodaiber/Desktop/lrec_2012_spotting/surface_forms-Wikipedia-TitRedDis.thresh3.spotterDictionary");

    Spotter spotter = null;/*from   w w w  .jav  a2 s  .  c  o m*/

    //
    if (args.length == 0) {
        LOG.error("server.properties is requested to continue...");
        return;
    }

    SpotlightConfiguration configuration = new SpotlightConfiguration(args[0]);

    int spotterNr = 0;

    switch (spotterNr) {
    case 0: {
        String openNLPDir = "/Users/jodaiber/Desktop/DBpedia/";
        SurfaceFormDictionary sfDictProbThresh3 = ExactSurfaceFormDictionary.fromLingPipeDictionary(dictionary,
                false);
        System.out.println("Dictionary size: " + sfDictProbThresh3.size());
        File stopwordsFile = new File(openNLPDir + "stopwords.txt");
        spotter = OpenNLPChunkerSpotter.fromDir(openNLPDir, configuration.getI18nLanguageCode(),
                sfDictProbThresh3, stopwordsFile);
        break;
    }
    case 1: {
        spotter = new LingPipeSpotter(dictionary, configuration.getAnalyzer());
        break;
    }
    }

    System.out.println("Using Spotter " + spotter.getName());

    System.out.println("Running GC.");
    System.gc();
    System.gc();
    System.gc();
    System.gc();

    int i = 0;

    LinkedList<Long> consumption = new LinkedList<Long>();

    for (File textFile : new File("/data/spotlight/csaw/original/crawledDocs").listFiles()) {

        if (!textFile.getName().endsWith(".txt"))
            continue;

        i++;
        if (i == 100)
            break;

        spotter.extract(new Text(new Scanner(textFile).useDelimiter("\\A").next()));

        consumption.addLast(
                (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (1024 * 1024));
        System.out.println("Memory consumption: " + consumption.getLast());
    }

    long total = 0;
    for (long step : consumption) {
        total += step;
    }

    System.out.println("Mean consumption: " + (total / consumption.size()));

}

From source file:org.apache.rocketmq.example.benchmark.Producer.java

public static void main(String[] args) throws MQClientException, UnsupportedEncodingException {

    Options options = ServerUtil.buildCommandlineOptions(new Options());
    CommandLine commandLine = ServerUtil.parseCmdLine("benchmarkProducer", args,
            buildCommandlineOptions(options), new PosixParser());
    if (null == commandLine) {
        System.exit(-1);/* w ww. jav  a  2 s  .c o  m*/
    }

    final String topic = commandLine.hasOption('t') ? commandLine.getOptionValue('t').trim() : "BenchmarkTest";
    final int threadCount = commandLine.hasOption('w') ? Integer.parseInt(commandLine.getOptionValue('w')) : 64;
    final int messageSize = commandLine.hasOption('s') ? Integer.parseInt(commandLine.getOptionValue('s'))
            : 128;
    final boolean keyEnable = commandLine.hasOption('k')
            && Boolean.parseBoolean(commandLine.getOptionValue('k'));
    final int propertySize = commandLine.hasOption('p') ? Integer.parseInt(commandLine.getOptionValue('p')) : 0;

    System.out.printf("topic %s threadCount %d messageSize %d keyEnable %s%n", topic, threadCount, messageSize,
            keyEnable);

    final InternalLogger log = ClientLogger.getLog();

    final ExecutorService sendThreadPool = Executors.newFixedThreadPool(threadCount);

    final StatsBenchmarkProducer statsBenchmark = new StatsBenchmarkProducer();

    final Timer timer = new Timer("BenchmarkTimerThread", true);

    final LinkedList<Long[]> snapshotList = new LinkedList<Long[]>();

    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            snapshotList.addLast(statsBenchmark.createSnapshot());
            if (snapshotList.size() > 10) {
                snapshotList.removeFirst();
            }
        }
    }, 1000, 1000);

    timer.scheduleAtFixedRate(new TimerTask() {
        private void printStats() {
            if (snapshotList.size() >= 10) {
                Long[] begin = snapshotList.getFirst();
                Long[] end = snapshotList.getLast();

                final long sendTps = (long) (((end[3] - begin[3]) / (double) (end[0] - begin[0])) * 1000L);
                final double averageRT = (end[5] - begin[5]) / (double) (end[3] - begin[3]);

                System.out.printf(
                        "Send TPS: %d Max RT: %d Average RT: %7.3f Send Failed: %d Response Failed: %d%n",
                        sendTps, statsBenchmark.getSendMessageMaxRT().get(), averageRT, end[2], end[4]);
            }
        }

        @Override
        public void run() {
            try {
                this.printStats();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, 10000, 10000);

    final DefaultMQProducer producer = new DefaultMQProducer("benchmark_producer");
    producer.setInstanceName(Long.toString(System.currentTimeMillis()));

    if (commandLine.hasOption('n')) {
        String ns = commandLine.getOptionValue('n');
        producer.setNamesrvAddr(ns);
    }

    producer.setCompressMsgBodyOverHowmuch(Integer.MAX_VALUE);

    producer.start();

    for (int i = 0; i < threadCount; i++) {
        sendThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        final Message msg;
                        try {
                            msg = buildMessage(messageSize, topic);
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                            return;
                        }
                        final long beginTimestamp = System.currentTimeMillis();
                        if (keyEnable) {
                            msg.setKeys(String.valueOf(beginTimestamp / 1000));
                        }
                        if (propertySize > 0) {
                            if (msg.getProperties() != null) {
                                msg.getProperties().clear();
                            }
                            int i = 0;
                            int startValue = (new Random(System.currentTimeMillis())).nextInt(100);
                            int size = 0;
                            while (true) {
                                String prop1 = "prop" + i, prop1V = "hello" + startValue;
                                String prop2 = "prop" + (i + 1), prop2V = String.valueOf(startValue);
                                msg.putUserProperty(prop1, prop1V);
                                msg.putUserProperty(prop2, prop2V);
                                size += prop1.length() + prop2.length() + prop1V.length() + prop2V.length();
                                if (size > propertySize) {
                                    break;
                                }
                                i += 2;
                                startValue += 2;
                            }
                        }
                        producer.send(msg);
                        statsBenchmark.getSendRequestSuccessCount().incrementAndGet();
                        statsBenchmark.getReceiveResponseSuccessCount().incrementAndGet();
                        final long currentRT = System.currentTimeMillis() - beginTimestamp;
                        statsBenchmark.getSendMessageSuccessTimeTotal().addAndGet(currentRT);
                        long prevMaxRT = statsBenchmark.getSendMessageMaxRT().get();
                        while (currentRT > prevMaxRT) {
                            boolean updated = statsBenchmark.getSendMessageMaxRT().compareAndSet(prevMaxRT,
                                    currentRT);
                            if (updated)
                                break;

                            prevMaxRT = statsBenchmark.getSendMessageMaxRT().get();
                        }
                    } catch (RemotingException e) {
                        statsBenchmark.getSendRequestFailedCount().incrementAndGet();
                        log.error("[BENCHMARK_PRODUCER] Send Exception", e);

                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException ignored) {
                        }
                    } catch (InterruptedException e) {
                        statsBenchmark.getSendRequestFailedCount().incrementAndGet();
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e1) {
                        }
                    } catch (MQClientException e) {
                        statsBenchmark.getSendRequestFailedCount().incrementAndGet();
                        log.error("[BENCHMARK_PRODUCER] Send Exception", e);
                    } catch (MQBrokerException e) {
                        statsBenchmark.getReceiveResponseFailedCount().incrementAndGet();
                        log.error("[BENCHMARK_PRODUCER] Send Exception", e);
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException ignored) {
                        }
                    }
                }
            }
        });
    }
}

From source file:sanghoon.flickr.photos.Dump.java

public static void main(String[] args) throws FileNotFoundException {

    //      args = new String[] { "-b", "-122.373971375,47.55575575,-122.3455185,47.585350625000004" };

    if (args.length < 1) {

        String header = "\n" + "Download all photos matching some criteria, using flickr.photos.search API."
                + "\n\n";

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java " + Dump.class.getName() + " [OPTIONS]...", header, createOptions(), "");
        return;//from   w  w  w  .  j ava  2 s .  co  m
    }

    CommandLineParser parser = new DefaultParser();
    CommandLine line;
    try {
        line = parser.parse(createOptions(), args);
    } catch (ParseException exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        return;
    }

    String tags = line.hasOption("tags") ? line.getOptionValue("tags") : null;

    String minTakenDate = line.hasOption("min-taken-date") ? line.getOptionValue("min-taken-date") : null;
    String maxTakenDate = line.hasOption("max-taken-date") ? line.getOptionValue("max-taken-date") : null;

    String bbox = line.hasOption("bounding-box") ? line.getOptionValue("bounding-box") : null;
    if (bbox == null) {
        System.err.println("bounding box parameter is required");
        return;
    }
    // TODO: places.find  places.getInfo  ? id bounding box 
    //      String woeID = line.hasOption("woe-id") ? line.getOptionValue("woe-id") : null;
    //      String placeID = line.hasOption("place-id") ? line.getOptionValue("place-id") : null;

    String outputFilePrefix = line.hasOption("output-file-prefix") ? line.getOptionValue("output-file-prefix")
            : "output";

    ApiKey key = ApiKey.load(ClassLoader.getSystemResourceAsStream("flickr_api_key.properties"));

    Map<String, String> outputs = new HashMap<>();

    String[] coords = bbox.split(",");

    double minimum_longitude = Double.parseDouble(coords[0]);
    double minimum_latitude = Double.parseDouble(coords[1]);
    double maximum_longitude = Double.parseDouble(coords[2]);
    double maximum_latitude = Double.parseDouble(coords[3]);

    LinkedList<BoundingBox> bboxes = new LinkedList<>();
    bboxes.add(new BoundingBox(minimum_longitude, minimum_latitude, maximum_longitude, maximum_latitude));

    int index = 0;

    while (bboxes.isEmpty() == false) {
        BoundingBox box = bboxes.pollFirst();

        int page = 1;

        System.out.print("searching for " + box.toString() + " .");

        Integer total = search(key, box, tags, minTakenDate, maxTakenDate, page, outputs);

        if (total == null) {
            bboxes.addLast(box);
            System.out.println(" failed, retry later");
            continue;
        } else if (MAX_PHOTOS_IN_A_BBOX < total) {
            // Please note that Flickr will return at most the first 4,000 results for any given search query. 
            // If this is an issue, we recommend trying a more specific query.

            //  
            List<BoundingBox> splitBoxes = box.split();
            for (BoundingBox splitBox : splitBoxes)
                bboxes.addLast(splitBox);

            System.out.print(" " + total + " photos (>" + MAX_PHOTOS_IN_A_BBOX + "), split ");

            System.out.print("{");
            for (int i = 0; i < splitBoxes.size(); i++) {
                if (0 < i)
                    System.out.print(",");
                System.out.print("[");
                System.out.print(splitBoxes.get(i).toString());
                System.out.print("]");
            }
            System.out.print("}");
            System.out.println();

            continue;
        } else if (PER_PAGE < total) {
            // ? search box ? ?  ? ?  
            // (?  ? PER_PAGE ?), 
            // page ?  

            while (page * PER_PAGE < total) {
                page++;
                search(key, box, tags, minTakenDate, maxTakenDate, page, outputs);
                System.out.print(".");
            }
            System.out.println(" " + total + " photos in " + page + " pages");
        }

        if (MAX_PHOTOS_IN_AN_OUTPUT < outputs.size()) {
            // ? ? ?  ? ?

            String filename = outputFilePrefix + "_" + index++ + ".json";
            write(outputs, filename);
            outputs.clear();
        }
    }

    String filename = outputFilePrefix + "_" + index++ + ".json";
    write(outputs, filename);

    System.out.println("finished");
}

From source file:LinkedListExample.java

public static void main(String[] args) {
    // Create a new LinkedList
    LinkedList<Integer> list = new LinkedList<Integer>();

    // Add Items to the array list
    list.add(new Integer(1));
    list.add(new Integer(2));
    list.add(new Integer(3));
    list.add(new Integer(4));
    list.add(new Integer(5));
    list.add(new Integer(6));
    list.add(new Integer(7));
    list.add(new Integer(8));
    list.add(new Integer(9));
    list.add(new Integer(10));

    // Use iterator to display the values
    for (Iterator i = list.iterator(); i.hasNext();) {
        Integer integer = (Integer) i.next();
        System.out.println(integer);
    }//from   w w  w.ja va  2 s.  c o  m

    // Remove the element at index 5 (value=6)
    list.remove(5);

    // Set the value at index 5, this overwrites the value 7
    list.set(5, new Integer(66));

    // Use the linked list as a queue:
    // add an object to the end of the list (queue)
    // remove an item from the head of the list (queue)
    list.addLast(new Integer(11));
    Integer head = (Integer) list.removeFirst();
    System.out.println("Head: " + head);

    // Use iterator to display the values
    for (Iterator i = list.iterator(); i.hasNext();) {
        Integer integer = (Integer) i.next();
        System.out.println(integer);
    }
}

From source file:org.gcaldaemon.gui.Messages.java

public static final Locale[] getAvailableLocales() {
    LinkedList list = new LinkedList();
    list.addLast(Locale.ENGLISH);
    try {//from   ww w.  java 2  s .  c o m
        Locale[] availables = Locale.getAvailableLocales();
        String programDir = System.getProperty("gcaldaemon.program.dir", "/Progra~1/GCALDaemon");
        File langDir = new File(programDir, "lang");
        if (langDir.isDirectory()) {
            String[] names = langDir.list();
            String name;
            int s, e;
            for (int i = 0; i < names.length; i++) {
                name = names[i];
                if (name.equals("messages-en.txt")) {
                    continue;
                }
                s = name.indexOf('-');
                e = name.indexOf('.', s);
                if (s != -1 && e != -1) {
                    name = name.substring(s + 1, e);
                    Locale locale = null;
                    for (s = 0; s < availables.length; s++) {
                        if (name.equals(availables[s].getCountry().toLowerCase())) {
                            locale = availables[s];
                            break;
                        }
                    }
                    if (locale == null) {
                        locale = new Locale(name);
                    }
                    list.add(locale);
                }
            }
        }
    } catch (Exception ignored) {
        log.warn(ignored);
    }
    Locale[] array = new Locale[list.size()];
    list.toArray(array);
    return array;
}

From source file:org.gcaldaemon.gui.Messages.java

public static final String[][] getTranslatorTable(Locale locale) {
    Enumeration keyEnumerator = DEFAULT_RESOURCE_BUNDLE.getKeys();
    LinkedList list = new LinkedList();
    while (keyEnumerator.hasMoreElements()) {
        list.addLast(keyEnumerator.nextElement());
    }//from  ww w  . j  a va 2 s.  c  o  m
    String[] keys = new String[list.size()];
    list.toArray(keys);
    Arrays.sort(keys, String.CASE_INSENSITIVE_ORDER);
    String[][] data = new String[keys.length][3];
    PropertyResourceBundle localeBundle = null;
    try {
        String programDir = System.getProperty("gcaldaemon.program.dir", "/Progra~1/GCALDaemon");
        File langDir = new File(programDir, "lang");
        if (!langDir.isDirectory()) {
            langDir.mkdir();
        } else {
            File msgFile = new File(langDir, "messages-" + locale.getLanguage().toLowerCase() + ".txt");
            if (msgFile.isFile()) {
                InputStream in = new BufferedInputStream(new FileInputStream(msgFile));
                localeBundle = new PropertyResourceBundle(in);
                in.close();
            }
        }
    } catch (Exception ignored) {
        log.warn("Unable to load messages!", ignored);
    }
    for (int i = 0; i < keys.length; i++) {
        data[i][0] = keys[i];
        data[i][1] = DEFAULT_RESOURCE_BUNDLE.getString(keys[i]);
        if (localeBundle != null) {
            try {
                data[i][2] = localeBundle.getString(keys[i]);
            } catch (Exception ignored) {
            }
        }
        if (data[i][2] == null) {
            data[i][2] = data[i][1];
        }
    }
    return data;
}

From source file:Main.java

/**
 * Takes a number of tags of name 'name' that are children of 'root', and
 * looks for attributes of 'attrib' on them.  Converts attributes to an
 * int and returns in an array.//from  w  ww . ja  v a 2s . c  om
 */
public static String[] getElementArrayString(Element root, String name, String attrib) {
    if (root == null)
        return null;

    NodeList nl = root.getChildNodes();
    LinkedList<String> elementCache = new LinkedList<String>();
    int size = nl.getLength();

    for (int i = 0; i < size; i++) {
        Node node = nl.item(i);
        if (!(node instanceof Element))
            continue;
        Element ele = (Element) node;
        if (!ele.getTagName().equals(name))
            continue;

        String valS = ele.getAttribute(attrib);

        elementCache.addLast(valS);
    }

    String[] retArr = new String[elementCache.size()];
    Iterator<String> it = elementCache.iterator();
    int idx = 0;
    while (it.hasNext()) {
        retArr[idx++] = it.next();
    }

    return retArr;
}