Example usage for java.io File getName

List of usage examples for java.io File getName

Introduction

In this page you can find the example usage for java.io File getName.

Prototype

public String getName() 

Source Link

Document

Returns the name of the file or directory denoted by this abstract pathname.

Usage

From source file:edu.indiana.d2i.sloan.internal.CreateVMSimulator.java

public static void main(String[] args) {
    CreateVMSimulator simulator = new CreateVMSimulator();

    CommandLineParser parser = new PosixParser();

    try {// ww  w .  j a va2s  . c om
        CommandLine line = simulator.parseCommandLine(parser, args);

        String imagePath = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.IMAGE_PATH));
        int vcpu = Integer.parseInt(line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VCPU)));
        int mem = Integer.parseInt(line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.MEM)));

        if (!HypervisorCmdSimulator.resourceExist(imagePath)) {
            logger.error(String.format("Cannot find requested image: %s", imagePath));
            System.exit(ERROR_CODE.get(ERROR_STATE.IMAGE_NOT_EXIST));
        }

        if (!hasEnoughCPUs(vcpu)) {
            logger.error(String.format("Don't have enough cpus, requested %d", vcpu));
            System.exit(ERROR_CODE.get(ERROR_STATE.NOT_ENOUGH_CPU));
        }

        if (!hasEnoughMem(mem)) {
            logger.error(String.format("Don't have enough memory, requested %d", mem));
            System.exit(ERROR_CODE.get(ERROR_STATE.NOT_ENOUGH_MEM));
        }

        String wdir = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR));

        if (HypervisorCmdSimulator.resourceExist(wdir)) {
            logger.error(String.format("Working directory %s already exists ", wdir));
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_ALREADY_EXIST));
        }

        // copy VM image to working directory
        File imageFile = new File(imagePath);
        FileUtils.copyFile(imageFile, new File(HypervisorCmdSimulator.cleanPath(wdir) + imageFile.getName()));

        // write state as property file so that we can query later
        Properties prop = new Properties();

        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.IMAGE_PATH), imagePath);
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VCPU), String.valueOf(vcpu));
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.MEM), String.valueOf(mem));
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR), wdir);
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VNC_PORT),
                line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VNC_PORT)));
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.SSH_PORT),
                line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.SSH_PORT)));
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.LOGIN_USERNAME),
                line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.LOGIN_USERNAME)));
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.LOGIN_PASSWD),
                line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.LOGIN_PASSWD)));

        // write VM state as shutdown
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE), VMState.SHUTDOWN.toString());
        // write VM mode as undefined
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE), VMMode.NOT_DEFINED.toString());

        prop.store(
                new FileOutputStream(new File(
                        HypervisorCmdSimulator.cleanPath(wdir) + HypervisorCmdSimulator.VM_INFO_FILE_NAME)),
                "");

        // do other related settings
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }

        // success
        System.exit(0);

    } catch (ParseException e) {
        logger.error(String.format("Cannot parse input arguments: %s%n, expected:%n%s",
                StringUtils.join(args, " "), simulator.getUsage(100, "", 5, 5, "")));

        System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_INPUT_ARGS));
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        System.exit(ERROR_CODE.get(ERROR_STATE.IO_ERR));
    }
}

From source file:apps.classification.LearnSVMPerf.java

public static void main(String[] args) throws IOException {
    String cmdLineSyntax = LearnSVMPerf.class.getName()
            + " [OPTIONS] <path to svm_perf> <trainingIndexDirectory>";

    Options options = new Options();

    OptionBuilder.withArgName("c");
    OptionBuilder.withDescription("The c value for svm_perf (default 0.01)");
    OptionBuilder.withLongOpt("c");
    OptionBuilder.isRequired(false);//from   w  w w.j a va2s  .c  om
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("t");
    OptionBuilder.withDescription("Path for temporary files");
    OptionBuilder.withLongOpt("t");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("l");
    OptionBuilder.withDescription("The loss function to optimize (default 2):\n"
            + "               0  Zero/one loss: 1 if vector of predictions contains error, 0 otherwise.\n"
            + "               1  F1: 100 minus the F1-score in percent.\n"
            + "               2  Errorrate: Percentage of errors in prediction vector.\n"
            + "               3  Prec/Rec Breakeven: 100 minus PRBEP in percent.\n"
            + "               4  Prec@p: 100 minus precision at p in percent.\n"
            + "               5  Rec@p: 100 minus recall at p in percent.\n"
            + "               10  ROCArea: Percentage of swapped pos/neg pairs (i.e. 100 - ROCArea).");
    OptionBuilder.withLongOpt("l");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("w");
    OptionBuilder.withDescription("Choice of structural learning algorithm (default 9):\n"
            + "               0: n-slack algorithm described in [2]\n"
            + "               1: n-slack algorithm with shrinking heuristic\n"
            + "               2: 1-slack algorithm (primal) described in [5]\n"
            + "               3: 1-slack algorithm (dual) described in [5]\n"
            + "               4: 1-slack algorithm (dual) with constraint cache [5]\n"
            + "               9: custom algorithm in svm_struct_learn_custom.c");
    OptionBuilder.withLongOpt("w");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("p");
    OptionBuilder.withDescription("The value of p used by the prec@p and rec@p loss functions (default 0)");
    OptionBuilder.withLongOpt("p");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg();
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("v");
    OptionBuilder.withDescription("Verbose output");
    OptionBuilder.withLongOpt("v");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    OptionBuilder.withArgName("s");
    OptionBuilder.withDescription("Don't delete temporary training file in svm_perf format (default: delete)");
    OptionBuilder.withLongOpt("s");
    OptionBuilder.isRequired(false);
    OptionBuilder.hasArg(false);
    options.addOption(OptionBuilder.create());

    SvmPerfLearnerCustomizer classificationLearnerCustomizer = null;

    GnuParser parser = new GnuParser();
    String[] remainingArgs = null;
    try {
        CommandLine line = parser.parse(options, args);

        remainingArgs = line.getArgs();

        classificationLearnerCustomizer = new SvmPerfLearnerCustomizer(remainingArgs[0]);

        if (line.hasOption("c"))
            classificationLearnerCustomizer.setC(Float.parseFloat(line.getOptionValue("c")));

        if (line.hasOption("w"))
            classificationLearnerCustomizer.setW(Integer.parseInt(line.getOptionValue("w")));

        if (line.hasOption("p"))
            classificationLearnerCustomizer.setP(Integer.parseInt(line.getOptionValue("p")));

        if (line.hasOption("l"))
            classificationLearnerCustomizer.setL(Integer.parseInt(line.getOptionValue("l")));

        if (line.hasOption("v"))
            classificationLearnerCustomizer.printSvmPerfOutput(true);

        if (line.hasOption("s"))
            classificationLearnerCustomizer.setDeleteTrainingFiles(false);

        if (line.hasOption("t"))
            classificationLearnerCustomizer.setTempPath(line.getOptionValue("t"));

    } catch (Exception exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    if (remainingArgs.length != 2) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options);
        System.exit(-1);
    }

    String indexFile = remainingArgs[1];

    File file = new File(indexFile);

    String indexName = file.getName();
    String indexPath = file.getParent();

    // LEARNING
    SvmPerfLearner classificationLearner = new SvmPerfLearner();

    classificationLearner.setRuntimeCustomizer(classificationLearnerCustomizer);

    FileSystemStorageManager storageManager = new FileSystemStorageManager(indexPath, false);
    storageManager.open();
    IIndex training = TroveReadWriteHelper.readIndex(storageManager, indexName, TroveContentDBType.Full,
            TroveClassificationDBType.Full);
    storageManager.close();

    IClassifier classifier = classificationLearner.build(training);

    File executableFile = new File(classificationLearnerCustomizer.getSvmPerfLearnPath());
    SvmPerfDataManager dataManager = new SvmPerfDataManager(new SvmPerfClassifierCustomizer(
            executableFile.getParentFile().getAbsolutePath() + Os.pathSeparator() + "svm_perf_classify"));
    String description = "_SVMPerf_C-" + classificationLearnerCustomizer.getC() + "_W-"
            + classificationLearnerCustomizer.getW() + "_L-" + classificationLearnerCustomizer.getL();
    if (classificationLearnerCustomizer.getL() == 4 || classificationLearnerCustomizer.getL() == 5)
        description += "_P-" + classificationLearnerCustomizer.getP();
    if (classificationLearnerCustomizer.getAdditionalParameters().length() > 0)
        description += "_" + classificationLearnerCustomizer.getAdditionalParameters();

    storageManager = new FileSystemStorageManager(indexPath, false);
    storageManager.open();
    dataManager.write(storageManager, indexName + description, classifier);
    storageManager.close();
}

From source file:frankhassanabad.com.github.Jasperize.java

/**
 * Main method to call through Java in order to take a LinkedInProfile on disk and load it.
 *
 * @param args command line arguments where the options are stored
 * @throws FileNotFoundException Thrown if any file its expecting cannot be found.
 * @throws JRException  If there's generic overall Jasper issues.
 * @throws ParseException If there's command line parsing issues.
 *//*from   w  ww.ja  va2 s.c o  m*/
public static void main(String[] args) throws IOException, JRException, ParseException {

    Options options = new Options();
    options.addOption("h", "help", false, "Shows the help documentation");
    options.addOption("v", "version", false, "Shows the help documentation");
    options.addOption("cl", "coverLetter", false, "Utilizes a cover letter defined in coverletter.xml");
    options.addOption("sig", true, "Picture of your signature to add to the cover letter.");
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Jasperize [OPTIONS] [InputJrxmlFile] [OutputExportFile]", options);
        System.exit(0);
    }
    if (cmd.hasOption("v")) {
        System.out.println("Version:" + version);
        System.exit(0);
    }
    boolean useCoverLetter = cmd.hasOption("cl");
    String signatureLocation = cmd.getOptionValue("sig");
    BufferedImage signatureImage = null;
    if (signatureLocation != null) {
        signatureImage = ImageIO.read(new File(signatureLocation));
        ;
    }

    @SuppressWarnings("unchecked")
    List<String> arguments = cmd.getArgList();

    final String jrxmlFile;
    final String jasperOutput;
    if (arguments.size() == 2) {
        jrxmlFile = arguments.get(0);
        jasperOutput = arguments.get(1);
        System.out.println("*Detected* the command line arguments of:");
        System.out.println("    [InputjrxmlFile] " + jrxmlFile);
        System.out.println("    [OutputExportFile] " + jasperOutput);
    } else if (arguments.size() == 3) {
        jrxmlFile = arguments.get(1);
        jasperOutput = arguments.get(2);
        System.out.println("*Detected* the command line arguments of:");
        System.out.println("    [InputjrxmlFile] " + jrxmlFile);
        System.out.println("    [OutputExportFile] " + jasperOutput);
    } else {
        System.out.println("Using the default arguments of:");
        jrxmlFile = "data/jasperTemplates/resume1.jrxml";
        jasperOutput = "data/jasperOutput/linkedInResume.pdf";
        System.out.println("    [InputjrxmlFile] " + jrxmlFile);
        System.out.println("    [OutputExportFile] " + jasperOutput);
    }

    final String compiledMasterFile;
    final String outputType;
    final String jrPrintFile;
    //Split the inputFile
    final String[] inputSplit = jrxmlFile.split("\\.");
    if (inputSplit.length != 2 || !(inputSplit[1].equalsIgnoreCase("jrxml"))) {
        //Error
        System.out.println("Your [InputjrxmlFile] (1st argument) should have a jrxml extension like such:");
        System.out.println("    data/jasperTemplates/resume1.jrxml");
        System.exit(1);
    }
    //Split the outputFile
    final String[] outputSplit = jasperOutput.split("\\.");
    if (outputSplit.length != 2) {
        //Error
        System.out.println("Your [OutputExportFile] (2nd argument) should have a file extension like such:");
        System.out.println("    data/jasperOutput/linkedInResume.pdf");
        System.exit(1);
    }

    File inputFile = new File(inputSplit[0]);
    String inputFileName = inputFile.getName();
    String inputFileParentPath = inputFile.getParent();

    File outputFile = new File(outputSplit[0]);
    String outputFileParentPath = outputFile.getParent();

    System.out.println("Compiling report(s)");
    compileAllJrxmlTemplateFiles(inputFileParentPath, outputFileParentPath);
    System.out.println("Done compiling report(s)");

    compiledMasterFile = outputFileParentPath + File.separator + inputFileName + ".jasper";
    jrPrintFile = outputFileParentPath + File.separator + inputFileName + ".jrprint";

    System.out.println("Filling report: " + compiledMasterFile);
    Reporting.fill(compiledMasterFile, useCoverLetter, signatureImage);
    System.out.println("Done filling reports");
    outputType = outputSplit[1];
    System.out.println("Creating output export file of: " + jasperOutput);
    if (outputType.equalsIgnoreCase("pdf")) {
        Reporting.pdf(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("pptx")) {
        Reporting.pptx(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("docx")) {
        Reporting.docx(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("odt")) {
        Reporting.odt(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("xhtml")) {
        Reporting.xhtml(jrPrintFile, jasperOutput);
    }
    System.out.println("Done creating output export file of: " + jasperOutput);
}

From source file:gov.lanl.adore.djatoka.DjatokaCompress.java

/**
 * Uses apache commons cli to parse input args. Passes parsed
 * parameters to ICompress implementation.
 * @param args command line parameters to defined input,output,etc.
 *//*from   w w w  . jav a2  s.  c om*/
public static void main(String[] args) {
    // create the command line parser
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();
    options.addOption("i", "input", true, "Filepath of the input file or dir.");
    options.addOption("o", "output", true, "Filepath of the output file or dir.");
    options.addOption("r", "rate", true, "Absolute Compression Ratio");
    options.addOption("s", "slope", true,
            "Used to generate relative compression ratio based on content characteristics.");
    options.addOption("y", "Clayers", true, "Number of quality levels.");
    options.addOption("l", "Clevels", true, "Number of DWT levels (reolution levels).");
    options.addOption("v", "Creversible", true, "Use Reversible Wavelet");
    options.addOption("c", "Cprecincts", true, "Precinct dimensions");
    options.addOption("p", "props", true, "Compression Properties File");
    options.addOption("d", "Corder", true, "Progression order");
    options.addOption("g", "ORGgen_plt", true, "Enables insertion of packet length information in the header");
    options.addOption("t", "ORGtparts", true, "Division of each tile's packets into tile-parts");
    options.addOption("b", "Cblk", true, "Codeblock Size");
    options.addOption("a", "AltImpl", true, "Alternate ICompress Implemenation");

    try {
        if (args.length == 0) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("gov.lanl.adore.djatoka.DjatokaCompress", options);
            System.exit(0);
        }

        // parse the command line arguments
        CommandLine line = parser.parse(options, args);
        String input = line.getOptionValue("i");
        String output = line.getOptionValue("o");

        String propsFile = line.getOptionValue("p");
        DjatokaEncodeParam p;
        if (propsFile != null) {
            Properties props = IOUtils.loadConfigByPath(propsFile);
            p = new DjatokaEncodeParam(props);
        } else
            p = new DjatokaEncodeParam();
        String rate = line.getOptionValue("r");
        if (rate != null)
            p.setRate(rate);
        String slope = line.getOptionValue("s");
        if (slope != null)
            p.setSlope(slope);
        String Clayers = line.getOptionValue("y");
        if (Clayers != null)
            p.setLayers(Integer.parseInt(Clayers));
        String Clevels = line.getOptionValue("l");
        if (Clevels != null)
            p.setLevels(Integer.parseInt(Clevels));
        String Creversible = line.getOptionValue("v");
        if (Creversible != null)
            p.setUseReversible(Boolean.parseBoolean(Creversible));
        String Cprecincts = line.getOptionValue("c");
        if (Cprecincts != null)
            p.setPrecincts(Cprecincts);
        String Corder = line.getOptionValue("d");
        if (Corder != null)
            p.setProgressionOrder(Corder);
        String ORGgen_plt = line.getOptionValue("g");
        if (ORGgen_plt != null)
            p.setInsertPLT(Boolean.parseBoolean(ORGgen_plt));
        String Cblk = line.getOptionValue("b");
        if (Cblk != null)
            p.setCodeBlockSize(Cblk);
        String alt = line.getOptionValue("a");

        ICompress jp2 = new KduCompressExe();
        if (alt != null)
            jp2 = (ICompress) Class.forName(alt).newInstance();
        if (new File(input).isDirectory() && new File(output).isDirectory()) {
            ArrayList<File> files = IOUtils.getFileList(input, new SourceImageFileFilter(), false);
            for (File f : files) {
                long x = System.currentTimeMillis();
                File outFile = new File(output, f.getName().substring(0, f.getName().indexOf(".")) + ".jp2");
                compress(jp2, f.getAbsolutePath(), outFile.getAbsolutePath(), p);
                report(f.getAbsolutePath(), x);
            }
        } else {
            long x = System.currentTimeMillis();
            File f = new File(input);
            if (output == null)
                output = f.getName().substring(0, f.getName().indexOf(".")) + ".jp2";
            if (new File(output).isDirectory())
                output = output + f.getName().substring(0, f.getName().indexOf(".")) + ".jp2";
            compress(jp2, input, output, p);
            report(input, x);
        }
    } catch (ParseException e) {
        logger.error("Parse exception:" + e.getMessage(), e);
    } catch (DjatokaException e) {
        logger.error("djatoka Compression exception:" + e.getMessage(), e);
    } catch (InstantiationException e) {
        logger.error("Unable to initialize alternate implemenation:" + e.getMessage(), e);
    } catch (Exception e) {
        logger.error("An exception occured:" + e.getMessage(), e);
    }
}

From source file:FileSample.java

public static void main(String args[]) {
    JFrame frame = new JFrame("JFileChooser Popup");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container contentPane = frame.getContentPane();

    final JLabel directoryLabel = new JLabel();
    contentPane.add(directoryLabel, BorderLayout.NORTH);

    final JLabel filenameLabel = new JLabel();
    contentPane.add(filenameLabel, BorderLayout.SOUTH);

    final JButton button = new JButton("Open FileChooser");
    ActionListener actionListener = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            Component parent = (Component) actionEvent.getSource();
            JFileChooser fileChooser = new JFileChooser(".");
            fileChooser.setAccessory(new LabelAccessory(fileChooser));
            FileView view = new JavaFileView();
            fileChooser.setFileView(view);
            int status = fileChooser.showOpenDialog(parent);
            if (status == JFileChooser.APPROVE_OPTION) {
                File selectedFile = fileChooser.getSelectedFile();
                directoryLabel.setText(selectedFile.getParent());
                filenameLabel.setText(selectedFile.getName());
            } else if (status == JFileChooser.CANCEL_OPTION) {
                directoryLabel.setText(" ");
                filenameLabel.setText(" ");
            }//from   ww w .  j a  v a  2s.com
        }
    };
    button.addActionListener(actionListener);
    contentPane.add(button, BorderLayout.CENTER);

    frame.setSize(300, 200);
    frame.setVisible(true);
}

From source file:eu.scape_project.cdx_creator.CDXCreator.java

/**
 * Main entry point.// w  w  w . j  a  v  a 2 s  . c  o m
 *
 * @param args
 * @throws java.io.IOException
 * @throws org.apache.commons.cli.ParseException
 */
public static void main(String[] args) throws IOException, ParseException {
    Configuration conf = new Configuration();
    // Command line interface
    config = new CDXCreatorConfig();
    CommandLineParser cmdParser = new PosixParser();
    GenericOptionsParser gop = new GenericOptionsParser(conf, args);
    CDXCreatorOptions cdxCreatorOpts = new CDXCreatorOptions();
    CommandLine cmd = cmdParser.parse(cdxCreatorOpts.options, gop.getRemainingArgs());
    if ((args.length == 0) || (cmd.hasOption(cdxCreatorOpts.HELP_OPT))) {
        cdxCreatorOpts.exit("Help", 0);
    } else {
        cdxCreatorOpts.initOptions(cmd, config);
    }

    // configuration properties
    if (config.getPropertiesFilePath() != null) {
        pu = new PropertyUtil(config.getPropertiesFilePath(), true);
    } else {
        pu = new PropertyUtil("/eu/scape_project/cdx_creator/config.properties", false);
    }

    config.setCdxfileCsColumns(pu.getProp("cdxfile.cscolumns"));
    config.setCdxfileCsHeader(pu.getProp("cdxfile.csheader"));

    CDXCreator cdxCreator = new CDXCreator();

    File input = new File(config.getInputStr());

    if (input.isDirectory()) {
        config.setDirectoryInput(true);
        cdxCreator.traverseDir(input);
    } else {
        CDXCreationTask cdxCreationTask = new CDXCreationTask(config, input, input.getName());
        cdxCreationTask.createIndex();
    }

    System.exit(0);
}

From source file:MainClass.java

public static void main(String[] args) {
    File myDir = new File("C:/");
    // Define a filter for java source files beginning with F
    FilenameFilter select = new FileListFilter("F", "java");

    File[] contents = myDir.listFiles(select);

    if (contents != null) {
        System.out.println(//from  w ww  . j  a v  a 2s .c o m
                "\nThe " + contents.length + " matching items in the directory, " + myDir.getName() + ", are:");
        for (File file : contents) {
            System.out.println(file + " is a " + (file.isDirectory() ? "directory" : "file")
                    + " last modified on\n" + new Date(file.lastModified()));
        }
    } else {
        System.out.println(myDir.getName() + " is not a directory");
    }
    return;
}

From source file:net.sf.jodreports.cli.CreateDocument.java

public static void main(String[] args) throws Exception {
    if (args.length < 3) {
        System.err.println("USAGE: " + CreateDocument.class.getName()
                + " <template-document> <data-file> <output-document>");
        System.exit(0);/*from  w w  w .  jav  a  2s .  com*/
    }
    File templateFile = new File(args[0]);
    File dataFile = new File(args[1]);
    File outputFile = new File(args[2]);

    DocumentTemplateFactory documentTemplateFactory = new DocumentTemplateFactory();
    DocumentTemplate template = documentTemplateFactory.getTemplate(templateFile);

    Object model = null;
    String dataFileExtension = FilenameUtils.getExtension(dataFile.getName());
    if (dataFileExtension.equals("xml")) {
        model = NodeModel.parse(dataFile);
    } else if (dataFileExtension.equals("properties")) {
        Properties properties = new Properties();
        properties.load(new FileInputStream(dataFile));
        model = properties;
    } else {
        throw new IllegalArgumentException(
                "data file must be 'xml' or 'properties'; unsupported type: " + dataFileExtension);
    }

    template.createDocument(model, new FileOutputStream(outputFile));
}

From source file:App.App.java

public static void main(String[] args) throws IOException {
    File inFile = new File("C:\\Data\\LogTest.java");
    FileInputStream fis = new FileInputStream(inFile);
    DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
    HttpPost httppost = new HttpPost("http://localhost:8080/rest_j2ee/rest/files/upload");
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("file", new InputStreamBody(fis, inFile.getName()));
    httppost.setEntity(entity);/*  w ww.  j  ava2  s.c  om*/
    HttpResponse response = httpclient.execute(httppost);
    int statusCode = response.getStatusLine().getStatusCode();
    HttpEntity responseEntity = response.getEntity();
    String responseString = EntityUtils.toString(responseEntity, "UTF-8");
    System.out.println("[" + statusCode + "] " + responseString);
}

From source file:com.nohowdezign.gcpmanager.Main.java

public final static void main(String[] args) {
    //Remove old log, it does not need to be there anymore.
    File oldLog = new File("./CloudPrintManager.log");

    if (oldLog.exists()) {
        oldLog.delete();//from   ww w  .j  av a2 s. c o  m
    }

    //Create a file reader for the props file
    Reader propsStream = null;
    try {
        propsStream = new FileReader("./props.json");
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    }

    PrintManagerProperties props = null;
    if (propsStream != null) {
        props = gson.fromJson(propsStream, PrintManagerProperties.class);
    } else {
        logger.error("Property file does not exist. Please create one.");
    }

    //Set the variables to what is in the props file
    String email = props.getEmail();
    String password = props.getPassword();
    String printerId = props.getPrinterId();
    amountOfPagesPerPrintJob = props.getAmountOfPagesPerPrintJob();
    timeRestraintsForPrinter = props.getTimeRestraintsForPrinter();

    JobStorageManager.timeToKeepFileInDays = props.getTimeToKeepFileInDays();

    //AuthenticationManager authenticationManager = new AuthenticationManager();
    //authenticationManager.setPasswordToUse(props.getAdministrativePassword());
    //authenticationManager.initialize(1337); //Start the authentication manager on port 1337

    try {
        cloudPrint.connect(email, password, "cloudprintmanager-1.0");
    } catch (CloudPrintAuthenticationException e) {
        logger.error(e.getMessage());
    }

    //TODO: Get a working website ready
    //Thread adminConsole = new Thread(new HttpServer(80), "HttpServer");
    //adminConsole.start();

    Thread printJobManager = new Thread(new JobStorageManagerThread(), "JobStorageManager");
    printJobManager.start();

    try {
        if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
            logger.error("Your operating system is not supported. Please switch to linux ya noob.");
            System.exit(1);
        } else {
            PrinterManager printerManager = new PrinterManager(cloudPrint);

            File cupsPrinterDir = new File("/etc/cups/ppd");

            if (cupsPrinterDir.isDirectory() && cupsPrinterDir.canRead()) {
                for (File cupsPrinterPPD : cupsPrinterDir.listFiles()) {
                    //Init all of the CUPS printers in the manager
                    printerManager.initializePrinter(cupsPrinterPPD, cupsPrinterPPD.getName());
                }
            } else {
                logger.error("Please run this with a higher access level.");
                System.exit(1);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    while (true) {
        try {
            getPrintingJobs(printerId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}