Example usage for java.io PrintWriter close

List of usage examples for java.io PrintWriter close

Introduction

In this page you can find the example usage for java.io PrintWriter close.

Prototype

public void close() 

Source Link

Document

Closes the stream and releases any system resources associated with it.

Usage

From source file:edu.usc.qufd.Main.java

/**
 * The main method./*from  w  w w.j ava2  s .c o m*/
 *
 * @param args the arguments
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void main(String[] args) throws IOException {
    if (parseInputs(args) == false) {
        System.exit(-1); //The input files do not exist
    }

    /*
     * Parsing inputs: fabric & qasm file
     */
    PrintWriter outputFile;
    RandomAccessFile raf = null;
    String latencyPlaceHolder;
    if (RuntimeConfig.OUTPUT_TO_FILE) {
        latencyPlaceHolder = "Total Latency: " + Long.MAX_VALUE + " us" + System.lineSeparator();
        raf = new RandomAccessFile(outputFileAddr, "rws");
        //removing the old values in the file
        raf.setLength(0);
        //writing a place holder for the total latency
        raf.writeBytes(latencyPlaceHolder);
        raf.close();

        outputFile = new PrintWriter(new BufferedWriter(new FileWriter(outputFileAddr, true)), true);
    } else { //writing to stdout
        outputFile = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), true);
    }
    /* parsing the input*/
    layout = LayoutParser.parse(pmdFileAddr);
    qasm = QASMParser.QASMParser(qasmFileAddr, layout);

    long totalLatency = qufd(outputFile);

    if (RuntimeConfig.OUTPUT_TO_FILE) {
        outputFile.close();
        //Over writing the place holder with the actual latency
        String latencyActual = "Total Latency: " + totalLatency + " " + layout.getTimeUnit();
        latencyActual = StringUtils.rightPad(latencyActual,
                latencyPlaceHolder.length() - System.lineSeparator().length());
        raf = new RandomAccessFile(outputFileAddr, "rws");
        //Writing to the top of a file
        raf.seek(0);
        //writing the actual total latency in the at the top of the output file
        raf.writeBytes(latencyActual + System.lineSeparator());
        raf.close();
    } else {
        outputFile.flush();
        System.out.println("Total Latency: " + totalLatency + " " + layout.getTimeUnit());
    }

    if (RuntimeConfig.VERBOSE) {
        System.out.println("Done.");
    }
    outputFile.close();
}

From source file:EchoClient.java

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

     Socket echoSocket = null;/*  w  w w .  j ava  2s  . c om*/
     PrintWriter out = null;
     BufferedReader in = null;

     try {
         echoSocket = new Socket("taranis", 7);
         out = new PrintWriter(echoSocket.getOutputStream(), true);
         in = new BufferedReader(new InputStreamReader(
                                     echoSocket.getInputStream()));
     } catch (UnknownHostException e) {
         System.err.println("Don't know about host: taranis.");
         System.exit(1);
     } catch (IOException e) {
         System.err.println("Couldn't get I/O for "
                            + "the connection to: taranis.");
         System.exit(1);
     }

BufferedReader stdIn = new BufferedReader(
                                new InputStreamReader(System.in));
String userInput;

while ((userInput = stdIn.readLine()) != null) {
    out.println(userInput);
    System.out.println("echo: " + in.readLine());
}

out.close();
in.close();
stdIn.close();
echoSocket.close();
 }

From source file:dap4.dap4.Dap4Print.java

/**
 * Main program.//w  w  w.j av  a2 s  .  c om
 * See usage() for command line arguments.
 * Default is to dump the header info only.
 *
 * @param argv command line arguments
 */
static public void main(String[] argv) {
    try {

        if (argv.length == 0)
            usage("");

        CommandlineOptions options = getopts(argv);
        PrintWriter output = null;
        if (options.outputfile != null) {
            File f = new File(options.outputfile);
            if (!f.canWrite())
                usage("Cannot write to output file: " + options.outputfile);
            output = new PrintWriter(new OutputStreamWriter(new FileOutputStream(f), DapUtil.UTF8));
        } else
            output = new PrintWriter(new OutputStreamWriter(System.out, DapUtil.UTF8));
        Dap4Print d4printer = new Dap4Print(options.path, output);
        d4printer.print();
        output.close();

    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:it.tidalwave.imageio.example.stats.FocalLengthStats.java

public static void main(final String[] args) {
    try {//from w  ww.j a  v  a2 s  . c  om
        final PrintWriter out = new PrintWriter(new File(args[1]));
        new DirectoryWalker() {
            @Override
            protected void handleFile(final File file, final int depth, final Collection results)
                    throws IOException {
                if (file.getName().toUpperCase().endsWith(".NEF")) {
                    System.out.printf("Processing %s...\n", file.getCanonicalPath());
                    final ImageReader reader = (ImageReader) ImageIO.getImageReaders(file).next();
                    reader.setInput(ImageIO.createImageInputStream(file));
                    final IIOMetadata metadata = reader.getImageMetadata(0);
                    final NEFMetadata nefMetadata = (NEFMetadata) metadata;
                    final IFD exifIFD = nefMetadata.getExifIFD();
                    final TagRational focalLength = exifIFD.getFocalLength();
                    out.println(focalLength.doubleValue());
                }
            }

            public void start() throws IOException {
                super.walk(new File(args[0]), new ArrayList<Object>());
            }
        }.start();

        out.flush();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Connect.java

public static void main(String[] args) {
    try { // Handle exceptions below
        // Get our command-line arguments
        String hostname = args[0];
        int port = Integer.parseInt(args[1]);
        String message = "";
        if (args.length > 2)
            for (int i = 2; i < args.length; i++)
                message += args[i] + " ";

        // Create a Socket connected to the specified host and port.
        Socket s = new Socket(hostname, port);

        // Get the socket output stream and wrap a PrintWriter around it
        PrintWriter out = new PrintWriter(s.getOutputStream());

        // Sent the specified message through the socket to the server.
        out.print(message + "\r\n");
        out.flush(); // Send it now.

        // Get an input stream from the socket and wrap a BufferedReader
        // around it, so we can read lines of text from the server.
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

        // Before we start reading the server's response tell the socket
        // that we don't want to wait more than 3 seconds
        s.setSoTimeout(3000);//from  w  w  w.j  av  a2  s.  c  om

        // Now read lines from the server until the server closes the
        // connection (and we get a null return indicating EOF) or until
        // the server is silent for 3 seconds.
        try {
            String line;
            while ((line = in.readLine()) != null)
                // If we get a line
                System.out.println(line); // print it out.
        } catch (SocketTimeoutException e) {
            // We end up here if readLine() times out.
            System.err.println("Timeout; no response from server.");
        }

        out.close(); // Close the output stream
        in.close(); // Close the input stream
        s.close(); // Close the socket
    } catch (IOException e) { // Handle IO and network exceptions here
        System.err.println(e);
    } catch (NumberFormatException e) { // Bad port number
        System.err.println("You must specify the port as a number");
    } catch (ArrayIndexOutOfBoundsException e) { // wrong # of args
        System.err.println("Usage: Connect <hostname> <port> message...");
    }
}

From source file:com.xx_dev.speed_test.SpeedTestClient.java

public static void main(String[] args) {
    EventLoopGroup group = new NioEventLoopGroup();
    try {/* w w w.jav a 2 s  .  c o  m*/

        URL url = new URL(args[0]);

        boolean isSSL = false;
        String host = url.getHost();
        int port = 80;
        if (StringUtils.equals(url.getProtocol(), "https")) {
            port = 443;
            isSSL = true;
        }

        if (url.getPort() > 0) {
            port = url.getPort();
        }

        String path = url.getPath();
        if (StringUtils.isNotBlank(url.getQuery())) {
            path += "?" + url.getQuery();
        }

        PrintWriter resultPrintWriter = null;
        if (StringUtils.isNotBlank(args[1])) {
            String resultFile = args[1];

            resultPrintWriter = new PrintWriter(
                    new OutputStreamWriter(new FileOutputStream(resultFile, false), "UTF-8"));
        }

        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class)
                .handler(new SpeedTestHttpClientChannelInitializer(isSSL, resultPrintWriter));

        // Make the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();

        // Prepare the HTTP request.
        HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
        request.headers().set(HttpHeaders.Names.HOST, host);
        request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
        //request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

        // Send the HTTP request.
        ch.writeAndFlush(request);

        // Wait for the server to close the connection.
        ch.closeFuture().sync();

        if (resultPrintWriter != null) {
            resultPrintWriter.close();
        }

    } catch (InterruptedException e) {
        logger.error(e.getMessage(), e);
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage(), e);
    } catch (MalformedURLException e) {
        logger.error(e.getMessage(), e);
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java

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

    logger = org.apache.logging.log4j.LogManager.getLogger(OpenUnisonUtils.class.getName());

    Options options = new Options();
    options.addOption("unisonXMLFile", true, "The full path to the Unison xml file");
    options.addOption("keystorePath", true, "The full path to the Unison keystore");
    options.addOption("chainName", true, "The name of the authentication chain");
    options.addOption("mechanismName", true, "The name of the authentication mechanism for SAML2");
    options.addOption("idpName", true, "The name of the identity provider application");
    options.addOption("pathToMetaData", true, "The full path to the saml2 metadata file");
    options.addOption("createDefault", false, "If set, add default parameters");
    options.addOption("action", true,
            "export-sp-metadata, import-sp-metadata, export-secretkey, print-secretkey, import-idp-metadata, export-idp-metadata, clear-dlq, import-secretkey, create-secretkey");
    options.addOption("urlBase", true, "Base URL, no URI; https://host:port");
    options.addOption("alias", true, "Key alias");
    options.addOption("newKeystorePath", true, "Path to the new keystore");
    options.addOption("newKeystorePassword", true, "Password for the new keystore");
    options.addOption("help", false, "Prints this message");
    options.addOption("signMetadataWithKey", true, "Signs the metadata with the specified key");
    options.addOption("dlqName", true, "The name of the dead letter queue");
    options.addOption("upgradeFrom106", false, "Updates workflows from 1.0.6");
    options.addOption("secretkey", true, "base64 encoded secret key");
    options.addOption("envFile", true, "Environment variables for parmaterized configs");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args, true);

    if (args.length == 0 || cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("OpenUnisonUtils", options);
    }//from www .ja  v  a 2  s  .  c om

    logger.info("Loading Unison Configuration");
    String unisonXMLFile = loadOption(cmd, "unisonXMLFile", options);
    TremoloType ttRead = loadTremoloType(unisonXMLFile, cmd, options);

    String action = loadOption(cmd, "action", options);
    TremoloType ttWrite = null;
    if (action.equalsIgnoreCase("import-sp-metadata") || action.equalsIgnoreCase("import-idp-metadata")) {
        ttWrite = loadTremoloType(unisonXMLFile);
    }

    logger.info("Configuration loaded");

    logger.info("Loading the keystore...");
    String ksPath = loadOption(cmd, "keystorePath", options);

    KeyStore ks = loadKeyStore(ksPath, ttRead);

    logger.info("...loaded");

    if (action.equalsIgnoreCase("import-sp-metadata")) {

        importMetaData(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);
    } else if (action.equalsIgnoreCase("export-sp-metadata")) {
        exportSPMetaData(options, cmd, ttRead, ks);

    } else if (action.equalsIgnoreCase("print-secretkey")) {
        printSecreyKey(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("import-secretkey")) {
        importSecreyKey(options, cmd, ttRead, ks, ksPath);
    } else if (action.equalsIgnoreCase("create-secretkey")) {
        Security.addProvider(new BouncyCastleProvider());
        logger.info("Creating AES-256 secret key");
        String alias = loadOption(cmd, "alias", options);
        logger.info("Alias : '" + alias + "'");
        KeyGenerator kg = KeyGenerator.getInstance("AES", "BC");
        kg.init(256, new SecureRandom());
        SecretKey sk = kg.generateKey();
        ks.setKeyEntry(alias, sk, ttRead.getKeyStorePassword().toCharArray(), null);
        logger.info("Saving key");
        ks.store(new FileOutputStream(ksPath), ttRead.getKeyStorePassword().toCharArray());
        logger.info("Finished");
    } else if (action.equalsIgnoreCase("export-secretkey")) {
        logger.info("Export Secret Key");

        logger.info("Loading key");
        String alias = loadOption(cmd, "alias", options);
        SecretKey key = (SecretKey) ks.getKey(alias, ttRead.getKeyStorePassword().toCharArray());
        logger.info("Loading new keystore path");
        String pathToNewKeystore = loadOption(cmd, "newKeystorePath", options);
        logger.info("Loading new keystore password");
        String ksPassword = loadOption(cmd, "newKeystorePassword", options);

        KeyStore newKS = KeyStore.getInstance("PKCS12");
        newKS.load(null, ttRead.getKeyStorePassword().toCharArray());
        newKS.setKeyEntry(alias, key, ksPassword.toCharArray(), null);
        newKS.store(new FileOutputStream(pathToNewKeystore), ksPassword.toCharArray());
        logger.info("Exported");
    } else if (action.equalsIgnoreCase("import-idp-metadata")) {
        importIdpMetadata(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks);

    } else if (action.equalsIgnoreCase("export-idp-metadata")) {
        exportIdPMetadata(options, cmd, ttRead, ks);
    } else if (action.equalsIgnoreCase("clear-dlq")) {
        logger.info("Getting the DLQ Name...");
        String dlqName = loadOption(cmd, "dlqName", options);
        QueUtils.emptyDLQ(ttRead, dlqName);
    } else if (action.equalsIgnoreCase("upgradeFrom106")) {
        logger.info("Upgrading OpenUnison's configuration from 1.0.6");

        String backupFileName = unisonXMLFile + ".bak";

        logger.info("Backing up to '" + backupFileName + "'");

        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(unisonXMLFile)));
        PrintWriter out = new PrintWriter(new FileOutputStream(backupFileName));
        String line = null;
        while ((line = in.readLine()) != null) {
            out.println(line);
        }
        out.flush();
        out.close();
        in.close();

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        AddChoiceToTasks.convert(new FileInputStream(unisonXMLFile), bout);
        FileOutputStream fsout = new FileOutputStream(unisonXMLFile);
        fsout.write(bout.toByteArray());
        fsout.flush();
        fsout.close();

    }

}

From source file:htmlwordtag.HtmlWordTag.java

public static void main(String[] args)
        throws RepositoryException, MalformedQueryException, QueryEvaluationException {
    //get current path
    String current = System.getProperty("user.dir");
    //get html file from internet
    loadhtml();/*from ww  w.  j a v a  2  s  .com*/
    //make director for output
    verifyArgs();
    //translate html file to rdf
    HtmlWordTag httpClientPost = new HtmlWordTag();
    httpClientPost.input = new File("input");
    httpClientPost.output = new File("output");
    httpClientPost.client = new HttpClient();
    httpClientPost.client.getParams().setParameter("http.useragent", "Calais Rest Client");

    httpClientPost.run();

    //create main memory repository
    Repository repo = new SailRepository(new MemoryStore());
    repo.initialize();

    File file = new File(current + "\\output\\website1.html.xml");

    RepositoryConnection con = repo.getConnection();
    try {
        con.add(file, null, RDFFormat.RDFXML);
    } catch (OpenRDFException e) {
        // handle exception
    } catch (java.io.IOException e) {
        // handle io exception
    }

    System.out.println(con.isEmpty());

    //query entire repostiory
    String queryString = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
            + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
            + "PREFIX c: <http://s.opencalais.com/1/type/em/e/>\n"
            + "PREFIX p: <http://s.opencalais.com/1/pred/>\n"
            + "PREFIX geo: <http://s.opencalais.com/1/type/er/Geo/>\n"

            + "SELECT  distinct ?s ?n\n" + "WHERE {\n" + "{  ?s rdf:type c:Organization.\n"
            + "   ?s p:name ?n.\n}" + "  UNION \n" + "{  ?s rdf:type c:Person.\n" + "   ?s p:name ?n.\n}"
            + "  UNION \n" + "{  ?s rdf:type geo:City.\n" + "   ?s p:name ?n.\n}" + "}";

    //System.out.println(queryString);

    //insert query through sparql repository connection
    TupleQuery tupleQuery = con.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
    TupleQueryResult result = tupleQuery.evaluate();

    File queryresultdir = new File(current + "\\queryresult");
    if (!queryresultdir.exists()) {
        if (queryresultdir.mkdir()) {
            System.out.println("Directory is created!");
        } else {
            System.out.println("Failed to create directory!");
        }
    }

    File queryresult = null;
    try {
        // create new file
        queryresult = new File(current + "\\queryresult\\queryresult1.txt");

        // tries to create new file in the system
        if (queryresult.exists()) {
            if (queryresult.delete()) {
                System.out.println("file queryresult1.txt is already exist.");
                System.out.println("file queryresult1.txt has been delete.");
                if (queryresult.createNewFile()) {
                    System.out.println("create queryresult1.txt success");
                } else {
                    System.out.println("fail to create queryresult1.txt");
                }
            } else {
                System.out.println("fail to delete queryresult1.txt.");
            }
        } else {
            if (queryresult.createNewFile()) {
                System.out.println("create queryresult1.txt success");
            } else {
                System.out.println("fail to create queryresult1.txt");
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        PrintWriter outputStream = null;
        try {
            outputStream = new PrintWriter(new FileOutputStream(current + "\\queryresult\\queryresult1.txt"));
        } catch (FileNotFoundException e) {
            System.out.println("Error to find file queryresult1.txt");
            System.exit(0);
        }
        //go through all triple in sparql repository
        while (result.hasNext()) { // iterate over the result
            BindingSet bindingSet = result.next();
            Value valueOfS = bindingSet.getValue("s");
            Value valueOfN = bindingSet.getValue("n");

            System.out.println(valueOfS + " " + valueOfN);

            outputStream.println(valueOfS + " " + valueOfN);

        }
        outputStream.close();
    } finally {
        result.close();
    }
    //create main memory repository
    Repository repo2 = new SailRepository(new MemoryStore());
    repo2.initialize();

    File file2 = new File(current + "\\output\\website2.html.xml");

    RepositoryConnection con2 = repo2.getConnection();
    try {
        con2.add(file2, null, RDFFormat.RDFXML);
    } catch (OpenRDFException e) {
        // handle exception
    } catch (java.io.IOException e) {
        // handle io exception
    }

    System.out.println(con2.isEmpty());

    //query entire repostiory
    String queryString2 = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
            + "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n"
            + "PREFIX c: <http://s.opencalais.com/1/type/em/e/>\n"
            + "PREFIX p: <http://s.opencalais.com/1/pred/>\n"
            + "PREFIX geo: <http://s.opencalais.com/1/type/er/Geo/>\n"

            + "SELECT  distinct ?s ?n\n" + "WHERE {\n" + "{  ?s rdf:type c:Organization.\n"
            + "   ?s p:name ?n.\n}" + "  UNION \n" + "{  ?s rdf:type c:Person.\n" + "   ?s p:name ?n.\n}"
            + "  UNION \n" + "{  ?s rdf:type geo:City.\n" + "   ?s p:name ?n.\n}" + "}";

    //System.out.println(queryString2);

    //insert query through sparql repository connection
    TupleQuery tupleQuery2 = con2.prepareTupleQuery(QueryLanguage.SPARQL, queryString2);
    TupleQueryResult result2 = tupleQuery2.evaluate();

    File queryresult2 = null;
    try {
        // create new file
        queryresult2 = new File(current + "\\queryresult\\queryresult2.txt");

        // tries to create new file in the system
        if (queryresult2.exists()) {
            if (queryresult2.delete()) {
                System.out.println("file queryresult2.txt is already exist.");
                System.out.println("file queryresult2.txt has been delete.");
                if (queryresult2.createNewFile()) {
                    System.out.println("create queryresult2.txt success");
                } else {
                    System.out.println("fail to create queryresult2.txt");
                }
            } else {
                System.out.println("fail to delete queryresult2.txt.");
            }
        } else {
            if (queryresult2.createNewFile()) {
                System.out.println("create queryresult2.txt success");
            } else {
                System.out.println("fail to create queryresult2.txt");
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        PrintWriter outputStream2 = null;
        try {
            outputStream2 = new PrintWriter(new FileOutputStream(current + "\\queryresult\\queryresult2.txt"));
        } catch (FileNotFoundException e) {
            System.out.println("Error to find file queryresult2.txt");
            System.exit(0);
        }
        //go through all triple in sparql repository
        while (result2.hasNext()) { // iterate over the result
            BindingSet bindingSet = result2.next();
            Value valueOfS = bindingSet.getValue("s");
            Value valueOfN = bindingSet.getValue("n");

            System.out.println(valueOfS + " " + valueOfN);

            outputStream2.println(valueOfS + " " + valueOfN);

        }
        outputStream2.close();
    } finally {
        result2.close();
    }

}

From source file:HttpMirror.java

public static void main(String args[]) {
    try {/*w  w  w. ja v a 2  s.c o m*/
        // Get the port to listen on
        int port = Integer.parseInt(args[0]);
        // Create a ServerSocket to listen on that port.
        ServerSocket ss = new ServerSocket(port);
        // Now enter an infinite loop, waiting for & handling connections.
        for (;;) {
            // Wait for a client to connect. The method will block;
            // when it returns the socket will be connected to the client
            Socket client = ss.accept();

            // Get input and output streams to talk to the client
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            PrintWriter out = new PrintWriter(client.getOutputStream());

            // Start sending our reply, using the HTTP 1.1 protocol
            out.print("HTTP/1.1 200 \r\n"); // Version & status code
            out.print("Content-Type: text/plain\r\n"); // The type of data
            out.print("Connection: close\r\n"); // Will close stream
            out.print("\r\n"); // End of headers

            // Now, read the HTTP request from the client, and send it
            // right back to the client as part of the body of our
            // response. The client doesn't disconnect, so we never get
            // an EOF. It does sends an empty line at the end of the
            // headers, though. So when we see the empty line, we stop
            // reading. This means we don't mirror the contents of POST
            // requests, for example. Note that the readLine() method
            // works with Unix, Windows, and Mac line terminators.
            String line;
            while ((line = in.readLine()) != null) {
                if (line.length() == 0)
                    break;
                out.print(line + "\r\n");
            }

            // Close socket, breaking the connection to the client, and
            // closing the input and output streams
            out.close(); // Flush and close the output stream
            in.close(); // Close the input stream
            client.close(); // Close the socket itself
        } // Now loop again, waiting for the next connection
    }
    // If anything goes wrong, print an error message
    catch (Exception e) {
        System.err.println(e);
        System.err.println("Usage: java HttpMirror <port>");
    }
}

From source file:org.kuali.student.git.importer.GitImporterMain.java

/**
 * @param args//from w ww  .  ja  va 2  s . c o  m
 */
public static void main(final String[] args) {

    if (args.length != 8 && args.length != 9) {
        log.error(
                "USAGE: <svn dump file> <git repository> <veto.log> <skipped-copy-from.log> <blob.log> <gc enabled> <svn repo base url> <repo uuid> [<git command path>]");
        log.error("\t<veto.log> : which paths were veto's as not being a valid branch");
        log.error("\t<skipped-copy-from.log> : which copy-from-paths were skipped");
        log.error("\t<blob.log> : issues related to blobs (typically directory copy related)");
        log.error("\t<gc enabled> : set to 1 (true ever 500 revs) or 0 (false) to disable");
        log.error("\t<svn repo base url> : the svn repo base url to use in the git-svn-id");
        log.error(
                "\t<repo uuid> : The svn repository uuid to use in the git-svn-id.\n\tIt you are importing from a clone use this to set the field to the real repositories uuid.");
        log.error("\t<git command path> : the path to a native git to use for gc's which occur every 500 revs");
        System.exit(-1);
    }

    try {

        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "GitImporterMain-applicationContext.xml");

        applicationContext.registerShutdownHook();

        SvnDumpFilter filter = applicationContext.getBean(SvnDumpFilter.class);

        BranchDetector branchDetector = applicationContext.getBean("branchDetector", BranchDetector.class);

        // final MergeDetectorData detectorData = applicationContext
        // .getBean(MergeDetectorData.class);

        File dumpFile = new File(args[0]);

        if (!dumpFile.exists()) {
            throw new FileNotFoundException(args[0] + " path not found");
        }

        File gitRepository = new File(args[1]).getAbsoluteFile();

        if (!gitRepository.getParentFile().exists())
            throw new FileNotFoundException(args[1] + "path not found");

        final PrintWriter vetoLog = new PrintWriter(args[2]);

        final PrintWriter copyFromSkippedLog = new PrintWriter(args[3]);

        final PrintWriter blobLog = new PrintWriter(args[4]);

        boolean gcEnabled = true;

        final boolean printGitSvnIds = true; // not optional anymore

        String repositoryBaseUrl = null;

        String repositoryUUID = null;

        if (args[5].trim().equals("0"))
            gcEnabled = false;

        repositoryBaseUrl = args[6].trim();

        repositoryUUID = args[7].trim();

        String nativeGitCommandPath = null;

        if (args.length == 9)
            nativeGitCommandPath = args[8].trim();

        final Repository repo = GitRepositoryUtils.buildFileRepository(gitRepository, false);

        // extract any known branches from the repository

        BZip2CompressorInputStream compressedInputStream = new BZip2CompressorInputStream(
                new FileInputStream(dumpFile));

        filter.parseDumpFile(compressedInputStream,
                new GitImporterParseOptions(repo, vetoLog, copyFromSkippedLog, blobLog, printGitSvnIds,
                        repositoryBaseUrl, repositoryUUID, branchDetector, gcEnabled, nativeGitCommandPath));

        vetoLog.close();
        copyFromSkippedLog.close();
        blobLog.close();

        compressedInputStream.close();

    } catch (Exception e) {
        log.error("Processing failed", e);
    }

}