List of usage examples for java.lang StringBuilder toString
@Override
@HotSpotIntrinsicCandidate
public String toString()
From source file:de.huxhorn.lilith.Lilith.java
public static void main(String[] args) { {/*from w w w .j a v a 2 s. c o m*/ // initialize java.util.logging to use slf4j... Handler handler = new Slf4JHandler(); java.util.logging.Logger rootLogger = java.util.logging.Logger.getLogger(""); rootLogger.addHandler(handler); rootLogger.setLevel(java.util.logging.Level.WARNING); } StringBuilder appTitle = new StringBuilder(); appTitle.append(APP_NAME).append(" V").append(APP_VERSION); if (APP_SNAPSHOT) { // always append timestamp for SNAPSHOT appTitle.append(" (").append(APP_TIMESTAMP_DATE).append(")"); } CommandLineArgs cl = new CommandLineArgs(); JCommander commander = new JCommander(cl); Cat cat = new Cat(); commander.addCommand(Cat.NAME, cat); Tail tail = new Tail(); commander.addCommand(Tail.NAME, tail); Filter filter = new Filter(); commander.addCommand(Filter.NAME, filter); Index index = new Index(); commander.addCommand(Index.NAME, index); Md5 md5 = new Md5(); commander.addCommand(Md5.NAME, md5); Help help = new Help(); commander.addCommand(Help.NAME, help); try { commander.parse(args); } catch (ParameterException ex) { printAppInfo(appTitle.toString(), false); System.out.println(ex.getMessage() + "\n"); printHelp(commander); System.exit(-1); } if (cl.verbose) { if (!APP_SNAPSHOT) { // timestamp is always appended for SNAPSHOT // don't append it twice appTitle.append(" (").append(APP_TIMESTAMP_DATE).append(")"); } appTitle.append(" - ").append(APP_REVISION); } String appTitleString = appTitle.toString(); if (cl.showHelp) { printAppInfo(appTitleString, false); printHelp(commander); System.exit(0); } String command = commander.getParsedCommand(); if (!Tail.NAME.equals(command) && !Cat.NAME.equals(command) && !Filter.NAME.equals(command)) // don't print info in case of cat, tail or filter { printAppInfo(appTitleString, true); } if (cl.logbackConfig != null) { File logbackFile = new File(cl.logbackConfig); if (!logbackFile.isFile()) { System.out.println(logbackFile.getAbsolutePath() + " is not a valid file."); System.exit(-1); } try { initLogbackConfig(logbackFile.toURI().toURL()); } catch (MalformedURLException e) { System.out.println("Failed to convert " + logbackFile.getAbsolutePath() + " to URL. " + e); System.exit(-1); } } else if (cl.verbose) { initVerboseLogging(); } if (cl.printBuildTimestamp) { System.out.println("Build-Date : " + APP_TIMESTAMP_DATE); System.out.println("Build-Revision : " + APP_REVISION); System.out.println("Build-Timestamp: " + APP_TIMESTAMP); System.exit(0); } if (Help.NAME.equals(command)) { commander.usage(); if (help.commands == null || help.commands.size() == 0) { commander.usage(Help.NAME); } else { Map<String, JCommander> commands = commander.getCommands(); for (String current : help.commands) { if (commands.containsKey(current)) { commander.usage(current); } else { System.out.println("Unknown command '" + current + "'!"); } } } System.exit(0); } if (Md5.NAME.equals(command)) { List<String> files = md5.files; if (files == null || files.isEmpty()) { printHelp(commander); System.out.println("Missing files!"); System.exit(-1); } boolean error = false; for (String current : files) { if (!CreateMd5Command.createMd5(new File(current))) { error = true; } } if (error) { System.exit(-1); } System.exit(0); } if (Index.NAME.equals(command)) { if (!cl.verbose && cl.logbackConfig == null) { initCLILogging(); } List<String> files = index.files; if (files == null || files.size() == 0) { printHelp(commander); System.exit(-1); } boolean error = false; for (String current : files) { if (!IndexCommand.indexLogFile(new File(current))) { error = true; } } if (error) { System.exit(-1); } System.exit(0); } if (Cat.NAME.equals(command)) { if (!cl.verbose && cl.logbackConfig == null) { initCLILogging(); } List<String> files = cat.files; if (files == null || files.size() != 1) { printHelp(commander); System.exit(-1); } if (CatCommand.catFile(new File(files.get(0)), cat.pattern, cat.numberOfLines)) { System.exit(0); } System.exit(-1); } if (Tail.NAME.equals(command)) { if (!cl.verbose && cl.logbackConfig == null) { initCLILogging(); } List<String> files = tail.files; if (files == null || files.size() != 1) { printHelp(commander); System.exit(-1); } if (TailCommand.tailFile(new File(files.get(0)), tail.pattern, tail.numberOfLines, tail.keepRunning)) { System.exit(0); } System.exit(-1); } if (Filter.NAME.equals(command)) { if (!cl.verbose && cl.logbackConfig == null) { initCLILogging(); } if (FilterCommand.filterFile(new File(filter.input), new File(filter.output), new File(filter.condition), filter.searchString, filter.pattern, filter.overwrite, filter.keepRunning, filter.exclusive)) { System.exit(0); } System.exit(-1); } if (cl.flushPreferences) { flushPreferences(); } if (cl.exportPreferencesFile != null) { exportPreferences(cl.exportPreferencesFile); } if (cl.importPreferencesFile != null) { importPreferences(cl.importPreferencesFile); } if (cl.exportPreferencesFile != null || cl.importPreferencesFile != null) { System.exit(0); } if (cl.flushLicensed) { flushLicensed(); } startLilith(appTitleString); }
From source file:com.linkedin.databus2.client.util.DatabusClusterUtil.java
/** * @param args//from w ww .j av a 2 s . co m * DbusClusterUtil -z <zookeper-server> -c <cluster-name> [-p * <partitionNumber] partitions readSCN writeSCN SCN remove * clients */ public static void main(String[] args) { try { GnuParser cmdLineParser = new GnuParser(); Options options = new Options(); options.addOption("z", true, "zk-server").addOption("c", true, "cluster-name ") .addOption("p", true, "partition").addOption("l", false, "legacy") .addOption("h", false, "help"); CommandLine cmdLineArgs = cmdLineParser.parse(options, args, false); if (cmdLineArgs.hasOption('h')) { usage(); System.exit(0); } if (!cmdLineArgs.hasOption('c')) { usage(); System.exit(1); } String clusterName = cmdLineArgs.getOptionValue('c'); String zkServer = cmdLineArgs.getOptionValue('z'); boolean isLegacyChkptLocation = cmdLineArgs.hasOption('l'); if (zkServer == null || zkServer.isEmpty()) { zkServer = "localhost:2181"; } String partitionStr = cmdLineArgs.getOptionValue('p'); String partition = partitionStr; if ((partition != null) && partition.equals("all")) { partition = ""; } String[] fns = cmdLineArgs.getArgs(); if (fns.length < 1) { usage(); System.exit(1); } DatabusClusterUtilHelper clusterState = new DatabusClusterUtilHelper(zkServer, clusterName); String function = fns[0]; String arg1 = (fns.length > 1) ? fns[1] : null; String arg2 = (fns.length > 2) ? fns[2] : null; boolean clusterExists = clusterState.existsCluster(); if (function.equals("create")) { if (!clusterExists) { if (arg1 == null) { throw new DatabusClusterUtilException("create: please provide the number of partitions"); } int part = Integer.parseInt(arg1); clusterState.createCluster(part); return; } else { throw new DatabusClusterUtilException("Cluster " + clusterName + " already exists"); } } if (!clusterExists) { throw new DatabusClusterUtilException("Cluster doesn't exist! "); } if (function.equals("delete")) { clusterState.removeCluster(); } else if (function.equals("partitions")) { int numParts = clusterState.getNumPartitions(); System.out.println(numParts); } else { // all these functions require the notion of partition; Set<Integer> partitions = getPartitions(partition, clusterState.getNumPartitions()); if (function.equals("sources")) { DatabusClusterCkptManager ckptMgr = new DatabusClusterCkptManager(zkServer, clusterName, null, partitions, isLegacyChkptLocation); Set<String> sources = ckptMgr.getSourcesFromCheckpoint(); if (sources != null) { for (String s : sources) { System.out.println(s); } } else { throw new DatabusClusterUtilException( "sources: Sources not found for cluster " + clusterName); } } else if (function.equals("clients")) { clusterState.getClusterInfo(); for (Integer p : partitions) { String client = clusterState.getInstanceForPartition(p); System.out.println(p + "\t" + client); } } else if (function.equals("readSCN")) { List<String> sources = getSources(arg1); if ((sources != null) && !sources.isEmpty()) { DatabusClusterCkptManager ckptMgr = new DatabusClusterCkptManager(zkServer, clusterName, sources, partitions, isLegacyChkptLocation); Map<Integer, Checkpoint> ckpts = ckptMgr.readCheckpoint(); char delim = '\t'; for (Map.Entry<Integer, Checkpoint> mkPair : ckpts.entrySet()) { StringBuilder output = new StringBuilder(64); output.append(mkPair.getKey()); output.append(delim); Checkpoint cp = mkPair.getValue(); if (cp == null) { output.append(-1); output.append(delim); output.append(-1); } else { if (cp.getConsumptionMode() == DbusClientMode.ONLINE_CONSUMPTION) { output.append(cp.getWindowScn()); output.append(delim); output.append(cp.getWindowOffset()); } else if (cp.getConsumptionMode() == DbusClientMode.BOOTSTRAP_CATCHUP) { output.append(cp.getWindowScn()); output.append(delim); output.append(cp.getWindowOffset()); } else if (cp.getConsumptionMode() == DbusClientMode.BOOTSTRAP_SNAPSHOT) { output.append(cp.getBootstrapSinceScn()); output.append(delim); output.append(-1); } } System.out.println(output.toString()); } } else { throw new DatabusClusterUtilException("readSCN: please specify non-empty sources"); } } else if (function.equals("checkpoint")) { List<String> sources = getSources(arg1); if ((sources != null) && !sources.isEmpty()) { DatabusClusterCkptManager ckptMgr = new DatabusClusterCkptManager(zkServer, clusterName, sources, partitions, isLegacyChkptLocation); Map<Integer, Checkpoint> ckpts = ckptMgr.readCheckpoint(); char delim = '\t'; for (Map.Entry<Integer, Checkpoint> mkPair : ckpts.entrySet()) { StringBuilder output = new StringBuilder(64); output.append(mkPair.getKey()); output.append(delim); Checkpoint cp = mkPair.getValue(); if (cp == null) { output.append("null"); } else { output.append(cp.toString()); } System.out.println(output.toString()); } } else { throw new DatabusClusterUtilException("readSCN: please specify non-empty sources"); } } else if (function.equals("writeSCN")) { String scnStr = arg1; Long scn = Long.parseLong(scnStr); if (partitionStr != null) { List<String> sources = getSources(arg2); if ((sources != null) && !sources.isEmpty()) { DatabusClusterCkptManager ckptMgr = new DatabusClusterCkptManager(zkServer, clusterName, sources, partitions, isLegacyChkptLocation); ckptMgr.writeCheckpoint(scn); } else { throw new DatabusClusterUtilException("writeSCN: please specify non-empty sources"); } } else { throw new DatabusClusterUtilException( "writeSCN: to write the SCN to all partitions please use '-p all'"); } } else if (function.equals("removeSCN")) { if (partitionStr != null) { List<String> sources = getSources(arg1); if ((sources != null) && !sources.isEmpty()) { DatabusClusterCkptManager ckptMgr = new DatabusClusterCkptManager(zkServer, clusterName, sources, partitions, isLegacyChkptLocation); ckptMgr.remove(); } else { throw new DatabusClusterUtilException("remove: please specify non-empty sources"); } } else { throw new DatabusClusterUtilException( "remove: to remove SCN from all partitions please use '-p all'"); } } else { usage(); System.exit(1); } } } catch (ParseException e) { usage(); System.exit(1); } catch (DatabusClusterUtilException e) { System.err.println("Error! " + e.toString()); System.exit(1); } }
From source file:edu.cuhk.hccl.TripRealRatingsApp.java
public static void main(String[] args) throws IOException { File dir = new File(args[0]); File outFile = new File(args[1]); outFile.delete();// w w w. jav a 2s. c o m StringBuilder buffer = new StringBuilder(); for (File file : dir.listFiles()) { List<String> lines = FileUtils.readLines(file, "UTF-8"); String hotelID = file.getName().split("_")[1]; String author = null; boolean noContent = false; for (String line : lines) { if (line.startsWith("<Author>")) { try { author = line.split(">")[1].trim(); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("[ERROR] An error occured on this line:"); System.out.println(line); continue; } } else if (line.startsWith("<Content>")) { // ignore records if they have no content String content = line.split(">")[1].trim(); if (content == null || content.equals("")) noContent = true; } else if (line.startsWith("<Rating>")) { String[] rates = line.split(">")[1].trim().split("\t"); if (noContent || rates.length != 8) continue; // Change missing rating from -1 to 0 for (int i = 0; i < rates.length; i++) { if (rates[i].equals("-1")) rates[i] = "0"; } buffer.append(author + "\t"); buffer.append(hotelID + "\t"); // overall buffer.append(rates[0] + "\t"); // location buffer.append(rates[3] + "\t"); // room buffer.append(rates[2] + "\t"); // service buffer.append(rates[6] + "\t"); // value buffer.append(rates[1] + "\t"); // cleanliness buffer.append(rates[4] + "\t"); buffer.append("\n"); } } // Write once for each file FileUtils.writeStringToFile(outFile, buffer.toString(), true); // Clear buffer buffer.setLength(0); System.out.printf("[INFO] Finished processing %s\n", file.getName()); } System.out.println("[INFO] All processinig are finished!"); }
From source file:com.cloudhopper.sxmp.Post.java
static public void main(String[] args) throws Exception { String message = "Test With @ Character"; //String message = "Tell Twitter what you're doing!\nStd msg charges apply. Send 'stop' to quit.\nVisit twitter.com or email help@twitter.com for help."; StringBuilder string0 = new StringBuilder(200).append("<?xml version=\"1.0\"?>\n") .append("<operation type=\"submit\">\n") .append(" <account username=\"customer1\" password=\"password1\"/>\n") .append(" <submitRequest referenceId=\"MYREF102020022\">\n") .append(" <operatorId>75</operatorId>\n").append(" <deliveryReport>true</deliveryReport>\n") .append(" <sourceAddress type=\"network\">40404</sourceAddress>\n") .append(" <destinationAddress type=\"international\">+13135551234</destinationAddress>\n") .append(" <text encoding=\"ISO-8859-1\">" + HexUtil.toHexString(message.getBytes("ISO-8859-1")) + "</text>\n") .append(" </submitRequest>\n").append("</operation>\n").append(""); /**//from w w w.jav a2 s . c o m //.append("<!DOCTYPE chapter PUBLIC \"-//OASIS//DTD DocBook XML//EN\" \"../dtds/docbookx.dtd\">") //.append("<!DOCTYPE chapter PUBLIC \"-//OASIS//DTD DocBook XML//EN\">") .append("<submitRequest sequenceId=\"1000\">\n") .append(" <!-- this is a comment -->\n") .append(" <account username=\"testaccount\" password=\"testpassword\"/>\n") .append(" <option />\n") .append(" <messageRequest referenceId=\"MYMESSREF\">\n") //.append(" <sourceAddress>+13135551212</sourceAddress>\n") .append(" <destinationAddress>+13135551200</destinationAddress>\n") .append(" <text><![CDATA[Hello World]]></text>\n") .append(" </messageRequest>\n") .append("</submitRequest>") .append(""); */ // Get target URL String strURL = "http://localhost:9080/api/sxmp/1.0"; // Get file to be posted //String strXMLFilename = args[1]; //File input = new File(strXMLFilename); HttpClient client = new DefaultHttpClient(); long totalStart = System.currentTimeMillis(); for (int i = 0; i < 1; i++) { long start = System.currentTimeMillis(); // execute request try { HttpPost post = new HttpPost(strURL); StringEntity entity = new StringEntity(string0.toString(), "ISO-8859-1"); entity.setContentType("text/xml; charset=\"ISO-8859-1\""); post.setEntity(entity); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = client.execute(post, responseHandler); long stop = System.currentTimeMillis(); logger.debug("----------------------------------------"); logger.debug("Response took " + (stop - start) + " ms"); logger.debug(responseBody); logger.debug("----------------------------------------"); } finally { // do nothing } } long totalEnd = System.currentTimeMillis(); logger.debug("Response took " + (totalEnd - totalStart) + " ms"); }
From source file:com.music.Generator.java
public static void main(String[] args) throws Exception { Score score1 = new Score(); Read.midi(score1, "c:/tmp/gen.midi"); for (Part part : score1.getPartArray()) { System.out.println(part.getInstrument()); }/* w ww .j a v a2 s.co m*/ new StartupListener().contextInitialized(null); Generator generator = new Generator(); generator.configLocation = "c:/config/music"; generator.maxConcurrentGenerations = 5; generator.init(); UserPreferences prefs = new UserPreferences(); prefs.setElectronic(Ternary.YES); //prefs.setSimpleMotif(Ternary.YES); //prefs.setMood(Mood.MAJOR); //prefs.setDrums(Ternary.YES); //prefs.setClassical(true); prefs.setAccompaniment(Ternary.YES); prefs.setElectronic(Ternary.YES); final ScoreContext ctx = generator.generatePiece(); Score score = ctx.getScore(); for (Part part : score.getPartArray()) { System.out.println(part.getTitle() + ": " + part.getInstrument()); } System.out.println("Metre: " + ctx.getMetre()[0] + "/" + ctx.getMetre()[1]); System.out.println(ctx); Write.midi(score, "c:/tmp/gen.midi"); new Thread(new Runnable() { @Override public void run() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(0, 0, 500, 500); frame.setVisible(true); Part part = ctx.getParts().get(PartType.MAIN); Note[] notes = part.getPhrase(0).getNoteArray(); List<Integer> pitches = new ArrayList<Integer>(); for (Note note : notes) { if (!note.isRest()) { pitches.add(note.getPitch()); } } GraphicsPanel gp = new GraphicsPanel(pitches); frame.setContentPane(gp); } }).start(); DecimalFormat df = new DecimalFormat("#.##"); for (Part part : score.getPartArray()) { StringBuilder sb = new StringBuilder(); printStatistics(ctx, part); System.out.println("------------ " + part.getTitle() + "-----------------"); Phrase[] phrases = part.getPhraseArray(); for (Phrase phr : phrases) { if (phr instanceof ExtendedPhrase) { sb.append("Contour=" + ((ExtendedPhrase) phr).getContour() + " "); } double measureSize = 0; int measures = 0; double totalLength = 0; List<String> pitches = new ArrayList<String>(); List<String> lengths = new ArrayList<String>(); System.out.println("((Phrase notes: " + phr.getNoteArray().length + ")"); for (Note note : phr.getNoteArray()) { if (!note.isRest()) { int degree = 0; if (phr instanceof ExtendedPhrase) { degree = Arrays.binarySearch(((ExtendedPhrase) phr).getScale().getDefinition(), note.getPitch() % 12); } pitches.add(String.valueOf(note.getPitch() + " (" + degree + ") ")); } else { pitches.add(" R "); } lengths.add(df.format(note.getRhythmValue())); measureSize += note.getRhythmValue(); totalLength += note.getRhythmValue(); ; if (measureSize >= ctx.getNormalizedMeasureSize()) { pitches.add(" || "); lengths.add(" || " + (measureSize > ctx.getNormalizedMeasureSize() ? "!" : "")); measureSize = 0; measures++; } } sb.append(pitches.toString() + "\r\n"); sb.append(lengths.toString() + "\r\n"); if (part.getTitle().equals(PartType.MAIN.getTitle())) { sb.append("\r\n"); } System.out.println("Phrase measures: " + measures); System.out.println("Phrase length: " + totalLength); } System.out.println(sb.toString()); } MutingPrintStream.ignore.set(true); Write.midi(score, "c:/tmp/gen.midi"); MutingPrintStream.ignore.set(null); Play.midi(score); generator.toMp3(FileUtils.readFileToByteArray(new File("c:/tmp/gen.midi"))); }
From source file:com.github.codingtogenomic.CodingToGenomic.java
public static void main(String[] args) throws Exception { //parse commandline Options options = new Options(); CommandLineParser parser = new PosixParser(); String gene = new String(); String transcript = new String(); String species = "human"; boolean mapCdna = false; String coordinate = new String(); StringBuilder errorMsg = new StringBuilder(); try {// w w w . ja v a 2 s .c om options = getOptions(args); } catch (org.apache.commons.cli.ParseException ex) { System.err.println("Parsing failed. Reason: " + ex.getMessage()); System.exit(1); } CommandLine line = parser.parse(options, args); if (line.hasOption("help")) { showHelp(options); } if (line.hasOption("gene")) { gene = line.getOptionValue("gene"); } else { if (!line.hasOption("transcript")) { errorMsg.append("Either --gene or --transcript argument is required\n"); } } if (line.hasOption("transcript")) { if (line.hasOption("gene")) { errorMsg.append("Please specify only one of " + "--gene or --transcript arguments, not both\n"); } else { transcript = line.getOptionValue("transcript"); if (line.hasOption("species")) { System.out.println("Ignoring --species option when using --transcript argument"); } } } if (line.hasOption("coordinate")) { coordinate = line.getOptionValue("coordinate"); } else { errorMsg.append("--coordinate argument is required\n"); } if (line.hasOption("species")) { species = line.getOptionValue("species").replaceAll("\\s+", "_"); } if (line.hasOption("b37")) { if (species.equalsIgnoreCase("human") || species.equalsIgnoreCase("homo sapiens")) { SERVER = GRCh37Server; } else { System.out.println("--b37 argument will be ignored - it can only be " + "used when human is the species of interest. Current species" + " is " + species + ".\n"); } } if (line.hasOption("noncoding")) { mapCdna = true; } if (errorMsg.length() > 0) { showHelp(options, errorMsg.toString(), 2); } int c = 0; boolean threePrimeUtr = false; String prefix = "c."; if (mapCdna) { prefix = "n."; try { c = Integer.parseInt(coordinate); } catch (NumberFormatException ex) { showHelp(options, "--coordinate argument '" + coordinate + "' could not " + "be parsed as an integer", 2); } } else if (coordinate.startsWith("*")) { threePrimeUtr = true; prefix = "c.*"; String coord = coordinate.replaceFirst("\\*", ""); try { c = Integer.parseInt(coord); } catch (NumberFormatException ex) { showHelp(options, "--coordinate argument '" + coordinate + "' could not " + "be parsed as an integer or UTR coordinate", 2); } } else { try { c = Integer.parseInt(coordinate); } catch (NumberFormatException ex) { showHelp(options, "--coordinate argument '" + coordinate + "' could not " + "be parsed as an integer", 2); } } //got arguments String result; String header = "Input\tSymbol\tEnsemblGene\tEnsemblTranscript\tGenomicCoordinate"; if (!gene.isEmpty()) { IdParser idParser = new IdParser(gene); System.out.println("Interpretting " + gene + " as of type " + idParser.getIdentifierType()); if (idParser.isEnsemblId()) { if (line.hasOption("species")) { System.out.println("Ignoring --species option when searching Ensembl ID."); } if (idParser.isTranscript()) { result = codingToGenomicTranscript(gene, c, threePrimeUtr, mapCdna); } else if (idParser.isEnsp()) { result = codingToGenomicEnsp(gene, c, threePrimeUtr, mapCdna); } else { result = codingToGenomicId(gene, c, threePrimeUtr, mapCdna); } } else { if (idParser.isTranscript()) { //append user input to beginning result = codingToGenomicXrefTranscript(species, gene, c, threePrimeUtr, mapCdna); } else { result = codingToGenomicXref(species, gene, c, threePrimeUtr, mapCdna); } } if (idParser.isTranscript() || idParser.isEnsp()) { result = gene + ":" + prefix + c + "\t" + result; } else { result = convertGeneResult(result, gene, c, prefix); } } else { System.out.println("Searching for " + transcript + " as Ensembl transcript ID"); result = codingToGenomicTranscript(transcript, c, threePrimeUtr, mapCdna); //append user input to beginning result = transcript + ":" + prefix + c + "\t" + result; } System.out.println(header); System.out.println(result); }
From source file:com.sccl.attech.common.utils.excel.ExportExcel.java
/** * // w w w .j ava2 s . co m */ public static void main(String[] args) throws Throwable { List<String> headerList = Lists.newArrayList(); headerList.add("??"); headerList.add("??"); headerList.add(""); headerList.add("?"); headerList.add(""); List<String> dataRowList = Lists.newArrayList(); for (int i = 1; i <= headerList.size(); i++) { dataRowList.add("?" + i); } List<List<String>> dataList = Lists.newArrayList(); for (int i = 1; i <= 100; i++) { dataList.add(dataRowList); } ExportExcel ee = new ExportExcel(null, headerList); for (int i = 0; i < dataList.size(); i++) { Row row = ee.addRow(); for (int j = 0; j < dataList.get(i).size(); j++) { ee.addCell(row, j, dataList.get(i).get(j)); } } ee.createAddMergedRegion(); StringBuilder sb = new StringBuilder(); sb.append("????").append("\r\n"); sb.append( "???64????? ?: ; { } ! @ $ ^ & | , . / ? [ ] ~ * # <+ - = ") .append("\r"); sb.append("??:").append("").append("'").append("%") .append("\\").append("? ") .append("\r"); sb.append( "?? ?60?????? : ; { } ! @ $ ^ & | , . / ? [ ] ~ * # < +- = ") .append("\r"); sb.append( " ????") .append("\r"); sb.append( "??180???1590???15???? :") .append("\r"); sb.append( "79.000000000000000?GPS???????6?") .append("\r"); sb.append( "* ??2000??2000?????") .append("\r"); sb.append("* EXCEL???.xls97-2003").append("\r"); sb.append("* ??????").append("\r"); sb.append( "* ??") .append("\r"); sb.append( "* ????POI??POI??????") .append("\r"); ee.addCellStyle(ee.getExistRow(1), 6, sb.toString()); //demo ee.initializeDemo(null, headerList); ee.addCellStyle(ee.getExistRow(25), 6, "?"); ee.addCellStyle(ee.getExistRow(25), 7, ""); ee.addCellStyle(ee.getExistRow(25), 8, ""); ee.addCellStyle(ee.getExistRow(25), 9, "116.35526644472"); ee.addCellStyle(ee.getExistRow(25), 10, "40.03711432476"); //ee.addCell(ee.getExistRow(26), 6, dataList.get(i).get(j)); ee.writeFile("D:\\export.xlsx"); ee.dispose(); log.debug("Export success."); }
From source file:com.moviejukebox.MovieJukebox.java
public static void main(String[] args) throws Throwable { JukeboxStatistics.setTimeStart(System.currentTimeMillis()); // Create the log file name here, so we can change it later (because it's locked System.setProperty("file.name", LOG_FILENAME); PropertyConfigurator.configure("properties/log4j.properties"); LOG.info("Yet Another Movie Jukebox {}", GitRepositoryState.getVersion()); LOG.info("~~~ ~~~~~~~ ~~~~~ ~~~~~~~ {}", StringUtils.repeat("~", GitRepositoryState.getVersion().length())); LOG.info("https://github.com/YAMJ/yamj-v2"); LOG.info("Copyright (c) 2004-2016 YAMJ Members"); LOG.info(""); LOG.info("This software is licensed under the GNU General Public License v3+"); LOG.info("See this page: https://github.com/YAMJ/yamj-v2/wiki/License"); LOG.info(""); LOG.info(" Revision SHA: {} {}", GIT.getCommitId(), GIT.getDirty() ? "(Custom Build)" : ""); LOG.info(" Commit Date: {}", GIT.getCommitTime()); LOG.info(" Build Date: {}", GIT.getBuildTime()); LOG.info(""); LOG.info(" Java Version: {}", GitRepositoryState.getJavaVersion()); LOG.info(""); if (!SystemTools.validateInstallation()) { LOG.info("ABORTING."); return;//from w w w . j av a2 s .c o m } String movieLibraryRoot = null; String jukeboxRoot = null; Map<String, String> cmdLineProps = new LinkedHashMap<>(); try { for (int i = 0; i < args.length; i++) { String arg = args[i]; if ("-v".equalsIgnoreCase(arg)) { // We've printed the version, so quit now return; } else if ("-t".equalsIgnoreCase(arg)) { String pin = args[++i]; // load the apikeys.properties file if (!setPropertiesStreamName("./properties/apikeys.properties", Boolean.TRUE)) { return; } // authorize to Trakt.TV TraktTV.getInstance().initialize().authorizeWithPin(pin); // We've authorized access to Trakt.TV, so quit now return; } else if ("-o".equalsIgnoreCase(arg)) { jukeboxRoot = args[++i]; PropertiesUtil.setProperty("mjb.jukeboxRoot", jukeboxRoot); } else if ("-c".equalsIgnoreCase(arg)) { jukeboxClean = Boolean.TRUE; PropertiesUtil.setProperty("mjb.jukeboxClean", TRUE); } else if ("-k".equalsIgnoreCase(arg)) { setJukeboxPreserve(Boolean.TRUE); } else if ("-p".equalsIgnoreCase(arg)) { userPropertiesName = args[++i]; } else if ("-i".equalsIgnoreCase(arg)) { skipIndexGeneration = Boolean.TRUE; PropertiesUtil.setProperty("mjb.skipIndexGeneration", TRUE); } else if ("-h".equalsIgnoreCase(arg)) { skipHtmlGeneration = Boolean.TRUE; PropertiesUtil.setProperty("mjb.skipHtmlGeneration", Boolean.TRUE); } else if ("-dump".equalsIgnoreCase(arg)) { dumpLibraryStructure = Boolean.TRUE; } else if ("-memory".equalsIgnoreCase(arg)) { showMemory = Boolean.TRUE; PropertiesUtil.setProperty("mjb.showMemory", Boolean.TRUE); } else if (arg.startsWith("-D")) { String propLine = arg.length() > 2 ? arg.substring(2) : args[++i]; int propDiv = propLine.indexOf('='); if (-1 != propDiv) { cmdLineProps.put(propLine.substring(0, propDiv), propLine.substring(propDiv + 1)); } } else if (arg.startsWith("-")) { help(); return; } else { movieLibraryRoot = args[i]; } } } catch (Exception error) { LOG.error("Wrong arguments specified"); help(); return; } // Save the name of the properties file for use later setProperty("userPropertiesName", userPropertiesName); LOG.info("Processing started at {}", new Date()); LOG.info(""); // Load the moviejukebox-default.properties file if (!setPropertiesStreamName("./properties/moviejukebox-default.properties", Boolean.TRUE)) { return; } // Load the user properties file "moviejukebox.properties" // No need to abort if we don't find this file // Must be read before the skin, because this may contain an override skin setPropertiesStreamName(userPropertiesName, Boolean.FALSE); // Grab the skin from the command-line properties if (cmdLineProps.containsKey(SKIN_DIR)) { setProperty(SKIN_DIR, cmdLineProps.get(SKIN_DIR)); } // Load the skin.properties file if (!setPropertiesStreamName(getProperty(SKIN_DIR, SKIN_DEFAULT) + "/skin.properties", Boolean.TRUE)) { return; } // Load the skin-user.properties file (ignore the error) setPropertiesStreamName(getProperty(SKIN_DIR, SKIN_DEFAULT) + "/skin-user.properties", Boolean.FALSE); // Load the overlay.properties file (ignore the error) String overlayRoot = getProperty("mjb.overlay.dir", Movie.UNKNOWN); overlayRoot = (PropertiesUtil.getBooleanProperty("mjb.overlay.skinroot", Boolean.TRUE) ? (getProperty(SKIN_DIR, SKIN_DEFAULT) + File.separator) : "") + (StringTools.isValidString(overlayRoot) ? (overlayRoot + File.separator) : ""); setPropertiesStreamName(overlayRoot + "overlay.properties", Boolean.FALSE); // Load the apikeys.properties file if (!setPropertiesStreamName("./properties/apikeys.properties", Boolean.TRUE)) { return; } // This is needed to update the static reference for the API Keys in the pattern formatter // because the formatter is initialised before the properties files are read FilteringLayout.addApiKeys(); // Load the rest of the command-line properties for (Map.Entry<String, String> propEntry : cmdLineProps.entrySet()) { setProperty(propEntry.getKey(), propEntry.getValue()); } // Read the information about the skin SkinProperties.readSkinVersion(); // Display the information about the skin SkinProperties.printSkinVersion(); StringBuilder properties = new StringBuilder("{"); for (Map.Entry<Object, Object> propEntry : PropertiesUtil.getEntrySet()) { properties.append(propEntry.getKey()); properties.append("="); properties.append(propEntry.getValue()); properties.append(","); } properties.replace(properties.length() - 1, properties.length(), "}"); // Print out the properties to the log file. LOG.debug("Properties: {}", properties.toString()); // Check for mjb.skipIndexGeneration and set as necessary // This duplicates the "-i" functionality, but allows you to have it in the property file skipIndexGeneration = PropertiesUtil.getBooleanProperty("mjb.skipIndexGeneration", Boolean.FALSE); if (PropertiesUtil.getBooleanProperty("mjb.people", Boolean.FALSE)) { peopleScan = Boolean.TRUE; peopleScrape = PropertiesUtil.getBooleanProperty("mjb.people.scrape", Boolean.TRUE); peopleMax = PropertiesUtil.getIntProperty("mjb.people.maxCount", 10); popularity = PropertiesUtil.getIntProperty("mjb.people.popularity", 5); // Issue 1947: Cast enhancement - option to save all related files to a specific folder peopleFolder = PropertiesUtil.getProperty("mjb.people.folder", ""); if (isNotValidString(peopleFolder)) { peopleFolder = ""; } else if (!peopleFolder.endsWith(File.separator)) { peopleFolder += File.separator; } StringTokenizer st = new StringTokenizer( PropertiesUtil.getProperty("photo.scanner.photoExtensions", "jpg,jpeg,gif,bmp,png"), ",;| "); while (st.hasMoreTokens()) { PHOTO_EXTENSIONS.add(st.nextToken()); } } // Check for mjb.skipHtmlGeneration and set as necessary // This duplicates the "-h" functionality, but allows you to have it in the property file skipHtmlGeneration = PropertiesUtil.getBooleanProperty("mjb.skipHtmlGeneration", Boolean.FALSE); // Look for the parameter in the properties file if it's not been set on the command line // This way we don't overwrite the setting if it's not found and defaults to FALSE showMemory = PropertiesUtil.getBooleanProperty("mjb.showMemory", Boolean.FALSE); // This duplicates the "-c" functionality, but allows you to have it in the property file jukeboxClean = PropertiesUtil.getBooleanProperty("mjb.jukeboxClean", Boolean.FALSE); MovieFilenameScanner.setSkipKeywords( tokenizeToArray(getProperty("filename.scanner.skip.keywords", ""), ",;| "), PropertiesUtil.getBooleanProperty("filename.scanner.skip.caseSensitive", Boolean.TRUE)); MovieFilenameScanner.setSkipRegexKeywords( tokenizeToArray(getProperty("filename.scanner.skip.keywords.regex", ""), ","), PropertiesUtil.getBooleanProperty("filename.scanner.skip.caseSensitive.regex", Boolean.TRUE)); MovieFilenameScanner.setExtrasKeywords( tokenizeToArray(getProperty("filename.extras.keywords", "trailer,extra,bonus"), ",;| ")); MovieFilenameScanner.setMovieVersionKeywords(tokenizeToArray( getProperty("filename.movie.versions.keywords", "remastered,directors cut,extended cut,final cut"), ",;|")); MovieFilenameScanner.setLanguageDetection( PropertiesUtil.getBooleanProperty("filename.scanner.language.detection", Boolean.TRUE)); final KeywordMap languages = PropertiesUtil.getKeywordMap("filename.scanner.language.keywords", null); if (!languages.isEmpty()) { MovieFilenameScanner.clearLanguages(); for (String lang : languages.getKeywords()) { String values = languages.get(lang); if (values != null) { MovieFilenameScanner.addLanguage(lang, values, values); } else { LOG.info("No values found for language code '{}'", lang); } } } final KeywordMap sourceKeywords = PropertiesUtil.getKeywordMap("filename.scanner.source.keywords", "HDTV,PDTV,DVDRip,DVDSCR,DSRip,CAM,R5,LINE,HD2DVD,DVD,DVD5,DVD9,HRHDTV,MVCD,VCD,TS,VHSRip,BluRay,HDDVD,D-THEATER,SDTV"); MovieFilenameScanner.setSourceKeywords(sourceKeywords.getKeywords(), sourceKeywords); String temp = getProperty("sorting.strip.prefixes"); if (temp != null) { StringTokenizer st = new StringTokenizer(temp, ","); while (st.hasMoreTokens()) { String token = st.nextToken().trim(); if (token.startsWith("\"") && token.endsWith("\"")) { token = token.substring(1, token.length() - 1); } Movie.addSortIgnorePrefixes(token.toLowerCase()); } } enableWatchScanner = PropertiesUtil.getBooleanProperty("watched.scanner.enable", Boolean.TRUE); enableWatchTraktTv = PropertiesUtil.getBooleanProperty("watched.trakttv.enable", Boolean.FALSE); enableCompleteMovies = PropertiesUtil.getBooleanProperty("complete.movies.enable", Boolean.TRUE); // Check to see if don't have a root, check the property file if (StringTools.isNotValidString(movieLibraryRoot)) { movieLibraryRoot = getProperty("mjb.libraryRoot"); if (StringTools.isValidString(movieLibraryRoot)) { LOG.info("Got libraryRoot from properties file: {}", movieLibraryRoot); } else { LOG.error("No library root found!"); help(); return; } } if (jukeboxRoot == null) { jukeboxRoot = getProperty("mjb.jukeboxRoot"); if (jukeboxRoot == null) { LOG.info("jukeboxRoot is null in properties file. Please fix this as it may cause errors."); } else { LOG.info("Got jukeboxRoot from properties file: {}", jukeboxRoot); } } File f = new File(movieLibraryRoot); if (f.exists() && f.isDirectory() && jukeboxRoot == null) { jukeboxRoot = movieLibraryRoot; } if (movieLibraryRoot == null) { help(); return; } if (jukeboxRoot == null) { LOG.info("Wrong arguments specified: you must define the jukeboxRoot property (-o) !"); help(); return; } if (!f.exists()) { LOG.error("Directory or library configuration file '{}', not found.", movieLibraryRoot); return; } FileTools.initUnsafeChars(); FileTools.initSubtitleExtensions(); // make canonical names jukeboxRoot = FileTools.getCanonicalPath(jukeboxRoot); movieLibraryRoot = FileTools.getCanonicalPath(movieLibraryRoot); MovieJukebox ml = new MovieJukebox(movieLibraryRoot, jukeboxRoot); if (dumpLibraryStructure) { LOG.warn( "WARNING !!! A dump of your library directory structure will be generated for debug purpose. !!! Library won't be built or updated"); ml.makeDumpStructure(); } else { ml.generateLibrary(); } // Now rename the log files renameLogFile(); if (ScanningLimit.isLimitReached()) { LOG.warn("Scanning limit of {} was reached, please re-run to complete processing.", ScanningLimit.getLimit()); System.exit(EXIT_SCAN_LIMIT); } else { System.exit(EXIT_NORMAL); } }
From source file:MainGeneratePicasaIniFile.java
public static void main(String[] args) { try {// w ww .java2 s .c o 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:net.sf.extjwnl.cli.ewn.java
public static void main(String[] args) throws IOException, JWNLException { if (args.length < 1) { System.out.println(USAGE); System.exit(0);// w w w . j a va 2 s . c om } //find dictionary Dictionary d = null; File config = new File(defaultConfig); if (!config.exists()) { if (System.getenv().containsKey("WNHOME")) { String wnHomePath = System.getenv().get("WNHOME"); File wnHome = new File(wnHomePath); if (wnHome.exists()) { d = Dictionary.getFileBackedInstance(wnHomePath); } else { log.error("Cannot find dictionary. Make sure " + defaultConfig + " is available or WNHOME variable is set."); } } } else { d = Dictionary.getInstance(new FileInputStream(config)); } if (null != d) { //parse and execute command line if ((-1 < args[0].indexOf('%') && -1 < args[0].indexOf(':')) || "-script".equals(args[0]) || (-1 < args[0].indexOf('#'))) { d.edit(); //edit if ("-script".equals(args[0])) { if (args.length < 2) { log.error("Filename missing for -script command"); System.exit(1); } else { File script = new File(args[1]); if (script.exists()) { //load into args ArrayList<String> newArgs = new ArrayList<String>(); BufferedReader in = new BufferedReader( new InputStreamReader(new FileInputStream(script), "UTF-8")); try { String str; while ((str = in.readLine()) != null) { String[] bits = str.split(" "); StringBuilder tempArg = null; for (String bit : bits) { int quoteCnt = 0; for (int j = 0; j < bit.length(); j++) { if ('"' == bit.charAt(j)) { quoteCnt++; } } if (null != tempArg) { if (0 == quoteCnt) { tempArg.append(" ").append(bit); } else { tempArg.append(" ").append(bit.replaceAll("\"\"", "\"")); if (1 == (quoteCnt % 2)) { newArgs.add( tempArg.toString().substring(1, tempArg.length() - 1)); tempArg = null; } } } else { if (0 == quoteCnt) { newArgs.add(bit); } else { if (1 == (quoteCnt % 2)) { tempArg = new StringBuilder(bit.replaceAll("\"\"", "\"")); } else { newArgs.add(bit.replaceAll("\"\"", "\"")); } } } } if (null != tempArg) { newArgs.add(tempArg.toString()); } } } finally { try { in.close(); } catch (IOException e) { //nop } } args = newArgs.toArray(args); } } } Word workWord = null; String key = null; String lemma = null; int lexFileNum = -1; int lexId = -1; // String headLemma = null; // int headLexId = -1; POS pos = null; String derivation = null; for (int i = 0; i < args.length; i++) { if (null == key && '-' != args[i].charAt(0) && ((-1 < args[i].indexOf('%') && -1 < args[i].indexOf(':')))) { key = args[i]; log.info("Searching " + key + "..."); if (null != key) { workWord = d.getWordBySenseKey(key); } if (null == workWord) { //parse sensekey lemma = key.substring(0, key.indexOf('%')).replace('_', ' '); String posId = key.substring(key.indexOf('%') + 1, key.indexOf(':')); if ("1".equals(posId) || "2".equals(posId) || "3".equals(posId) || "4".equals(posId) || "5".equals(posId)) { pos = POS.getPOSForId(Integer.parseInt(posId)); String lexFileString = key.substring(key.indexOf(':') + 1); if (-1 < lexFileString.indexOf(':')) { lexFileNum = Integer .parseInt(lexFileString.substring(0, lexFileString.indexOf(':'))); if (lexFileString.indexOf(':') + 1 < lexFileString.length()) { String lexIdString = lexFileString .substring(lexFileString.indexOf(':') + 1); if (-1 < lexIdString.indexOf(':')) { lexId = Integer .parseInt(lexIdString.substring(0, lexIdString.indexOf(':'))); // if (lexIdString.indexOf(':') + 1 < lexIdString.length()) { // headLemma = lexIdString.substring(lexIdString.indexOf(':') + 1); // if (-1 < headLemma.indexOf(':')) { // headLemma = headLemma.substring(0, headLemma.indexOf(':')); // if (null != headLemma && !"".equals(headLemma) && lexIdString.lastIndexOf(':') + 1 < lexIdString.length()) { // headLexId = Integer.parseInt(lexIdString.substring(lexIdString.lastIndexOf(':') + 1)); // } // } else { // log.error("Malformed sensekey " + key); // System.exit(1); // } // } } else { log.error("Malformed sensekey " + key); System.exit(1); } } else { log.error("Malformed sensekey " + key); System.exit(1); } } else { log.error("Malformed sensekey " + key); System.exit(1); } } else { log.error("Malformed sensekey " + key); System.exit(1); } } } else if (-1 < args[i].indexOf('#')) { if (2 < args[i].length()) { derivation = args[i].substring(2); if (null == derivation) { log.error("Missing derivation"); System.exit(1); } else { pos = POS.getPOSForKey(args[i].substring(0, 1)); if (null == pos) { log.error("POS " + args[i] + " is not recognized for derivation " + derivation); System.exit(1); } } } } if ("-add".equals(args[i])) { if (null == key) { log.error("Missing sensekey"); System.exit(1); } if (null != workWord) { log.error("Duplicate sensekey " + workWord.getSenseKey()); System.exit(1); } log.info("Creating " + pos.getLabel() + " synset..."); Synset tempSynset = d.createSynset(pos); log.info("Creating word " + lemma + "..."); workWord = new Word(d, tempSynset, 1, lemma); workWord.setLexId(lexId); tempSynset.getWords().add(workWord); tempSynset.setLexFileNum(lexFileNum); key = null; } if ("-remove".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { d.removeSynset(workWord.getSynset()); workWord = null; key = null; } } if ("-addword".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { i++; if (i < args.length && '-' != args[i].charAt(0)) { Word tempWord = new Word(d, workWord.getSynset(), workWord.getSynset().getWords().size() + 1, args[i]); workWord.getSynset().getWords().add(tempWord); key = null; } else { log.error( "Missing word for addword command for sensekey " + workWord.getSenseKey()); System.exit(1); } } } if ("-removeword".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { workWord.getSynset().getWords().remove(workWord); key = null; } } if ("-setgloss".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { i++; if (i < args.length && '-' != args[i].charAt(0)) { workWord.getSynset().setGloss(args[i]); key = null; } else { log.error("Missing gloss for setgloss command for sensekey " + workWord.getSenseKey()); System.exit(1); } } } if ("-setadjclus".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { i++; if (i < args.length && '-' != args[i].charAt(0)) { workWord.getSynset().setIsAdjectiveCluster(Boolean.parseBoolean(args[i])); key = null; } else { log.error("Missing flag for setadjclus command for sensekey " + workWord.getSenseKey()); System.exit(1); } } } if ("-setverbframe".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { i++; if (i < args.length) { if (workWord instanceof Verb) { Verb verb = (Verb) workWord; if ('-' == args[i].charAt(0)) { verb.getVerbFrameFlags().clear(Integer.parseInt(args[i].substring(1))); } else { verb.getVerbFrameFlags().set(Integer.parseInt(args[i])); } } else { log.error("Word at " + workWord.getSenseKey() + " should be verb"); System.exit(1); } key = null; } else { log.error("Missing index for setverbframe command for sensekey " + workWord.getSenseKey()); System.exit(1); } } } if ("-setverbframeall".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { i++; if (i < args.length) { if (workWord.getSynset() instanceof VerbSynset) { if ('-' == args[i].charAt(0)) { workWord.getSynset().getVerbFrameFlags() .clear(Integer.parseInt(args[i].substring(1))); } else { workWord.getSynset().getVerbFrameFlags().set(Integer.parseInt(args[i])); } } else { log.error("Synset at " + workWord.getSenseKey() + " should be verb"); System.exit(1); } key = null; } else { log.error("Missing index for setverbframeall command for sensekey " + workWord.getSenseKey()); System.exit(1); } } } if ("-setlexfile".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { i++; if (i < args.length && '-' != args[i].charAt(0)) { if (-1 < args[i].indexOf('.')) { workWord.getSynset() .setLexFileNum(LexFileNameLexFileIdMap.getMap().get(args[i])); } else { workWord.getSynset().setLexFileNum(Integer.parseInt(args[i])); } } else { log.error("Missing file number or name for setlexfile command for sensekey " + workWord.getSenseKey()); System.exit(1); } } } if ("-addptr".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { i++; if (i < args.length) { Word targetWord = d.getWordBySenseKey(args[i]); if (null != targetWord) { i++; if (i < args.length) { PointerType pt = PointerType.getPointerTypeForKey(args[i]); if (null != pt) { Pointer p; if (pt.isLexical()) { p = new Pointer(pt, workWord, targetWord); } else { p = new Pointer(pt, workWord.getSynset(), targetWord.getSynset()); } if (!workWord.getSynset().getPointers().contains(p)) { workWord.getSynset().getPointers().add(p); } else { log.error("Duplicate pointer of type " + pt + " to " + targetWord.getSenseKey() + " in addptr command for sensekey " + workWord.getSenseKey()); System.exit(1); } } else { log.error("Invalid pointer type at " + args[i] + " in addptr command for sensekey " + workWord.getSenseKey()); System.exit(1); } } else { log.error("Missing pointer type at " + args[i] + " in addptr command for sensekey " + workWord.getSenseKey()); System.exit(1); } } else { log.error("Missing target at " + args[i] + " in addptr command for sensekey " + workWord.getSenseKey()); System.exit(1); } key = null; } else { log.error("Missing sensekey for addptr command for sensekey " + workWord.getSenseKey()); System.exit(1); } } } if ("-removeptr".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { i++; if (i < args.length) { Word targetWord = d.getWordBySenseKey(args[i]); if (null != targetWord) { i++; if (i < args.length) { PointerType pt = PointerType.getPointerTypeForKey(args[i]); if (null != pt) { Pointer p; if (pt.isLexical()) { p = new Pointer(pt, workWord, targetWord); } else { p = new Pointer(pt, workWord.getSynset(), targetWord.getSynset()); } if (workWord.getSynset().getPointers().contains(p)) { workWord.getSynset().getPointers().remove(p); } else { log.error("Missing pointer of type " + pt + " to " + targetWord.getSenseKey() + " in removeptr command for sensekey " + workWord.getSenseKey()); System.exit(1); } } else { log.error("Invalid pointer type at " + args[i] + " in removeptr command for sensekey " + workWord.getSenseKey()); System.exit(1); } } else { log.error("Missing pointer type at " + args[i] + " in removeptr command for sensekey " + workWord.getSenseKey()); System.exit(1); } } else { log.error("Missing target at " + args[i] + " in removeptr command for sensekey " + workWord.getSenseKey()); System.exit(1); } key = null; } else { log.error("Missing sensekey for removeptr command for sensekey " + workWord.getSenseKey()); System.exit(1); } } } if ("-setlexid".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { i++; if (i < args.length && '-' != args[i].charAt(0)) { workWord.setLexId(Integer.parseInt(args[i])); key = null; } else { log.error("Missing lexid for setlexid command for sensekey " + workWord.getSenseKey()); System.exit(1); } } } if ("-setusecount".equals(args[i])) { if (null == workWord) { log.error("Missing sensekey"); System.exit(1); } else { i++; if (i < args.length && '-' != args[i].charAt(0)) { workWord.setUseCount(Integer.parseInt(args[i])); key = null; } else { log.error("Missing count for setusecount command for sensekey " + workWord.getSenseKey()); System.exit(1); } } } if ("-addexc".equals(args[i])) { i++; if (i < args.length && '-' != args[i].charAt(0)) { String baseform = args[i]; Exc e = d.getException(pos, derivation); if (null != e) { if (null != e.getExceptions()) { if (!e.getExceptions().contains(baseform)) { e.getExceptions().add(baseform); } } } else { ArrayList<String> list = new ArrayList<String>(1); list.add(baseform); d.createException(pos, derivation, list); } derivation = null; } else { log.error("Missing baseform for addexc command for derivation " + derivation); System.exit(1); } } if ("-removeexc".equals(args[i])) { Exc e = d.getException(pos, derivation); if (null != e) { i++; if (i < args.length && '-' != args[i].charAt(0)) { String baseform = args[i]; if (null != e.getExceptions()) { if (e.getExceptions().contains(baseform)) { e.getExceptions().remove(baseform); } if (0 == e.getExceptions().size()) { d.removeException(e); } } } else { d.removeException(e); } } else { log.error("Missing derivation " + derivation); System.exit(1); } derivation = null; } } d.save(); } else { //browse String key = args[0]; if (1 == args.length) { for (POS pos : POS.getAllPOS()) { IndexWord iw = d.getIndexWord(pos, key); if (null == iw) { System.out.println("\nNo information available for " + pos.getLabel() + " " + key); } else { System.out.println( "\nInformation available for " + iw.getPOS().getLabel() + " " + iw.getLemma()); printAvailableInfo(iw); } if (null != d.getMorphologicalProcessor()) { List<String> forms = d.getMorphologicalProcessor().lookupAllBaseForms(pos, key); if (null != forms) { for (String form : forms) { if (!key.equals(form)) { iw = d.getIndexWord(pos, form); if (null != iw) { System.out.println("\nInformation available for " + iw.getPOS().getLabel() + " " + iw.getLemma()); printAvailableInfo(iw); } } } } } } } else { boolean needHelp = false; boolean needGloss = false; boolean needLex = false; boolean needOffset = false; boolean needSenseNum = false; boolean needSenseKeys = false; int needSense = 0; for (String arg : args) { if ("-h".equals(arg)) { needHelp = true; } if ("-g".equals(arg)) { needGloss = true; } if ("-a".equals(arg)) { needLex = true; } if ("-o".equals(arg)) { needOffset = true; } if ("-s".equals(arg)) { needSenseNum = true; } if ("-k".equals(arg)) { needSenseKeys = true; } if (arg.startsWith("-n") && 2 < arg.length()) { needSense = Integer.parseInt(arg.substring(2)); } } for (String arg : args) { if (arg.startsWith("-ants") && 6 == arg.length()) { if (needHelp) { System.out.println( "Display synsets containing direct antonyms of the search string.\n" + "\n" + "Direct antonyms are a pair of words between which there is an\n" + "associative bond built up by co-occurrences.\n" + "\n" + "Antonym synsets are preceded by \"=>\"."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nAntonyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.ANTONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //ants if (arg.startsWith("-hype") && 6 == arg.length()) { if (needHelp) { System.out.println( "Recursively display hypernym (superordinate) tree for the search\n" + "string.\n" + "\n" + "Hypernym is the generic term used to designate a whole class of\n" + "specific instances. Y is a hypernym of X if X is a (kind of) Y.\n" + "\n" + "Hypernym synsets are preceded by \"=>\", and are indented from\n" + "the left according to their level in the hierarchy."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nHypernyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.HYPERNYM, PointerUtils.INFINITY, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //hype if (arg.startsWith("-hypo") && 6 == arg.length()) { if (needHelp) { System.out.println( "Display immediate hyponyms (subordinates) for the search string.\n" + "\n" + "Hyponym is the generic term used to designate a member of a class.\n" + "X is a hyponym of Y if X is a (kind of) Y.\n" + "\n" + "Hyponym synsets are preceded by \"=>\"."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nHyponyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.HYPONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //hypo if (arg.startsWith("-tree") && 6 == arg.length()) { if (needHelp) { System.out.println( "Display hyponym (subordinate) tree for the search string. This is\n" + "a recursive search that finds the hyponyms of each hyponym. \n" + "\n" + "Hyponym is the generic term used to designate a member of a class.\n" + "X is a hyponym of Y if X is a (kind of) Y. \n" + "\n" + "Hyponym synsets are preceded by \"=>\", and are indented from the left\n" + "according to their level in the hierarchy."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nHyponyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.HYPONYM, PointerUtils.INFINITY, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //tree if (arg.startsWith("-enta") && 6 == arg.length()) { if (needHelp) { System.out.println( "Recursively display entailment relations of the search string.\n" + "\n" + "The action represented by the verb X entails Y if X cannot be done\n" + "unless Y is, or has been, done.\n" + "\n" + "Entailment synsets are preceded by \"=>\", and are indented from the left\n" + "according to their level in the hierarchy."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nEntailment of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.ENTAILMENT, PointerUtils.INFINITY, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //enta if (arg.startsWith("-syns") && 6 == arg.length()) { POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nSynonyms of " + p.getLabel() + " " + iw.getLemma()); if (POS.ADJECTIVE == p) { if (needHelp) { System.out.println( "Display synonyms and synsets related to synsets containing\n" + "the search string. If the search string is in a head synset\n" + "the 'cluster's' satellite synsets are displayed. If the search\n" + "string is in a satellite synset, its head synset is displayed.\n" + "If the search string is a pertainym the word or synset that it\n" + "pertains to is displayed.\n" + "\n" + "A cluster is a group of adjective synsets that are organized around\n" + "antonymous pairs or triplets. An adjective cluster contains two or more\n" + "head synsets that contan antonyms. Each head synset has one or more\n" + "satellite synsets.\n" + "\n" + "A head synset contains at least one word that has a direct antonym\n" + "in another head synset of the same cluster.\n" + "\n" + "A satellite synset represents a concept that is similar in meaning to\n" + "the concept represented by its head synset.\n" + "\n" + "Direct antonyms are a pair of words between which there is an\n" + "associative bond built up by co-occurrences.\n" + "\n" + "Direct antonyms are printed in parentheses following the adjective.\n" + "The position of an adjective in relation to the noun may be restricted\n" + "to the prenominal, postnominal or predicative position. Where present\n" + "these restrictions are noted in parentheses.\n" + "\n" + "A pertainym is a relational adjective, usually defined by such phrases\n" + "as \"of or pertaining to\" and that does not have an antonym. It pertains\n" + "to a noun or another pertainym.\n" + "\n" + "Senses contained in head synsets are displayed above the satellites,\n" + "which are indented and preceded by \"=>\". Senses contained in\n" + "satellite synsets are displayed with the head synset below. The head\n" + "synset is preceded by \"=>\".\n" + "\n" + "Pertainym senses display the word or synsets that the search string\n" + "pertains to."); } tracePointers(iw, PointerType.SIMILAR_TO, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.PARTICIPLE_OF, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } if (POS.ADVERB == p) { if (needHelp) { System.out.println( "Display synonyms and synsets related to synsets containing\n" + "the search string. If the search string is a pertainym the word\n" + "or synset that it pertains to is displayed.\n" + "\n" + "A pertainym is a relational adverb that is derived from an adjective.\n" + "\n" + "Pertainym senses display the word that the search string is derived from\n" + "and the adjective synset that contains the word. If the adjective synset\n" + "is a satellite synset, its head synset is also displayed."); } tracePointers(iw, PointerType.PERTAINYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } if (POS.NOUN == p || POS.VERB == p) { if (needHelp) { System.out.println( "Recursively display hypernym (superordinate) tree for the search\n" + "string.\n" + "\n" + "Hypernym is the generic term used to designate a whole class of\n" + "specific instances. Y is a hypernym of X if X is a (kind of) Y.\n" + "\n" + "Hypernym synsets are preceded by \"=>\", and are indented from\n" + "the left according to their level in the hierarchy."); } tracePointers(iw, PointerType.HYPERNYM, PointerUtils.INFINITY, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } } //syns if (arg.startsWith("-smem") && 6 == arg.length()) { if (needHelp) { System.out.println("Display all holonyms of the search string.\n" + "\n" + "A holonym is the name of the whole of which the 'meronym' names a part.\n" + "Y is a holonym of X if X is a part of Y.\n" + "\n" + "A meronym is the name of a constituent part, the substance of, or a\n" + "member of something. X is a meronym of Y if X is a part of Y."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nMember Holonyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.MEMBER_HOLONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //smem if (arg.startsWith("-ssub") && 6 == arg.length()) { if (needHelp) { System.out.println("Display all holonyms of the search string.\n" + "\n" + "A holonym is the name of the whole of which the 'meronym' names a part.\n" + "Y is a holonym of X if X is a part of Y.\n" + "\n" + "A meronym is the name of a constituent part, the substance of, or a\n" + "member of something. X is a meronym of Y if X is a part of Y."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nSubstance Holonyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.SUBSTANCE_HOLONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //ssub if (arg.startsWith("-sprt") && 6 == arg.length()) { if (needHelp) { System.out.println("Display all holonyms of the search string.\n" + "\n" + "A holonym is the name of the whole of which the 'meronym' names a part.\n" + "Y is a holonym of X if X is a part of Y.\n" + "\n" + "A meronym is the name of a constituent part, the substance of, or a\n" + "member of something. X is a meronym of Y if X is a part of Y."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nPart Holonyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.PART_HOLONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //sprt if (arg.startsWith("-memb") && 6 == arg.length()) { if (needHelp) { System.out.println("Display all meronyms of the search string. \n" + "\n" + "A meronym is the name of a constituent part, the substance of, or a\n" + "member of something. X is a meronym of Y if X is a part of Y.\n" + "\n" + "A holonym is the name of the whole of which the meronym names a part.\n" + "Y is a holonym of X if X is a part of Y."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nMember Meronyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.MEMBER_MERONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //memb if (arg.startsWith("-subs") && 6 == arg.length()) { if (needHelp) { System.out.println("Display all meronyms of the search string. \n" + "\n" + "A meronym is the name of a constituent part, the substance of, or a\n" + "member of something. X is a meronym of Y if X is a part of Y.\n" + "\n" + "A holonym is the name of the whole of which the meronym names a part.\n" + "Y is a holonym of X if X is a part of Y."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nSubstance Meronyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.SUBSTANCE_MERONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //subs if (arg.startsWith("-part") && 6 == arg.length()) { if (needHelp) { System.out.println("Display all meronyms of the search string. \n" + "\n" + "A meronym is the name of a constituent part, the substance of, or a\n" + "member of something. X is a meronym of Y if X is a part of Y.\n" + "\n" + "A holonym is the name of the whole of which the meronym names a part.\n" + "Y is a holonym of X if X is a part of Y."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nPart Meronyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.PART_MERONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //part if (arg.startsWith("-mero") && 6 == arg.length()) { if (needHelp) { System.out.println("Display all meronyms of the search string. \n" + "\n" + "A meronym is the name of a constituent part, the substance of, or a\n" + "member of something. X is a meronym of Y if X is a part of Y.\n" + "\n" + "A holonym is the name of the whole of which the meronym names a part.\n" + "Y is a holonym of X if X is a part of Y."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nMeronyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.MEMBER_MERONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.SUBSTANCE_MERONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.PART_MERONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //mero if (arg.startsWith("-holo") && 6 == arg.length()) { if (needHelp) { System.out.println("Display all holonyms of the search string.\n" + "\n" + "A holonym is the name of the whole of which the 'meronym' names a part.\n" + "Y is a holonym of X if X is a part of Y.\n" + "\n" + "A meronym is the name of a constituent part, the substance of, or a\n" + "member of something. X is a meronym of Y if X is a part of Y."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nHolonyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.MEMBER_HOLONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.SUBSTANCE_HOLONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.PART_HOLONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //holo if (arg.startsWith("-caus") && 6 == arg.length()) { if (needHelp) { System.out.println("Recursively display CAUSE TO relations of the search string.\n" + "\n" + "The action represented by the verb X causes the action represented by\n" + "the verb Y.\n" + "\n" + "CAUSE TO synsets are preceded by \"=>\", and are indented from the left\n" + "according to their level in the hierarchy."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\n'Cause to' of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.CAUSE, PointerUtils.INFINITY, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //caus if (arg.startsWith("-pert") && 6 == arg.length()) { POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nPertainyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.PERTAINYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //pert if (arg.startsWith("-attr") && 6 == arg.length()) { POS p = POS.getPOSForKey(arg.substring(5)); if (needHelp) { if (POS.NOUN == p) { System.out .println("Display adjectives for which search string is an attribute."); } if (POS.ADJECTIVE == p) { System.out.println("Display nouns that are attributes of search string."); } } IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nAttributes of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.ATTRIBUTE, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //attr if (arg.startsWith("-deri") && 6 == arg.length()) { if (needHelp) { System.out.println( "Display derived forms - nouns and verbs that are related morphologically.\n" + "Each related synset is preceeded by its part of speech. Each word in the\n" + "synset is followed by its sense number."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nDerived forms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.NOMINALIZATION, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //deri if (arg.startsWith("-domn") && 6 == arg.length()) { if (needHelp) { System.out.println("Display domain to which this synset belongs."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nDomain of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.CATEGORY, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.USAGE, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.REGION, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //domn if (arg.startsWith("-domt") && 6 == arg.length()) { if (needHelp) { System.out.println("Display all synsets belonging to the domain."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nDomain of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.CATEGORY_MEMBER, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.USAGE_MEMBER, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.REGION_MEMBER, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //domt if (arg.startsWith("-faml") && 6 == arg.length()) { if (needHelp) { System.out.println( "Display familiarity and polysemy information for the search string.\n" + "The polysemy count is the number of senses in WordNet."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { String[] freqs = { "extremely rare", "very rare", "rare", "uncommon", "common", "familiar", "very familiar", "extremely familiar" }; String[] pos = { "a noun", "a verb", "an adjective", "an adverb" }; int cnt = iw.getSenses().size(); int familiar = 0; if (cnt == 0) { familiar = 0; } if (cnt == 1) { familiar = 1; } if (cnt == 2) { familiar = 2; } if (cnt >= 3 && cnt <= 4) { familiar = 3; } if (cnt >= 5 && cnt <= 8) { familiar = 4; } if (cnt >= 9 && cnt <= 16) { familiar = 5; } if (cnt >= 17 && cnt <= 32) { familiar = 6; } if (cnt > 32) { familiar = 7; } System.out.println("\n" + iw.getLemma() + " used as " + pos[p.getId() - 1] + " is " + freqs[familiar] + " (polysemy count = " + cnt + ")"); } } //faml if (arg.startsWith("-fram") && 6 == arg.length()) { if (needHelp) { System.out.println( "Display applicable verb sentence frames for the search string.\n" + "\n" + "A frame is a sentence template illustrating the usage of a verb.\n" + "\n" + "Verb sentence frames are preceded with the string \"*>\" if a sentence\n" + "frame is acceptable for all of the words in the synset, and with \"=>\"\n" + "if a sentence frame is acceptable for the search string only."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nVerb frames of " + p.getLabel() + " " + iw.getLemma()); for (int i = 0; i < iw.getSenses().size(); i++) { Synset synset = iw.getSenses().get(i); for (String vf : synset.getVerbFrames()) { System.out.println("\t*> " + vf); } for (Word word : synset.getWords()) { if (iw.getLemma().equalsIgnoreCase(word.getLemma())) { if (word instanceof Verb) { Verb verb = (Verb) word; for (String vf : verb.getVerbFrames()) { System.out.println("\t=> " + vf); } } } } } } } //fram if (arg.startsWith("-hmer") && 6 == arg.length()) { if (needHelp) { System.out.println( "Display meronyms for search string tree. This is a recursive search\n" + "the prints all the meronyms of the search string and all of its\n" + "hypernyms. \n" + "\n" + "A meronym is the name of a constituent part, the substance of, or a\n" + "member of something. X is a meronym of Y if X is a part of Y."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nMeronyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.MEMBER_MERONYM, PointerUtils.INFINITY, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.SUBSTANCE_MERONYM, PointerUtils.INFINITY, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.PART_MERONYM, PointerUtils.INFINITY, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //hmer if (arg.startsWith("-hhol") && 6 == arg.length()) { if (needHelp) { System.out.println( "\"Display holonyms for search string tree. This is a recursive search\n" + "that prints all the holonyms of the search string and all of the\n" + "holonym's holonyms.\n" + "\n" + "A holonym is the name of the whole of which the meronym names a part.\n" + "Y is a holonym of X if X is a part of Y."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nHolonyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.MEMBER_HOLONYM, PointerUtils.INFINITY, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.SUBSTANCE_HOLONYM, PointerUtils.INFINITY, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.PART_HOLONYM, PointerUtils.INFINITY, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //hhol if (arg.startsWith("-mero") && 6 == arg.length()) { if (needHelp) { System.out.println("Display all meronyms of the search string. \n" + "\n" + "A meronym is the name of a constituent part, the substance of, or a\n" + "member of something. X is a meronym of Y if X is a part of Y.\n" + "\n" + "A holonym is the name of the whole of which the meronym names a part.\n" + "Y is a holonym of X if X is a part of Y."); } POS p = POS.getPOSForKey(arg.substring(5)); IndexWord iw = d.lookupIndexWord(p, key); if (null != iw) { System.out.println("\nMeronyms of " + p.getLabel() + " " + iw.getLemma()); tracePointers(iw, PointerType.MEMBER_MERONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.SUBSTANCE_MERONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); tracePointers(iw, PointerType.PART_MERONYM, 1, needSense, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } //mero if (arg.startsWith("-grep") && 6 == arg.length()) { if (needHelp) { System.out .println("Print all strings in the database containing the search string\n" + "as an individual word, or as the first or last string in a word or\n" + "collocation."); } POS p = POS.getPOSForKey(arg.substring(5)); System.out.println("\nGrep of " + p.getLabel() + " " + key); Iterator<IndexWord> ii = d.getIndexWordIterator(p, key); while (ii.hasNext()) { System.out.println(ii.next().getLemma()); } } //grep if ("-over".equals(arg)) { for (POS pos : POS.getAllPOS()) { if (null != d.getMorphologicalProcessor()) { IndexWord iw = d.getIndexWord(pos, key); //for plurals like species, glasses if (null != iw && key.equals(iw.getLemma())) { printOverview(pos, iw, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } List<String> forms = d.getMorphologicalProcessor().lookupAllBaseForms(pos, key); if (null != forms) { for (String form : forms) { if (!form.equals(key)) { iw = d.getIndexWord(pos, form); if (null != iw) { printOverview(pos, iw, needGloss, needLex, needOffset, needSenseNum, needSenseKeys); } } } } } } } //over } } } } }