Example usage for com.google.common.collect Lists newArrayList

List of usage examples for com.google.common.collect Lists newArrayList

Introduction

In this page you can find the example usage for com.google.common.collect Lists newArrayList.

Prototype

@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayList(Iterator<? extends E> elements) 

Source Link

Document

Creates a mutable ArrayList instance containing the given elements; a very thin shortcut for creating an empty list and then calling Iterators#addAll .

Usage

From source file:com.google.api.services.samples.youtube.cmdline.data.ChannelSectionLocalizations.java

/**
 * Set and retrieve localized metadata for a channel section.
 *
 * @param args command line args (not used).
 *//*from  ww w .java 2 s  . c  o m*/
public static void main(String[] args) {

    // This OAuth 2.0 access scope allows for full read/write access to the
    // authenticated user's account.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube");

    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "localizations");

        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
                .setApplicationName("youtube-cmdline-localizations-sample").build();

        // Prompt the user to specify the action of the be achieved.
        String actionString = getActionFromUser();
        System.out.println("You chose " + actionString + ".");
        //Map the user input to the enum values.
        Action action = Action.valueOf(actionString.toUpperCase());

        switch (action) {
        case SET:
            setChannelSectionLocalization(getId("channel section"), getDefaultLanguage(), getLanguage(),
                    getMetadata("title"));
            break;
        case GET:
            getChannelSectionLocalization(getId("channel section"), getLanguage());
            break;
        case LIST:
            listChannelSectionLocalizations(getId("channel section"));
            break;
        }
    } catch (GoogleJsonResponseException e) {
        System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : "
                + e.getDetails().getMessage());
        e.printStackTrace();

    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
}

From source file:com.whoisthebest.UploadVideo.java

/**
 * Upload the user-selected video to the user's YouTube channel. The code
 * looks for the video in the application's project folder and uses OAuth
 * 2.0 to authorize the API request.//from   w ww  .ja v  a2 s .  c o m
 *
 * @param args command line args (not used).
 */
public static void main(String[] args) {

    // This OAuth 2.0 access scope allows an application to upload files
    // to the authenticated user's YouTube channel, but doesn't allow
    // other types of access.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.upload");

    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "uploadvideo");

        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
                .setApplicationName("youtube-cmdline-uploadvideo-sample").build();

        System.out.println("Uploading: " + SAMPLE_VIDEO_FILENAME);

        // Add extra information to the video before uploading.
        Video videoObjectDefiningMetadata = new Video();

        // Set the video to be publicly visible. This is the default
        // setting. Other supporting settings are "unlisted" and "private."
        VideoStatus status = new VideoStatus();
        status.setPrivacyStatus("public");
        videoObjectDefiningMetadata.setStatus(status);

        // Most of the video's metadata is set on the VideoSnippet object.
        VideoSnippet snippet = new VideoSnippet();

        // This code uses a Calendar instance to create a unique name and
        // description for test purposes so that you can easily upload
        // multiple files. You should remove this code from your project
        // and use your own standard names instead.
        Calendar cal = Calendar.getInstance();
        snippet.setTitle("Test Upload via Java on " + cal.getTime());
        snippet.setDescription(
                "Video uploaded via YouTube Data API V3 using the Java library " + "on " + cal.getTime());

        // Set the keyword tags that you want to associate with the video.
        List<String> tags = new ArrayList<String>();
        tags.add("test");
        tags.add("example");
        tags.add("java");
        tags.add("YouTube Data API V3");
        tags.add("erase me");
        snippet.setTags(tags);

        // Add the completed snippet object to the video resource.
        videoObjectDefiningMetadata.setSnippet(snippet);

        InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT,
                UploadVideo.class.getResourceAsStream("/sample-video.mp4"));

        // Insert the video. The command sends three arguments. The first
        // specifies which information the API request is setting and which
        // information the API response should return. The second argument
        // is the video resource that contains metadata about the new video.
        // The third argument is the actual video content.
        YouTube.Videos.Insert videoInsert = youtube.videos().insert("snippet,statistics,status",
                videoObjectDefiningMetadata, mediaContent);

        // Set the upload type and add an event listener.
        MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();

        // Indicate whether direct media upload is enabled. A value of
        // "True" indicates that direct media upload is enabled and that
        // the entire media content will be uploaded in a single request.
        // A value of "False," which is the default, indicates that the
        // request will use the resumable media upload protocol, which
        // supports the ability to resume an upload operation after a
        // network interruption or other transmission failure, saving
        // time and bandwidth in the event of network failures.
        uploader.setDirectUploadEnabled(false);

        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {
            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                switch (uploader.getUploadState()) {
                case INITIATION_STARTED:
                    System.out.println("Initiation Started");
                    break;
                case INITIATION_COMPLETE:
                    System.out.println("Initiation Completed");
                    break;
                case MEDIA_IN_PROGRESS:
                    System.out.println("Upload in progress");
                    System.out.println("Upload percentage: " + uploader.getProgress());
                    break;
                case MEDIA_COMPLETE:
                    System.out.println("Upload Completed!");
                    break;
                case NOT_STARTED:
                    System.out.println("Upload Not Started!");
                    break;
                }
            }
        };
        uploader.setProgressListener(progressListener);

        // Call the API and upload the video.
        Video returnedVideo = videoInsert.execute();

        // Print data about the newly inserted video from the API response.
        System.out.println("\n================== Returned Video ==================\n");
        System.out.println("  - Id: " + returnedVideo.getId());
        System.out.println("  - Title: " + returnedVideo.getSnippet().getTitle());
        System.out.println("  - Tags: " + returnedVideo.getSnippet().getTags());
        System.out.println("  - Privacy Status: " + returnedVideo.getStatus().getPrivacyStatus());
        System.out.println("  - Video Count: " + returnedVideo.getStatistics().getViewCount());

    } catch (GoogleJsonResponseException e) {
        System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : "
                + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
}

From source file:org.jclouds.examples.rackspace.cloudloadbalancers.CreateLoadBalancerWithNewServers.java

/**
 * To get a username and API key see http://jclouds.apache.org/guides/rackspace/
 *
 * The first argument (args[0]) must be your username
 * The second argument (args[1]) must be your API key
 *//*from  w  ww  .  ja v a 2  s.c o  m*/
public static void main(String[] args) throws IOException {
    CreateLoadBalancerWithNewServers createLoadBalancer = new CreateLoadBalancerWithNewServers(args[0],
            args[1]);

    try {
        List<String> argsList = Lists.newArrayList(args);
        argsList.add("2"); // the number of Cloud Servers to start
        Set<? extends NodeMetadata> nodes = CloudServersPublish.getPublishedCloudServers(argsList);

        Set<AddNode> addNodes = createLoadBalancer.createNodeRequests(nodes);
        createLoadBalancer.createLoadBalancer(addNodes);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        createLoadBalancer.close();
    }
}

From source file:com.aliyun.emr.example.JavaMNSWordCount.java

public static void main(String[] args) {
    if (args.length < 4) {
        System.err.println(//from  w ww .ja  v a  2  s . co m
                "Usage: bin/spark-submit --class JavaMNSWordCount examples-1.0-SNAPSHOT-shaded.jar <queueName> "
                        + "<accessKeyId> <accessKeySecret> <endpoint>");
        System.exit(1);
    }

    String queueName = args[0];
    String accessKeyId = args[1];
    String accessKeySecret = args[2];
    String endpoint = args[3];

    SparkConf sparkConf = new SparkConf().setAppName("JavaMNSWordCount");
    // Create the context with 2 seconds batch size
    JavaStreamingContext jssc = new JavaStreamingContext(sparkConf, new Duration(2000));

    JavaReceiverInputDStream<byte[]> lines = MnsUtils.createPullingStreamAsBytes(jssc, queueName, accessKeyId,
            accessKeySecret, endpoint, StorageLevel.MEMORY_AND_DISK());

    JavaDStream<String> words = lines.map(new Function<byte[], String>() {
        @Override
        public String call(byte[] v1) throws Exception {
            return new String(v1);
        }
    }).flatMap(new FlatMapFunction<String, String>() {
        @Override
        public Iterable<String> call(String x) {
            return Lists.newArrayList(SPACE.split(x));
        }
    });
    JavaPairDStream<String, Integer> wordCounts = words.mapToPair(new PairFunction<String, String, Integer>() {
        @Override
        public Tuple2<String, Integer> call(String s) {
            return new Tuple2<String, Integer>(s, 1);
        }
    }).reduceByKey(new Function2<Integer, Integer, Integer>() {
        @Override
        public Integer call(Integer i1, Integer i2) {
            return i1 + i2;
        }
    });

    wordCounts.print();
    jssc.start();
    jssc.awaitTermination();
}

From source file:org.elasticsearch.transport.netty.benchmark.BenchmarkNettyClient.java

public static void main(String[] args) {
    final SizeValue payloadSize = new SizeValue(100, SizeUnit.BYTES);
    final int NUMBER_OF_CLIENTS = 1;
    final int NUMBER_OF_ITERATIONS = 500000;
    final byte[] payload = new byte[(int) payloadSize.bytes()];
    final AtomicLong idGenerator = new AtomicLong();
    final boolean waitForRequest = false;
    final boolean spawn = true;

    Settings settings = ImmutableSettings.settingsBuilder().put("network.server", false)
            .put("transport.netty.connectionsPerNode", 5).build();

    final ThreadPool threadPool = new CachedThreadPool();
    final TransportService transportService = new TransportService(new NettyTransport(settings, threadPool),
            threadPool).start();//from  w  w w.  j  av  a 2 s.c  o  m

    final Node node = new Node("server", new InetSocketTransportAddress("localhost", 9999));

    transportService.nodesAdded(Lists.newArrayList(node));

    Thread[] clients = new Thread[NUMBER_OF_CLIENTS];
    final CountDownLatch latch = new CountDownLatch(NUMBER_OF_CLIENTS * NUMBER_OF_ITERATIONS);
    for (int i = 0; i < NUMBER_OF_CLIENTS; i++) {
        clients[i] = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int j = 0; j < NUMBER_OF_ITERATIONS; j++) {
                    final long id = idGenerator.incrementAndGet();
                    BenchmarkMessage message = new BenchmarkMessage(id, payload);
                    BaseTransportResponseHandler<BenchmarkMessage> handler = new BaseTransportResponseHandler<BenchmarkMessage>() {
                        @Override
                        public BenchmarkMessage newInstance() {
                            return new BenchmarkMessage();
                        }

                        @Override
                        public void handleResponse(BenchmarkMessage response) {
                            if (response.id != id) {
                                System.out.println("NO ID MATCH [" + response.id + "] and [" + id + "]");
                            }
                            latch.countDown();
                        }

                        @Override
                        public void handleException(RemoteTransportException exp) {
                            exp.printStackTrace();
                            latch.countDown();
                        }

                        @Override
                        public boolean spawn() {
                            return spawn;
                        }
                    };

                    if (waitForRequest) {
                        transportService.submitRequest(node, "benchmark", message, handler).txGet();
                    } else {
                        transportService.sendRequest(node, "benchmark", message, handler);
                    }
                }
            }
        });
    }

    StopWatch stopWatch = new StopWatch().start();
    for (int i = 0; i < NUMBER_OF_CLIENTS; i++) {
        clients[i].start();
    }

    try {
        latch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    stopWatch.stop();

    System.out.println("Ran [" + NUMBER_OF_CLIENTS + "], each with [" + NUMBER_OF_ITERATIONS
            + "] iterations, payload [" + payloadSize + "]: took [" + stopWatch.totalTime() + "], TPS: "
            + (NUMBER_OF_CLIENTS * NUMBER_OF_ITERATIONS) / stopWatch.totalTime().secondsFrac());

    transportService.close();
    threadPool.shutdownNow();
}

From source file:com.google.api.services.samples.youtube.cmdline.data.CommentHandling.java

/**
 * List, reply to comment threads; list, update, moderate, mark and delete
 * replies./* ww w.  j  a  v  a  2s  .  com*/
 *
 * @param args command line args (not used).
 */
public static void main(String[] args) {

    // This OAuth 2.0 access scope allows for full read/write access to the
    // authenticated user's account and requires requests to use an SSL connection.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.force-ssl");

    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "commentthreads");

        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
                .setApplicationName("youtube-cmdline-commentthreads-sample").build();

        // Prompt the user for the ID of a video to comment on.
        // Retrieve the video ID that the user is commenting to.
        String videoId = getVideoId();
        System.out.println("You chose " + videoId + " to subscribe.");

        // Prompt the user for the comment text.
        // Retrieve the text that the user is commenting.
        String text = getText();
        System.out.println("You chose " + text + " to subscribe.");

        // All the available methods are used in sequence just for the sake
        // of an example.

        // Call the YouTube Data API's commentThreads.list method to
        // retrieve video comment threads.
        V3CommentThreadListResponse videoCommentsListResponse = youtube.commentThreads().list("snippet")
                .setVideoId(videoId).setTextFormat("plainText").execute();
        List<CommentThread> videoComments = videoCommentsListResponse.getItems();

        if (videoComments.isEmpty()) {
            System.out.println("Can't get video comments.");
        } else {
            // Print information from the API response.
            System.out.println("\n================== Returned Video Comments ==================\n");
            for (CommentThread videoComment : videoComments) {
                CommentSnippet snippet = videoComment.getSnippet().getTopLevelComment().getSnippet();
                System.out.println("  - Author: " + snippet.getAuthorDisplayName());
                System.out.println("  - Comment: " + snippet.getTextDisplay());
                System.out.println("\n-------------------------------------------------------------\n");
            }
            CommentThread firstComment = videoComments.get(0);

            // Will use this thread as parent to new reply.
            String parentId = firstComment.getId();

            // Create a comment snippet with text.
            CommentSnippet commentSnippet = new CommentSnippet();
            commentSnippet.setTextOriginal(text);
            commentSnippet.setParentId(parentId);

            // Create a comment with snippet.
            Comment comment = new Comment();
            comment.setSnippet(commentSnippet);

            // Call the YouTube Data API's comments.insert method to reply
            // to a comment.
            // (If the intention is to create a new top-level comment,
            // commentThreads.insert
            // method should be used instead.)
            Comment commentInsertResponse = youtube.comments().insert("snippet", comment).execute();

            // Print information from the API response.
            System.out.println("\n================== Created Comment Reply ==================\n");
            CommentSnippet snippet = commentInsertResponse.getSnippet();
            System.out.println("  - Author: " + snippet.getAuthorDisplayName());
            System.out.println("  - Comment: " + snippet.getTextDisplay());
            System.out.println("\n-------------------------------------------------------------\n");

            // Call the YouTube Data API's comments.list method to retrieve
            // existing comment
            // replies.
            V3CommentListResponse commentsListResponse = youtube.comments().list("snippet")
                    .setParentId(parentId).setTextFormat("plainText").execute();
            List<Comment> comments = commentsListResponse.getItems();

            if (comments.isEmpty()) {
                System.out.println("Can't get comment replies.");
            } else {
                // Print information from the API response.
                System.out.println("\n================== Returned Comment Replies ==================\n");
                for (Comment commentReply : comments) {
                    snippet = commentReply.getSnippet();
                    System.out.println("  - Author: " + snippet.getAuthorDisplayName());
                    System.out.println("  - Comment: " + snippet.getTextDisplay());
                    System.out.println("\n-------------------------------------------------------------\n");
                }
                Comment firstCommentReply = comments.get(0);
                firstCommentReply.getSnippet().setTextOriginal("updated");
                Comment commentUpdateResponse = youtube.comments().update("snippet", firstCommentReply)
                        .execute();
                // Print information from the API response.
                System.out.println("\n================== Updated Video Comment ==================\n");
                snippet = commentUpdateResponse.getSnippet();
                System.out.println("  - Author: " + snippet.getAuthorDisplayName());
                System.out.println("  - Comment: " + snippet.getTextDisplay());
                System.out.println("\n-------------------------------------------------------------\n");

                // Call the YouTube Data API's comments.setModerationStatus
                // method to set moderation
                // status of an existing comment.
                youtube.comments().setModerationStatus(firstCommentReply.getId(), "published");
                System.out.println("  -  Changed comment status to published: " + firstCommentReply.getId());

                // Call the YouTube Data API's comments.markAsSpam method to
                // mark an existing comment as spam.
                youtube.comments().markAsSpam(firstCommentReply.getId());
                System.out.println("  -  Marked comment as spam: " + firstCommentReply.getId());

                // Call the YouTube Data API's comments.delete method to
                // delete an existing comment.
                youtube.comments().delete(firstCommentReply.getId());
                System.out.println("  -  Deleted comment as spam: " + firstCommentReply.getId());
            }
        }
    } catch (GoogleJsonResponseException e) {
        System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : "
                + e.getDetails().getMessage());
        e.printStackTrace();

    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
}

From source file:JavaNetworkWordCount.java

public static void main(String[] args) {

    // Create the context with a 10 second batch size
    SparkConf sparkConf = new SparkConf().setAppName("JavaNetworkWordCount");
    JavaStreamingContext ssc = new JavaStreamingContext(sparkConf, new Duration(10000));

    // Create a JavaReceiverInputDStream on target ip:port and count the
    // words in input stream of \n delimited text (eg. generated by 'nc')
    // Note that no duplication in storage level only for running locally.
    // Replication necessary in distributed scenario for fault tolerance.
    JavaReceiverInputDStream<String> lines = ssc.socketTextStream("localhost", Integer.parseInt("9999"),
            StorageLevels.MEMORY_AND_DISK_SER);

    JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
        @Override//from w w w .  j a  v  a2s.co  m
        public Iterable<String> call(String x) {
            return Lists.newArrayList(SPACE.split(x));
        }
    });

    JavaPairDStream<String, Integer> wordCounts = words.mapToPair(new PairFunction<String, String, Integer>() {
        @Override
        public Tuple2<String, Integer> call(String s) {
            return new Tuple2<String, Integer>(s, 1);
        }
    }).reduceByKey(new Function2<Integer, Integer, Integer>() {
        @Override
        public Integer call(Integer i1, Integer i2) {
            return i1 + i2;
        }
    });

    wordCounts.print();

    ssc.start();

    ssc.awaitTermination();
}

From source file:com.google.devtools.kythe.extractors.java.bazel.JavaExtractor.java

public static void main(String[] args) throws IOException, ExtractionException {
    if (args.length != 3) {
        System.err.println("Usage: java_extractor extra-action-file output-file vname-config");
        System.exit(1);/*  w  ww  . j  a  v a  2s. co m*/
    }

    String extraActionPath = args[0];
    String outputPath = args[1];
    String vNamesConfigPath = args[2];

    ExtensionRegistry registry = ExtensionRegistry.newInstance();
    ExtraActionsBase.registerAllExtensions(registry);

    ExtraActionInfo info;
    try (InputStream stream = Files.newInputStream(Paths.get(extraActionPath))) {
        CodedInputStream coded = CodedInputStream.newInstance(stream);
        info = ExtraActionInfo.parseFrom(coded, registry);
    }

    if (!info.hasExtension(JavaCompileInfo.javaCompileInfo)) {
        throw new IllegalArgumentException("Given ExtraActionInfo without JavaCompileInfo");
    }

    JavaCompileInfo jInfo = info.getExtension(JavaCompileInfo.javaCompileInfo);

    List<String> javacOpts = Lists.newArrayList(Iterables.filter(jInfo.getJavacOptList(), JAVAC_OPT_FILTER));

    // Set up a fresh output directory
    javacOpts.add("-d");
    Path output = Files.createTempDirectory("output");
    javacOpts.add(output.toString());

    // Add the generated sources directory if any processors could be invoked.
    if (!jInfo.getProcessorList().isEmpty()) {
        String gensrcdir = readGeneratedSourceDirParam(jInfo);
        if (gensrcdir != null) {
            javacOpts.add("-s");
            javacOpts.add(gensrcdir);
            // javac expects the directory to already exist.
            Files.createDirectories(Paths.get(gensrcdir));
        }
    }

    CompilationDescription description = new JavaCompilationUnitExtractor(FileVNames.fromFile(vNamesConfigPath),
            System.getProperty("user.dir")).extract(info.getOwner(), jInfo.getSourceFileList(),
                    jInfo.getClasspathList(), jInfo.getSourcepathList(), jInfo.getProcessorpathList(),
                    jInfo.getProcessorList(), javacOpts, jInfo.getOutputjar());

    IndexInfoUtils.writeIndexInfoToFile(description, outputPath);
}

From source file:org.apache.spark.examples.streaming.NetworkWordCount.java

public static void main(String[] args) {
    if (args.length < 2) {
        System.err.println("Usage: NetworkWordCount <hostname> <port>");
        System.exit(1);/*  ww w . j ava2  s.  co m*/
    }

    final String hostname = args[0];
    final int port = Integer.parseInt(args[1]);

    // Create the context with a 1 second batch size
    final SparkConf sparkConf = new SparkConf().setAppName("NetworkWordCount");
    final JavaStreamingContext ssc = new JavaStreamingContext(sparkConf, new Duration(1000));

    // Create a JavaReceiverInputDStream on target ip:port and count the
    // words in input stream of \n delimited text (eg. generated by 'nc')
    // Note that no duplication in storage level only for running locally.
    // Replication necessary in distributed scenario for fault tolerance.
    final JavaReceiverInputDStream<String> lines = ssc.socketTextStream(hostname, port,
            StorageLevels.MEMORY_AND_DISK_SER);
    final JavaDStream<String> words = lines.flatMap(x -> Lists.newArrayList(SPACE.split(x)));
    final JavaPairDStream<String, Integer> wordCounts = words.mapToPair(s -> new Tuple2<>(s, 1))
            .reduceByKey((i1, i2) -> i1 + i2);

    wordCounts.print();
    ssc.start();
    ssc.awaitTermination();
}

From source file:pl.edu.icm.cermine.bx.DocumentRORes.java

public static void main(String[] args) throws TransformationException, IOException, AnalysisException,
        ParseException, CloneNotSupportedException {
    Options options = new Options();
    options.addOption("input", true, "input path");
    options.addOption("output", true, "output path");
    CommandLineParser parser = new GnuParser();
    CommandLine line = parser.parse(options, args);
    String inDir = line.getOptionValue("input");
    String outDir = line.getOptionValue("output");

    File dir = new File(inDir);

    for (File f : FileUtils.listFiles(dir, new String[] { "xml" }, true)) {
        TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader();
        List<BxPage> pages = tvReader.read(new FileReader(f));
        BxDocument doc = new BxDocument().setPages(pages);
        doc.setFilename(f.getName());// w ww  .j  a v  a  2  s  .  co  m

        HierarchicalReadingOrderResolver roResolver = new HierarchicalReadingOrderResolver();
        BxDocument d2 = roResolver.resolve(doc);

        System.out.println(doc.getFilename());

        File f2 = new File(outDir + doc.getFilename());
        boolean created = f2.createNewFile();
        if (!created) {
            throw new IOException("Cannot create file!");
        }
        BxDocumentToTrueVizWriter writer = new BxDocumentToTrueVizWriter();
        writer.write(new FileWriter(f2), Lists.newArrayList(d2));
    }
}