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:org.objectrepository.MessageConsumerDaemon.java

/**
 * main//from   ww  w  . j a  va 2  s  .  com
 * <p/>
 * Accepts one folder as argument:  -messageQueues
 * That folder ought to contain one or more folders ( or symbolic links ) to the files
 * The folder has the format: [foldername] or [foldername].[maxTasks]
 * MaxTasks is to indicate the total number of jobs being able to run.
 *
 * long
 *
 * @param argv
 */
public static void main(String[] argv) {

    if (instance == null) {
        final Properties properties = new Properties();

        if (argv.length > 0) {
            for (int i = 0; i < argv.length; i += 2) {
                try {
                    properties.put(argv[i], argv[i + 1]);
                } catch (ArrayIndexOutOfBoundsException arr) {
                    System.out.println("Missing value after parameter " + argv[i]);
                    System.exit(-1);
                }
            }
        } else {
            log.fatal("Usage: pmq-agent.jar -messageQueues [queues] -heartbeatInterval [interval in ms]\n"
                    + "The queues is a folder that contains symbolic links to the startup scripts.");
            System.exit(-1);
        }

        if (log.isInfoEnabled()) {
            log.info("Arguments set: ");
            for (String key : properties.stringPropertyNames()) {
                log.info("'" + key + "'='" + properties.getProperty(key) + "'");
            }
        }

        if (!properties.containsKey("-messageQueues")) {
            log.fatal("Expected case sensitive parameter: -messageQueues");
            System.exit(-1);
        }

        final File messageQueues = new File((String) properties.get("-messageQueues"));
        if (!messageQueues.exists()) {
            log.fatal("Cannot find folder for messageQueues: " + messageQueues.getAbsolutePath());
            System.exit(-1);
        }

        if (messageQueues.isFile()) {
            log.fatal(
                    "-messageQueues should point to a folder, not a file: " + messageQueues.getAbsolutePath());
            System.exit(-1);
        }

        long heartbeatInterval = 600000;
        if (properties.containsKey("-heartbeatInterval")) {
            heartbeatInterval = Long.parseLong((String) properties.get("heartbeatInterval"));
        }

        String identifier = null;
        if (properties.containsKey("-id")) {
            identifier = (String) properties.get("-id");
        } else if (properties.containsKey("-identifier")) {
            identifier = (String) properties.get("-identifier");
        }

        final File[] files = messageQueues.listFiles();
        final String[] scriptNames = (properties.containsKey("-startup"))
                ? new String[] { properties.getProperty("-startup") }
                : new String[] { "/startup.sh", "\\startup.bat" };
        final List<Queue> queues = new ArrayList<Queue>();
        for (File file : files) {
            final String name = file.getName();
            final String[] split = name.split("\\.", 2);
            final String queueName = split[0];
            for (String scriptName : scriptNames) {
                final String shellScript = file.getAbsolutePath() + scriptName;
                final int maxTask = (split.length == 1) ? 1 : Integer.parseInt(split[1]);
                log.info("Candidate mq client for " + queueName + " maxTasks " + maxTask);
                if (new File(shellScript).exists()) {
                    final Queue queue = new Queue(queueName, shellScript, false);
                    queue.setCorePoolSize(1);
                    queue.setMaxPoolSize(maxTask);
                    queue.setQueueCapacity(1);
                    queues.add(queue);
                    break;
                } else {
                    log.warn("... skipping, because no startup script found at " + shellScript);
                }
            }
        }

        if (queues.size() == 0) {
            log.fatal("No queue folders seen in " + messageQueues.getAbsolutePath());
            System.exit(-1);
        }

        // Add the system queue
        queues.add(new Queue("Connection", null, true));

        getInstance(queues, identifier, heartbeatInterval).run();
    }
    System.exit(0);
}

From source file:com.twentyn.patentScorer.ScoreMerger.java

public static void main(String[] args) throws Exception {
    System.out.println("Starting up...");
    System.out.flush();//from ww w. j a v a2 s  .c om
    Options opts = new Options();
    opts.addOption(Option.builder("h").longOpt("help").desc("Print this help message and exit").build());

    opts.addOption(Option.builder("r").longOpt("results").required().hasArg()
            .desc("A directory of search results to read").build());
    opts.addOption(Option.builder("s").longOpt("scores").required().hasArg()
            .desc("A directory of patent classification scores to read").build());
    opts.addOption(Option.builder("o").longOpt("output").required().hasArg()
            .desc("The output file where results will be written.").build());

    HelpFormatter helpFormatter = new HelpFormatter();
    CommandLineParser cmdLineParser = new DefaultParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = cmdLineParser.parse(opts, args);
    } catch (ParseException e) {
        System.out.println("Caught exception when parsing command line: " + e.getMessage());
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(1);
    }

    if (cmdLine.hasOption("help")) {
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(0);
    }
    File scoresDirectory = new File(cmdLine.getOptionValue("scores"));
    if (cmdLine.getOptionValue("scores") == null || !scoresDirectory.isDirectory()) {
        LOGGER.error("Not a directory of score files: " + cmdLine.getOptionValue("scores"));
    }

    File resultsDirectory = new File(cmdLine.getOptionValue("results"));
    if (cmdLine.getOptionValue("results") == null || !resultsDirectory.isDirectory()) {
        LOGGER.error("Not a directory of results files: " + cmdLine.getOptionValue("results"));
    }

    FileWriter outputWriter = new FileWriter(cmdLine.getOptionValue("output"));

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

    FilenameFilter jsonFilter = new FilenameFilter() {
        public final Pattern JSON_PATTERN = Pattern.compile("\\.json$");

        public boolean accept(File dir, String name) {
            return JSON_PATTERN.matcher(name).find();
        }
    };

    Map<String, PatentScorer.ClassificationResult> scores = new HashMap<>();
    LOGGER.info("Reading scores from directory at " + scoresDirectory.getAbsolutePath());
    for (File scoreFile : scoresDirectory.listFiles(jsonFilter)) {
        BufferedReader reader = new BufferedReader(new FileReader(scoreFile));
        int count = 0;
        String line;
        while ((line = reader.readLine()) != null) {
            PatentScorer.ClassificationResult res = objectMapper.readValue(line,
                    PatentScorer.ClassificationResult.class);
            scores.put(res.docId, res);
            count++;
        }
        LOGGER.info("Read " + count + " scores from " + scoreFile.getAbsolutePath());
    }

    Map<String, List<DocumentSearch.SearchResult>> synonymsToResults = new HashMap<>();
    Map<String, List<DocumentSearch.SearchResult>> inchisToResults = new HashMap<>();
    LOGGER.info("Reading results from directory at " + resultsDirectory);
    // With help from http://stackoverflow.com/questions/6846244/jackson-and-generic-type-reference.
    JavaType resultsType = objectMapper.getTypeFactory().constructCollectionType(List.class,
            DocumentSearch.SearchResult.class);

    List<File> resultsFiles = Arrays.asList(resultsDirectory.listFiles(jsonFilter));
    Collections.sort(resultsFiles, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });
    for (File resultsFile : resultsFiles) {
        BufferedReader reader = new BufferedReader(new FileReader(resultsFile));
        CharBuffer buffer = CharBuffer.allocate(Long.valueOf(resultsFile.length()).intValue());
        int bytesRead = reader.read(buffer);
        LOGGER.info("Read " + bytesRead + " bytes from " + resultsFile.getName() + " (length is "
                + resultsFile.length() + ")");
        List<DocumentSearch.SearchResult> results = objectMapper.readValue(new CharArrayReader(buffer.array()),
                resultsType);

        LOGGER.info("Read " + results.size() + " results from " + resultsFile.getAbsolutePath());

        int count = 0;
        for (DocumentSearch.SearchResult sres : results) {
            for (DocumentSearch.ResultDocument resDoc : sres.getResults()) {
                String docId = resDoc.getDocId();
                PatentScorer.ClassificationResult classificationResult = scores.get(docId);
                if (classificationResult == null) {
                    LOGGER.warn("No classification result found for " + docId);
                } else {
                    resDoc.setClassifierScore(classificationResult.getScore());
                }
            }
            if (!synonymsToResults.containsKey(sres.getSynonym())) {
                synonymsToResults.put(sres.getSynonym(), new ArrayList<DocumentSearch.SearchResult>());
            }
            synonymsToResults.get(sres.getSynonym()).add(sres);
            count++;
            if (count % 1000 == 0) {
                LOGGER.info("Processed " + count + " search result documents");
            }
        }
    }

    Comparator<DocumentSearch.ResultDocument> resultDocumentComparator = new Comparator<DocumentSearch.ResultDocument>() {
        @Override
        public int compare(DocumentSearch.ResultDocument o1, DocumentSearch.ResultDocument o2) {
            int cmp = o2.getClassifierScore().compareTo(o1.getClassifierScore());
            if (cmp != 0) {
                return cmp;
            }
            cmp = o2.getScore().compareTo(o1.getScore());
            return cmp;
        }
    };

    for (Map.Entry<String, List<DocumentSearch.SearchResult>> entry : synonymsToResults.entrySet()) {
        DocumentSearch.SearchResult newSearchRes = null;
        // Merge all result documents into a single search result.
        for (DocumentSearch.SearchResult sr : entry.getValue()) {
            if (newSearchRes == null) {
                newSearchRes = sr;
            } else {
                newSearchRes.getResults().addAll(sr.getResults());
            }
        }
        if (newSearchRes == null || newSearchRes.getResults() == null) {
            LOGGER.error("Search results for " + entry.getKey() + " are null.");
            continue;
        }
        Collections.sort(newSearchRes.getResults(), resultDocumentComparator);
        if (!inchisToResults.containsKey(newSearchRes.getInchi())) {
            inchisToResults.put(newSearchRes.getInchi(), new ArrayList<DocumentSearch.SearchResult>());
        }
        inchisToResults.get(newSearchRes.getInchi()).add(newSearchRes);
    }

    List<String> sortedKeys = new ArrayList<String>(inchisToResults.keySet());
    Collections.sort(sortedKeys);
    List<GroupedInchiResults> orderedResults = new ArrayList<>(sortedKeys.size());
    Comparator<DocumentSearch.SearchResult> synonymSorter = new Comparator<DocumentSearch.SearchResult>() {
        @Override
        public int compare(DocumentSearch.SearchResult o1, DocumentSearch.SearchResult o2) {
            return o1.getSynonym().compareTo(o2.getSynonym());
        }
    };
    for (String inchi : sortedKeys) {
        List<DocumentSearch.SearchResult> res = inchisToResults.get(inchi);
        Collections.sort(res, synonymSorter);
        orderedResults.add(new GroupedInchiResults(inchi, res));
    }

    objectMapper.writerWithView(Object.class).writeValue(outputWriter, orderedResults);
    outputWriter.close();
}

From source file:de.fatalix.book.importer.CalibriImporter.java

public static void main(String[] args) throws IOException, URISyntaxException, SolrServerException {
    Gson gson = new Gson();
    CalibriImporterConfiguration config = gson.fromJson(args[0], CalibriImporterConfiguration.class);
    File importFolder = new File(config.getImportFolder());
    if (importFolder.isDirectory()) {
        File[] zipFiles = importFolder.listFiles(new FilenameFilter() {

            @Override//from   w w  w. j av  a2  s.  c o m
            public boolean accept(File dir, String name) {
                return name.endsWith(".zip");
            }
        });
        for (File zipFile : zipFiles) {
            try {
                processBooks(zipFile.toPath(), config.getSolrCore(), config.getSolrCore(),
                        config.getBatchSize());
                System.out.println("Processed file " + zipFile.getName());
            } catch (IOException ex) {
                ex.printStackTrace();

            }
        }
    } else {
        System.out.println("Import folder: " + importFolder.getAbsolutePath() + " cannot be read!");
    }
}

From source file:grnet.validation.XMLValidation.java

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method ssstub

    Enviroment enviroment = new Enviroment(args[0]);

    if (enviroment.envCreation) {
        String schemaUrl = enviroment.getArguments().getSchemaURL();
        Core core = new Core(schemaUrl);

        XMLSource source = new XMLSource(args[0]);

        File sourceFile = source.getSource();

        if (sourceFile.exists()) {

            Collection<File> xmls = source.getXMLs();

            System.out.println("Validating repository:" + sourceFile.getName());

            System.out.println("Number of files to validate:" + xmls.size());

            Iterator<File> iterator = xmls.iterator();

            System.out.println("Validating against schema:" + schemaUrl + "...");

            ValidationReport report = null;
            if (enviroment.getArguments().createReport().equalsIgnoreCase("true")) {

                report = new ValidationReport(enviroment.getArguments().getDestFolderLocation(),
                        enviroment.getDataProviderValid().getName());

            }/*from  www. ja v  a 2s .  c om*/

            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost(enviroment.getArguments().getQueueHost());
            factory.setUsername(enviroment.getArguments().getQueueUserName());
            factory.setPassword(enviroment.getArguments().getQueuePassword());

            while (iterator.hasNext()) {

                StringBuffer logString = new StringBuffer();
                logString.append(sourceFile.getName());
                logString.append(" " + schemaUrl);

                File xmlFile = iterator.next();
                String name = xmlFile.getName();
                name = name.substring(0, name.indexOf(".xml"));

                logString.append(" " + name);

                boolean xmlIsValid = core.validateXMLSchema(xmlFile);

                if (xmlIsValid) {
                    logString.append(" " + "Valid");
                    slf4jLogger.info(logString.toString());

                    Connection connection = factory.newConnection();
                    Channel channel = connection.createChannel();
                    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

                    channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes());
                    channel.close();
                    connection.close();
                    try {
                        if (report != null) {

                            report.raiseValidFilesNum();
                        }

                        FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderValid());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    logString.append(" " + "Invalid");
                    slf4jLogger.info(logString.toString());

                    Connection connection = factory.newConnection();
                    Channel channel = connection.createChannel();
                    channel.queueDeclare(QUEUE_NAME, false, false, false, null);

                    channel.basicPublish("", QUEUE_NAME, null, logString.toString().getBytes());
                    channel.close();
                    connection.close();

                    try {
                        if (report != null) {

                            if (enviroment.getArguments().extendedReport().equalsIgnoreCase("true"))
                                report.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.invalidData,
                                        core.getReason());

                            report.raiseInvalidFilesNum();
                        }
                        FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderInValid());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

            if (report != null) {
                report.writeErrorBank(core.getErrorBank());
                report.appendGeneralInfo();
            }
            System.out.println("Validation is done.");

        }

    }
}

From source file:gda.util.PackageMaker.java

/**
 * @param args//from   w  ww . j a v a  2  s.  co m
 */
public static void main(String args[]) {
    String destDir = null;
    if (args.length == 0)
        return;
    String filename = args[0];
    if (args.length > 1)
        destDir = args[1];
    try {
        ClassParser cp = new ClassParser(filename);
        JavaClass classfile = cp.parse();
        String packageName = classfile.getPackageName();
        String apackageName = packageName.replace(".", File.separator);
        if (destDir != null)
            destDir = destDir + File.separator + apackageName;
        else
            destDir = apackageName;
        File destFile = new File(destDir);
        File existFile = new File(filename);
        File parentDir = new File(existFile.getAbsolutePath().substring(0,
                existFile.getAbsolutePath().lastIndexOf(File.separator)));
        String allFiles[] = parentDir.list();
        Vector<String> selectedFiles = new Vector<String>();
        String toMatch = existFile.getName().substring(0, existFile.getName().lastIndexOf("."));
        for (int i = 0; i < allFiles.length; i++) {
            if (allFiles[i].startsWith(toMatch + "$"))
                selectedFiles.add(allFiles[i]);
        }
        FileUtils.copyFileToDirectory(existFile, destFile);
        Object[] filestoCopy = selectedFiles.toArray();
        for (int i = 0; i < filestoCopy.length; i++) {
            FileUtils.copyFileToDirectory(new File((String) filestoCopy[i]), destFile);
        }
    }

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

From source file:ViewImageTest.java

/**
 * Test image(s) (default : JPEG_example_JPG_RIP_100.jpg) are parsed and
 * rendered to an output foler. Result can then be checked with program of
 * your choice./* w  ww  .j  av  a  2 s .  c o  m*/
 * 
 * @param args
 *            may be empty or contain parameters to override defaults :
 *            <ul>
 *            <li>args[0] : input image file URL or folder containing image
 *            files URL. Default :
 *            viewImageTest/test/JPEG_example_JPG_RIP_100.jpg</li>
 *            <li>args[1] : output format name (for example : "jpg") for
 *            rendered image</li>
 *            <li>args[2] : ouput folder URL</li>
 *            <li>args[3] : max width (in pixels) for rendered image.
 *            Default : no value.</li>
 *            <li>args[4] : max height (in pixels) for rendered image.
 *            Default : no value.</li>
 *            </ul>
 * @throws IOException
 *             when a read/write error occured
 */
public static void main(String args[]) throws IOException {
    File inURL = getInputURL(args);
    String ext = getEncodingExt(args);
    File outDir = getOuputDir(args);
    serverObjects post = makePostParams(args);
    outDir.mkdirs();

    File[] inFiles;
    if (inURL.isFile()) {
        inFiles = new File[1];
        inFiles[0] = inURL;
        System.out.println("Testing ViewImage rendering with input file : " + inURL.getAbsolutePath()
                + " encoded To : " + ext);
    } else if (inURL.isDirectory()) {
        FileFilter filter = FileFileFilter.FILE;
        inFiles = inURL.listFiles(filter);
        System.out.println("Testing ViewImage rendering with input files in folder : " + inURL.getAbsolutePath()
                + " encoded To : " + ext);
    } else {
        inFiles = new File[0];
    }
    if (inFiles.length == 0) {
        throw new IllegalArgumentException(inURL.getAbsolutePath() + " is not a valid file or folder url.");
    }
    System.out.println("Rendered images will be written in dir : " + outDir.getAbsolutePath());

    Map<String, Exception> failures = new HashMap<String, Exception>();
    try {
        for (File inFile : inFiles) {
            /* Delete eventual previous result file */
            File outFile = new File(outDir, inFile.getName() + "." + ext);
            if (outFile.exists()) {
                outFile.delete();
            }

            byte[] resourceb = getBytes(inFile);
            String urlString = inFile.getAbsolutePath();
            EncodedImage img = null;
            Exception error = null;
            try {
                img = ViewImage.parseAndScale(post, true, urlString, ext, false, resourceb);
            } catch (Exception e) {
                error = e;
            }

            if (img == null) {
                failures.put(urlString, error);
            } else {
                FileOutputStream outFileStream = null;
                try {
                    outFileStream = new FileOutputStream(outFile);
                    img.getImage().writeTo(outFileStream);
                } finally {
                    if (outFileStream != null) {
                        outFileStream.close();
                    }
                    img.getImage().close();
                }
            }
        }
        displayResults(inFiles, failures);
    } finally {
        ConcurrentLog.shutdown();
    }

}

From source file:edu.ucla.cs.scai.swim.qa.ontology.dbpedia.tipicality.Test.java

public static void main(String[] args) throws IOException, ClassNotFoundException {
    String path = DBpediaOntology.DBPEDIA_CSV_FOLDER;
    if (args != null && args.length > 0) {
        path = args[0];// ww  w .jav a 2 s  .c  o m
        if (!path.endsWith("/")) {
            path = path + "/";
        }
    }

    stopAttributes.add("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
    stopAttributes.add("http://www.w3.org/2002/07/owl#sameAs");
    stopAttributes.add("http://dbpedia.org/ontology/wikiPageRevisionID");
    stopAttributes.add("http://dbpedia.org/ontology/wikiPageID");
    stopAttributes.add("http://purl.org/dc/elements/1.1/description");
    stopAttributes.add("http://dbpedia.org/ontology/thumbnail");
    stopAttributes.add("http://dbpedia.org/ontology/type");

    try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path + "counts.bin"))) {
        categories = (HashSet<String>) ois.readObject();
        attributes = (HashSet<String>) ois.readObject();
        categoryCount = (HashMap<String, Integer>) ois.readObject();
        attributeCount = (HashMap<String, Integer>) ois.readObject();
        categoryAttributeCount = (HashMap<String, HashMap<String, Integer>>) ois.readObject();
        attributeCategoryCount = (HashMap<String, HashMap<String, Integer>>) ois.readObject();
    }

    System.out.println(categories.size() + " categories found");
    System.out.println(attributes.size() + " attributes found");

    n = 0;
    for (Map.Entry<String, Integer> e : categoryCount.entrySet()) {
        n += e.getValue();
    }

    System.out.println(n);

    HashMap<String, ArrayList<Pair>> sortedCategoryAttributes = new HashMap<>();

    for (String category : categories) {
        //System.out.println(category);
        //System.out.println("-----------");
        ArrayList<Pair> attributesRank = new ArrayList<Pair>();
        Integer c = categoryCount.get(category);
        if (c == null || c == 0) {
            continue;
        }
        HashMap<String, Integer> thisCategoryAttributeCount = categoryAttributeCount.get(category);
        for (Map.Entry<String, Integer> e : thisCategoryAttributeCount.entrySet()) {
            attributesRank.add(new Pair(e.getKey(), 1.0 * e.getValue() / c));
        }
        Collections.sort(attributesRank);
        for (Pair p : attributesRank) {
            //System.out.println("A:" + p.getS() + "\t" + p.getP());
        }
        //System.out.println("===============================");
        sortedCategoryAttributes.put(category, attributesRank);
    }

    for (String attribute : attributes) {
        //System.out.println(attribute);
        //System.out.println("-----------");
        ArrayList<Pair> categoriesRank = new ArrayList<>();
        Integer a = attributeCount.get(attribute);
        if (a == null || a == 0) {
            continue;
        }
        HashMap<String, Integer> thisAttributeCategoryCount = attributeCategoryCount.get(attribute);
        for (Map.Entry<String, Integer> e : thisAttributeCategoryCount.entrySet()) {
            categoriesRank.add(new Pair(e.getKey(), 1.0 * e.getValue() / a));
        }
        Collections.sort(categoriesRank);
        for (Pair p : categoriesRank) {
            //System.out.println("C:" + p.getS() + "\t" + p.getP());
        }
        //System.out.println("===============================");
    }

    HashMap<Integer, Integer> histogram = new HashMap<>();
    histogram.put(0, 0);
    histogram.put(1, 0);
    histogram.put(2, 0);
    histogram.put(Integer.MAX_VALUE, 0);

    int nTest = 0;

    if (args != null && args.length > 0) {
        path = args[0];
        if (!path.endsWith("/")) {
            path = path + "/";
        }
    }

    for (File f : new File(path).listFiles()) {
        if (f.isFile() && f.getName().endsWith(".csv")) {
            String category = f.getName().replaceFirst("\\.csv", "");
            System.out.println("Category: " + category);
            ArrayList<HashSet<String>> entities = extractEntities(f, 2);
            for (HashSet<String> attributesOfThisEntity : entities) {
                nTest++;
                ArrayList<String> rankedCategories = rankedCategories(attributesOfThisEntity);
                boolean found = false;
                for (int i = 0; i < rankedCategories.size() && !found; i++) {
                    if (rankedCategories.get(i).equals(category)) {
                        Integer count = histogram.get(i);
                        if (count == null) {
                            histogram.put(i, 1);
                        } else {
                            histogram.put(i, count + 1);
                        }
                        found = true;
                    }
                }
                if (!found) {
                    histogram.put(Integer.MAX_VALUE, histogram.get(Integer.MAX_VALUE) + 1);
                }
            }
            System.out.println("Tested entities: " + nTest);
            System.out.println("1: " + histogram.get(0));
            System.out.println("2: " + histogram.get(1));
            System.out.println("3: " + histogram.get(2));
            System.out.println("+3: " + (nTest - histogram.get(2) - histogram.get(1) - histogram.get(0)
                    - histogram.get(Integer.MAX_VALUE)));
            System.out.println("NF: " + histogram.get(Integer.MAX_VALUE));
        }
    }
}

From source file:FilterSample.java

public static void main(String args[]) {
    JFrame frame = new JFrame("JFileChooser Filter 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));
            FileFilter filter1 = new ExtensionFileFilter(null, new String[] { "JPG", "JPEG" });
            //        fileChooser.setFileFilter(filter1);
            fileChooser.addChoosableFileFilter(filter1);
            FileFilter filter2 = new ExtensionFileFilter("gif", new String[] { "gif" });
            fileChooser.addChoosableFileFilter(filter2);
            fileChooser.setFileView(new JavaFileView());
            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 w ww  .  j  a v  a 2  s  .  co m
        }
    };
    button.addActionListener(actionListener);
    contentPane.add(button, BorderLayout.CENTER);

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

From source file:Main.java

public static void main(String[] argv) throws Exception {
    File file = new File("myimage.gif");
    FileInputStream fis = new FileInputStream(file);
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@//server.local:1521/prod", "scott",
            "tiger");
    conn.setAutoCommit(false);//from  w w w .  j av a2  s .c o  m
    PreparedStatement ps = conn.prepareStatement("insert into images values (?,?)");
    ps.setString(1, file.getName());
    ps.setBinaryStream(2, fis, (int) file.length());
    ps.executeUpdate();
    ps.close();
    fis.close();

}

From source file:at.tlphotography.jAbuseReport.Reporter.java

/**
 * The main method.//from  www .  j  a v a  2 s .c om
 *
 * @param args
 *          the arguments
 */
public static void main(String[] args) {
    parseArguments(args);

    File[] directory = new File(logDir).listFiles(); // get the files in the dir

    for (File file : directory) // iterate over the file
    {
        if (!file.isDirectory() && file.getName().contains(logNames)) // if the file is not a dir and the name contains the logName string
        {
            if (file.getName().endsWith(".gz")) // is it zipped?
            {
                content.putAll(readGZFile(file));
            } else {
                content.putAll(readLogFile(file));
            }
        }
    }

    // save the mails to the log lines
    HashMap<String, ArrayList<LogObject>> finalContent = new HashMap<>();

    Iterator<Entry<String, String>> it = content.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, String> pair = it.next();
        String mail = whoIsLookUp(pair.getKey());

        if (finalContent.containsKey(mail)) {
            finalContent.get(mail).add(new LogObject(pair.getValue()));
        } else {
            ArrayList<LogObject> temp = new ArrayList<LogObject>();
            temp.add(new LogObject(pair.getValue()));
            finalContent.put(mail, temp);
        }

        it.remove();
    }

    // sort them
    Iterator<Entry<String, ArrayList<LogObject>>> it2 = finalContent.entrySet().iterator();
    while (it2.hasNext()) {
        Entry<String, ArrayList<LogObject>> pair = it2.next();
        Collections.sort(pair.getValue());
        println(pair.getKey() + " =");
        for (LogObject obj : pair.getValue()) {
            println(obj.logContent);
        }

        println("\n");
        it2.remove();
    }

}