List of usage examples for java.io File getName
public String getName()
From source file:net.openbyte.Launch.java
/** * This is the main method that allows Java to initiate the program. * * @param args the arguments to the Java program, which are ignored *///from w w w . j a v a 2s. com public static void main(String[] args) { logger.info("Checking for a new version..."); try { GitHub gitHub = new GitHubBuilder().withOAuthToken("e5b60cea047a3e44d4fc83adb86ea35bda131744 ").build(); GHRepository repository = gitHub.getUser("PizzaCrust").getRepository("OpenByte"); for (GHRelease release : repository.listReleases()) { double releaseTag = Double.parseDouble(release.getTagName()); if (CURRENT_VERSION < releaseTag) { logger.info("Version " + releaseTag + " has been released."); JOptionPane.showMessageDialog(null, "Please update OpenByte to " + releaseTag + " at https://github.com/PizzaCrust/OpenByte.", "Update", JOptionPane.WARNING_MESSAGE); } else { logger.info("OpenByte is at the latest version."); } } } catch (Exception e) { logger.error("Failed to connect to GitHub."); e.printStackTrace(); } logger.info("Checking for a workspace folder..."); if (!Files.WORKSPACE_DIRECTORY.exists()) { logger.info("Workspace directory not found, creating one."); Files.WORKSPACE_DIRECTORY.mkdir(); } logger.info("Checking for a plugins folder..."); if (!Files.PLUGINS_DIRECTORY.exists()) { logger.info("Plugins directory not found, creating one."); Files.PLUGINS_DIRECTORY.mkdir(); } try { logger.info("Grabbing and applying system look and feel..."); UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { logger.info("Something went wrong when applying the look and feel, using the default one..."); e.printStackTrace(); } logger.info("Starting event manager..."); EventManager.init(); logger.info("Detecting plugin files..."); File[] pluginFiles = PluginManager.getPluginFiles(Files.PLUGINS_DIRECTORY); logger.info("Detected " + pluginFiles.length + " plugin files in the plugins directory!"); logger.info("Beginning load/register plugin process..."); for (File pluginFile : pluginFiles) { logger.info("Loading file " + FilenameUtils.removeExtension(pluginFile.getName()) + "..."); try { PluginManager.registerAndLoadPlugin(pluginFile); } catch (Exception e) { logger.error("Failed to load file " + FilenameUtils.removeExtension(pluginFile.getName()) + "!"); e.printStackTrace(); } } logger.info("All plugin files were loaded/registered to OpenByte."); logger.info("Showing graphical interface to user..."); WelcomeFrame welcomeFrame = new WelcomeFrame(); welcomeFrame.setVisible(true); }
From source file:ProductionJS.java
/** * @param args//from w ww. j a v a2 s.c om */ public static void main(String[] args) { boolean precondition = true; BackupLog backupLog = new BackupLog("log/backupLog.txt"); Property properties = null; Settings settings = null; // Load main cfg file try { properties = new Property("cfg/cfg"); } catch (IOException e) { backupLog.log("ERROR : Config file not found"); precondition = false; } // Load cfg for Log4J if (precondition) { try { DOMConfigurator.configureAndWatch(properties.getProperty("loggerConfiguration")); logger.info("ProductionJS is launched\n_______________________"); } catch (Exception e) { backupLog.log(e.getMessage()); precondition = false; } } // Load settings for current execution if (precondition) { try { settings = new Settings(new File(properties.getProperty("importConfiguration"))); } catch (IOException e) { logger.error("Properties file not found"); precondition = false; } catch (org.json.simple.parser.ParseException e) { logger.error("Properties file reading error : JSON may be invalid, check it!"); precondition = false; } } // All is OK : GO! if (precondition) { logger.info("Configuration OK"); logger.info("\"_______________________\nConcat BEGIN\n_______________________\n"); Concat concat = new Concat(); try { if (settings.getPrior() != null) { logger.info("Add Prior files\n_______________________\n"); concat.addJSONArray(settings.getPrior()); } for (int i = 0; i < settings.getIn().size(); i++) { ProductionJS.logger.info("Importation number " + (i + 1)); ProductionJS.logger.info("Directory imported " + settings.getIn().get(i)); Directory dir = new Directory(new File(settings.getIn().get(i).toString())); dir.scan(); concat.add(dir.getFiles()); } concat.output(settings.getOut()); logger.info("\"_______________________\nConcat END\n_______________________\n"); if (settings.getMinify() != null && settings.getMinify() == true) { logger.info( "\"_______________________\nMinify of concatened file BEGIN\n_______________________\n"); new Minify(new File(settings.getOut()), settings.getOut()); logger.info( "\"_______________________\nMinify of concatened file END\n_______________________\n"); } if (settings.getLicense() != null) { logger.info("Add License\n_______________________\n"); concat = new Concat(); UUID uniqueID = UUID.randomUUID(); PrintWriter tmp = new PrintWriter(uniqueID.toString() + ".txt"); tmp.println(settings.getLicense()); tmp.close(); File license = new File(uniqueID.toString() + ".txt"); concat.add(license); File out = new File(settings.getOut()); File tmpOut = new File(uniqueID + out.getName()); out.renameTo(tmpOut); concat.add(tmpOut); concat.output(settings.getOut()); license.delete(); tmpOut.delete(); } } catch (IOException e) { StackTrace stackTrace = new StackTrace(e.getStackTrace()); logger.error("An error occurred " + e.getMessage() + " " + stackTrace.toString()); } } }
From source file:de.tudarmstadt.ukp.argumentation.data.roomfordebate.DataFetcher.java
public static void main(String[] args) throws Exception { File crawledPagesFolder = new File(args[0]); if (!crawledPagesFolder.exists()) { crawledPagesFolder.mkdirs();//from w ww. java 2 s . c o m } File outputFolder = new File(args[1]); if (!outputFolder.exists()) { outputFolder.mkdirs(); } // read links from text file final String urlsResourceName = "roomfordebate-urls.txt"; InputStream urlsStream = DataFetcher.class.getClassLoader().getResourceAsStream(urlsResourceName); if (urlsStream == null) { throw new IOException("Cannot find resource " + urlsResourceName + " on the classpath"); } // read list of urls List<String> urls = new ArrayList<>(); LineIterator iterator = IOUtils.lineIterator(urlsStream, "utf-8"); while (iterator.hasNext()) { // ignore commented url (line starts with #) String line = iterator.nextLine(); if (!line.startsWith("#") && !line.trim().isEmpty()) { urls.add(line.trim()); } } // download all crawlPages(urls, crawledPagesFolder); List<File> files = new ArrayList<>(FileUtils.listFiles(crawledPagesFolder, null, false)); Collections.sort(files, new Comparator<File>() { @Override public int compare(File o1, File o2) { return o1.getName().compareTo(o2.getName()); } }); int idCounter = 0; for (File file : files) { NYTimesCommentsScraper commentsScraper = new NYTimesCommentsScraper(); NYTimesArticleExtractor extractor = new NYTimesArticleExtractor(); String html = FileUtils.readFileToString(file, "utf-8"); idCounter++; File outputFileArticle = new File(outputFolder, String.format("Cx%03d.txt", idCounter)); File outputFileComments = new File(outputFolder, String.format("Dx%03d.txt", idCounter)); try { List<Comment> comments = commentsScraper.extractComments(html); Article article = extractor.extractArticle(html); saveArticleToText(article, outputFileArticle); System.out.println("Saved to " + outputFileArticle); saveCommentsToText(comments, outputFileComments, article); System.out.println("Saved to " + outputFileComments); } catch (IOException ex) { System.err.println(file.getName() + "\n" + ex.getMessage()); } } }
From source file:com.schnobosoft.semeval.cortical.SemEvalTextSimilarity.java
public static void main(String[] args) throws IOException, ApiException { /* read command line arguments (input file and API key) */ String apiKey;// w ww. ja va 2 s . c o m File inputFile; Retina retinaName; if (args.length >= 2) { inputFile = new File(args[0]); assert inputFile.getName().startsWith(INPUT_FILE_PREFIX); apiKey = args[1]; retinaName = (args.length > 2 && args[2].toLowerCase().startsWith("syn")) ? EN_SYNONYMOUS : DEFAULT_RETINA_NAME; } else { throw new IllegalArgumentException( "Call: " + SemEvalTextSimilarity.class.getCanonicalName() + " <input file> <api key> [<syn>]"); } LOG.info("Using Retina " + retinaName.name().toLowerCase() + " at " + Util.RETINA_IP + "."); CompareModels[] input = readInput(inputFile); RetinaApis api = Util.getApi(apiKey, retinaName, Util.RETINA_IP); Metric[] scores = compare(input, api); assert input.length == scores.length; saveScores(scores, inputFile, retinaName); }
From source file:edu.ucla.cs.scai.swim.qa.ontology.dbpedia.tipicality.DbpediaCategoryAttributeCounts.java
public static void main(String args[]) throws FileNotFoundException, IOException { 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"); String path = DBpediaOntology.DBPEDIA_CSV_FOLDER; if (args != null && args.length > 0) { path = args[0];//from ww w . ja v a2 s . c om if (!path.endsWith("/")) { path = path + "/"; } } File folder = new File(path); if (!folder.exists()) { System.out.println("The path with DBpedia CSV files is set as " + path); System.out.println("You need to change the path with the correct one on your PC"); System.exit(0); } for (File f : new File(path).listFiles()) { if (f.isFile() && f.getName().endsWith(".csv.gz")) { System.out.println("Processing file " + f.getName() + "..."); processFile(f, f.getName().replaceAll("\\.csv.gz", "")); } } System.out.println(entities.size() + " entities processed"); System.out.println(categories.size() + " categories found"); System.out.println(attributes.size() + " attributes found"); try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path + "counts.bin"))) { oos.writeObject(categories); oos.writeObject(attributes); oos.writeObject(categoryCount); oos.writeObject(attributeCount); oos.writeObject(categoryAttributeCount); oos.writeObject(attributeCategoryCount); } }
From source file:com.doculibre.constellio.utils.resources.WriteResourceBundleUtils.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { File binDir = ClasspathUtils.getClassesDir(); File projectDir = binDir.getParentFile(); File sourceDir = new File(projectDir, "source"); String defaultLanguage;/* w w w .j a va 2s . c om*/ String otherLanguage; if (args.length > 0) { defaultLanguage = args[0]; otherLanguage = args[1]; } else { defaultLanguage = Locale.ENGLISH.getLanguage(); otherLanguage = Locale.FRENCH.getLanguage(); } List<File> propertiesFiles = (List<File>) FileUtils.listFiles(sourceDir, new String[] { "properties" }, true); for (File propertiesFile : propertiesFiles) { File propertiesDir = propertiesFile.getParentFile(); String propertiesNameWoutSuffix = StringUtils.substringBefore(propertiesFile.getName(), "_"); propertiesNameWoutSuffix = StringUtils.substringBefore(propertiesNameWoutSuffix, ".properties"); String noLanguageFileName = propertiesNameWoutSuffix + ".properties"; String defaultLanguageFileName = propertiesNameWoutSuffix + "_" + defaultLanguage + ".properties"; String otherLanguageFileName = propertiesNameWoutSuffix + "_" + otherLanguage + ".properties"; File noLanguageFile = new File(propertiesDir, noLanguageFileName); File defaultLanguageFile = new File(propertiesDir, defaultLanguageFileName); File otherLanguageFile = new File(propertiesDir, otherLanguageFileName); if (defaultLanguageFile.exists() && otherLanguageFile.exists() && !noLanguageFile.exists()) { System.out.println(defaultLanguageFile.getPath() + " > " + noLanguageFileName); System.out.println(defaultLanguageFile.getPath() + " > empty file"); defaultLanguageFile.renameTo(noLanguageFile); FileWriter defaultLanguageEmptyFileWriter = new FileWriter(defaultLanguageFile); defaultLanguageEmptyFileWriter.write(""); IOUtils.closeQuietly(defaultLanguageEmptyFileWriter); } } }
From source file:comparetopics.CompareTopics.java
/** * @param args the command line arguments *///from w w w .j a va 2s. c om public static void main(String[] args) { try { File file1 = new File( "/Users/apple/Desktop/graduation-project/topic-modeling/output/jhotdraw-extracted-code/keys.txt"); File file2 = new File( "/Users/apple/Desktop/graduation-project/topic-modeling/output/jhotdraw-extracted-code/keys.txt"); CompareTopics compareTopics = new CompareTopics(); String[] words1 = compareTopics.getWords(file1); String[] words2 = compareTopics.getWords(file2); StringBuffer words = new StringBuffer(); File outputFile = new File("/Users/apple/Desktop/test.txt"); if (outputFile.createNewFile()) { System.out.println("Create successful: " + outputFile.getName()); } boolean hasSame = false; for (String w1 : words1) { if (!NumberUtils.isNumber(w1)) { for (String w2 : words2) { if (w1.equals(w2)) { words.append(w1); // words.append("\r\n"); words.append(" "); hasSame = true; break; } } } } if (!hasSame) { System.out.println("No same word."); } else { compareTopics.printToFile(words.toString(), outputFile); } } catch (IOException ex) { Logger.getLogger(CompareTopics.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:MainGeneratePicasaIniFile.java
public static void main(String[] args) { try {//w w w . j a v a 2 s . co m Calendar start = Calendar.getInstance(); start.set(1899, 11, 30, 0, 0); PicasawebService myService = new PicasawebService("My Application"); myService.setUserCredentials(args[0], args[1]); // Get a list of all entries URL metafeedUrl = new URL("http://picasaweb.google.com/data/feed/api/user/" + args[0] + "?kind=album"); System.out.println("Getting Picasa Web Albums entries...\n"); UserFeed resultFeed = myService.getFeed(metafeedUrl, UserFeed.class); // resultFeed. File root = new File(args[2]); File[] albuns = root.listFiles(); int j = 0; List<GphotoEntry> entries = resultFeed.getEntries(); for (int i = 0; i < entries.size(); i++) { GphotoEntry entry = entries.get(i); String href = entry.getHtmlLink().getHref(); String name = entry.getTitle().getPlainText(); for (File album : albuns) { if (album.getName().equals(name) && !href.contains("02?")) { File picasaini = new File(album, "Picasa.ini"); if (!picasaini.exists()) { StringBuilder builder = new StringBuilder(); builder.append("\n"); builder.append("[Picasa]\n"); builder.append("name="); builder.append(name); builder.append("\n"); builder.append("location="); Collection<Extension> extensions = entry.getExtensions(); for (Extension extension : extensions) { if (extension instanceof GphotoLocation) { GphotoLocation location = (GphotoLocation) extension; if (location.getValue() != null) { builder.append(location.getValue()); } } } builder.append("\n"); builder.append("category=Folders on Disk"); builder.append("\n"); builder.append("date="); String source = name.substring(0, 10); DateFormat formater = new SimpleDateFormat("yyyy-MM-dd"); Date date = formater.parse(source); Calendar end = Calendar.getInstance(); end.setTime(date); builder.append(daysBetween(start, end)); builder.append(".000000"); builder.append("\n"); builder.append(args[0]); builder.append("_lh="); builder.append(entry.getGphotoId()); builder.append("\n"); builder.append("P2category=Folders on Disk"); builder.append("\n"); URL feedUrl = new URL("https://picasaweb.google.com/data/feed/api/user/" + args[0] + "/albumid/" + entry.getGphotoId()); AlbumFeed feed = myService.getFeed(feedUrl, AlbumFeed.class); for (GphotoEntry photo : feed.getEntries()) { builder.append("\n"); builder.append("["); builder.append(photo.getTitle().getPlainText()); builder.append("]"); builder.append("\n"); long id = Long.parseLong(photo.getGphotoId()); builder.append("IIDLIST_"); builder.append(args[0]); builder.append("_lh="); builder.append(Long.toHexString(id)); builder.append("\n"); } System.out.println(builder.toString()); IOUtils.write(builder.toString(), new FileOutputStream(picasaini)); j++; } } } } System.out.println(j); System.out.println("\nTotal Entries: " + entries.size()); } catch (Exception e) { e.printStackTrace(); } }
From source file:grnet.filter.XMLFiltering.java
public static void main(String[] args) throws IOException { // TODO Auto-generated method ssstub Enviroment enviroment = new Enviroment(args[0]); if (enviroment.envCreation) { Core core = new Core(); XMLSource source = new XMLSource(args[0]); File sourceFile = source.getSource(); if (sourceFile.exists()) { Collection<File> xmls = source.getXMLs(); System.out.println("Filtering repository:" + enviroment.dataProviderFilteredIn.getName()); System.out.println("Number of files to filter:" + xmls.size()); Iterator<File> iterator = xmls.iterator(); FilteringReport report = null; if (enviroment.getArguments().getProps().getProperty(Constants.createReport) .equalsIgnoreCase("true")) { report = new FilteringReport(enviroment.getArguments().getDestFolderLocation(), enviroment.getDataProviderFilteredIn().getName()); }/*ww w . ja v a2 s . com*/ 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(enviroment.dataProviderFilteredIn.getName()); File xmlFile = iterator.next(); String name = xmlFile.getName(); name = name.substring(0, name.indexOf(".xml")); logString.append(" " + name); boolean xmlIsFilteredIn = core.filterXML(xmlFile, enviroment.getArguments().getQueries()); if (xmlIsFilteredIn) { logString.append(" " + "FilteredIn"); 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.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.filteredInData); report.raiseFilteredInFilesNum(); } FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderFilteredIn()); } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); e.printStackTrace(); System.out.println("Filtering failed."); } } else { logString.append(" " + "FilteredOut"); 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.appendXMLFileNameNStatus(xmlFile.getPath(), Constants.filteredOutData); report.raiseFilteredOutFilesNum(); } FileUtils.copyFileToDirectory(xmlFile, enviroment.getDataProviderFilteredOuT()); } catch (IOException e) { // TODO Auto-generated catch block // e.printStackTrace(); e.printStackTrace(); System.out.println("Filtering failed."); } } } if (report != null) { report.appendXPathExpression(enviroment.getArguments().getQueries()); report.appendGeneralInfo(); } System.out.println("Filtering is done."); } } }
From source file:mujava.cli.testnew.java
public static void main(String[] args) throws IOException { testnewCom jct = new testnewCom(); String[] argv = { "Flower", "/Users/dmark/mujava/src/Flower" }; new JCommander(jct, args); muJavaHomePath = Util.loadConfig(); // muJavaHomePath= "/Users/dmark/mujava"; // check if debug mode if (jct.isDebug() || jct.isDebugMode()) { Util.debug = true;// w w w .j a va 2s. c om } System.out.println(jct.getParameters().size()); sessionName = jct.getParameters().get(0); // set first parameter as the // session name ArrayList<String> srcFiles = new ArrayList<>(); for (int i = 1; i < jct.getParameters().size(); i++) { srcFiles.add(jct.getParameters().get(i)); // retrieve all src file // names from parameters } // get all existing session name File folder = new File(muJavaHomePath); if (!folder.isDirectory()) { Util.Error("ERROR: cannot locate the folder specified in mujava.config"); return; } File[] listOfFiles = folder.listFiles(); // null checking // check the specified folder has files or not if (listOfFiles == null) { Util.Error("ERROR: no files in the muJava home folder " + muJavaHomePath); return; } List<String> fileNameList = new ArrayList<>(); for (File file : listOfFiles) { fileNameList.add(file.getName()); } // check if the session is new or not if (fileNameList.contains(sessionName)) { Util.Error("Session already exists."); } else { // create sub-directory for the session setupSessionDirectory(sessionName); // move src files into session folder for (String srcFile : srcFiles) { // new (dir, name) // check abs path or not // need to check if srcFile has .java at the end or not if (srcFile.length() > 5) { if (srcFile.substring(srcFile.length() - 5).equals(".java")) // name has .java at the end, e.g. cal.java { // delete .java, e.g. make it cal srcFile = srcFile.substring(0, srcFile.length() - 5); } } File source = new File(srcFile + ".java"); if (!source.isAbsolute()) // relative path, attach path, e.g. cal.java, make it c:\mujava\cal.java { source = new File(muJavaHomePath + "/src" + java.io.File.separator + srcFile + ".java"); } File desc = new File(muJavaHomePath + "/" + sessionName + "/src"); FileUtils.copyFileToDirectory(source, desc); // compile src files // String srcName = "t"; boolean result = compileSrc(srcFile); if (result) Util.Print("Session is built successfully."); } } // System.exit(0); }