List of usage examples for java.lang String isEmpty
public boolean isEmpty()
From source file:com.github.venkateshamurthy.designpatterns.builders.FluentBuilders.java
/** * A main method that accepts a Command line syntax as is represented in * {@value #CMD_LINE_OPTIONS}.// w w w . j a v a2 s . co m * * @param args * need to follow a command line style syntax as indicated by * --help option to get more details * @throws NotFoundException * when CtClass / Class is not found * @throws CannotCompileException * when non-compilable statements are added * @throws IOException * when during io errors * @throws ClassNotFoundException * when CtClass / Class is not found * @throws ParseException * when command line is un-parsable. */ public static void main(final String[] args) throws NotFoundException, CannotCompileException, IOException, ClassNotFoundException, ParseException { final CommandLineParser parser = new DefaultParser(); final HelpFormatter formatter = new HelpFormatter(); final CommandLine cmdLine = parser.parse(CMD_LINE_OPTIONS, args); if (HELP.selected(cmdLine)) { formatter.printHelp(FluentBuilders.class.getSimpleName() + ":", CMD_LINE_OPTIONS); System.exit(0); } final String classNamesCSV = getClassNamesAsCSV(cmdLine); if (classNamesCSV == null || classNamesCSV.isEmpty()) { formatter.printHelp(FluentBuilders.class.getSimpleName() + ":", CMD_LINE_OPTIONS); throw new IllegalArgumentException("Argument to this program needs to be a comma separated list " + "of well defined, valid and fully qualified POJO class names"); } final String setNamePattern = SET_METHOD_PATTERN.option(cmdLine, TYPICAL_SET_METHOD_PATTERN); final String srcFolderName = SRC_FOLDER.option(cmdLine, TYPICAL_SOURCE_FOLDER); final FluentBuilders fluentBuilders = FluentBuilders.create(setNamePattern, srcFolderName); fluentBuilders.writeInterface(getClassArray(classNamesCSV)); }
From source file:com.curecomp.primefaces.migrator.PrimefacesMigration.java
public static void main(String[] args) throws Exception { // Let's use some colors :) // AnsiConsole.systemInstall(); CommandLineParser cliParser = new BasicParser(); CommandLine cli = null;//from w w w . ja v a 2s . c o m try { cli = cliParser.parse(OPTIONS, args); } catch (ParseException e) { printHelp(); } if (!cli.hasOption("s")) { printHelp(); } String sourcePattern; if (cli.hasOption("p")) { sourcePattern = cli.getOptionValue("p"); } else { sourcePattern = DEFAULT_SOURCE_PATTERN; } String defaultAnswer; if (cli.hasOption("default-answer")) { defaultAnswer = cli.getOptionValue("default-answer"); } else { defaultAnswer = DEFAULT_DEFAULT_PROMPT_ANSWER; } boolean defaultAnswerYes = defaultAnswer.equalsIgnoreCase("y"); boolean quiet = cli.hasOption("q"); boolean testWrite = cli.hasOption("t"); Path sourceDirectory = Paths.get(cli.getOptionValue("s")).toAbsolutePath(); // Since we use IO we will have some blocking threads hanging around int threadCount = Runtime.getRuntime().availableProcessors() * 2; ThreadPoolExecutor threadPool = new ThreadPoolExecutor(threadCount, threadCount, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); BlockingQueue<WidgetVarLocation> foundUsages = new LinkedBlockingQueue<>(); BlockingQueue<WidgetVarLocation> unusedOrAmbiguous = new LinkedBlockingQueue<>(); BlockingQueue<WidgetVarLocation> skippedUsages = new LinkedBlockingQueue<>(); List<Future<?>> futures = new ArrayList<>(); findWidgetVars(sourceDirectory, sourcePattern, threadPool).forEach(widgetVarLocation -> { // We can't really find usages of widget vars that use EL expressions :( if (widgetVarLocation.widgetVar.contains("#")) { unusedOrAmbiguous.add(widgetVarLocation); return; } try { FileActionVisitor visitor = new FileActionVisitor(sourceDirectory, sourcePattern, sourceFile -> futures.add(threadPool.submit((Callable<?>) () -> { findWidgetVarUsages(sourceFile, widgetVarLocation, foundUsages, skippedUsages, unusedOrAmbiguous); return null; }))); Files.walkFileTree(sourceDirectory, visitor); } catch (IOException ex) { throw new RuntimeException(ex); } }); awaitAll(futures); new TreeSet<>(skippedUsages).forEach(widgetUsage -> { int startIndex = widgetUsage.columnNr; int endIndex = startIndex + widgetUsage.widgetVar.length(); String relativePath = widgetUsage.location.toAbsolutePath().toString() .substring(sourceDirectory.toString().length()); String previous = replace(widgetUsage.line, startIndex, endIndex, Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString()); System.out.println("Skipped " + relativePath + " at line " + widgetUsage.lineNr + " and col " + widgetUsage.columnNr + " for widgetVar '" + widgetUsage.widgetVar + "'"); System.out.println("\t" + previous); }); Map<WidgetVarLocation, List<WidgetVarLocation>> written = new HashMap<>(); new TreeSet<>(foundUsages).forEach(widgetUsage -> { WidgetVarLocation key = new WidgetVarLocation(null, widgetUsage.location, widgetUsage.lineNr, -1, null); List<WidgetVarLocation> writtenList = written.get(key); int existing = writtenList == null ? 0 : writtenList.size(); int startIndex = widgetUsage.columnNr; int endIndex = startIndex + widgetUsage.widgetVar.length(); String relativePath = widgetUsage.location.toAbsolutePath().toString() .substring(sourceDirectory.toString().length()); String next = replace(widgetUsage.line, startIndex, endIndex, Ansi.ansi().bold().fg(Ansi.Color.RED) .a("PF('" + widgetUsage.widgetVar + "')").reset().toString()); System.out .println(relativePath + " at line " + widgetUsage.lineNr + " and col " + widgetUsage.columnNr); System.out.println("\t" + next); System.out.print("Replace (Y/N)? [" + (defaultAnswerYes ? "Y" : "N") + "]: "); String input; if (quiet) { input = ""; System.out.println(); } else { try { do { input = in.readLine(); } while (input != null && !input.isEmpty() && !"y".equalsIgnoreCase(input) && !"n".equalsIgnoreCase(input)); } catch (IOException ex) { throw new RuntimeException(ex); } } if (input == null) { System.out.println("Aborted!"); } else if (input.isEmpty() && defaultAnswerYes || !input.isEmpty() && !"n".equalsIgnoreCase(input)) { System.out.println("Replaced!"); System.out.print("\t"); if (writtenList == null) { writtenList = new ArrayList<>(); written.put(key, writtenList); } writtenList.add(widgetUsage); List<String> lines; try { lines = Files.readAllLines(widgetUsage.location); } catch (IOException ex) { throw new RuntimeException(ex); } try (OutputStream os = testWrite ? new ByteArrayOutputStream() : Files.newOutputStream(widgetUsage.location); PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))) { String line; for (int i = 0; i < lines.size(); i++) { int lineNr = i + 1; line = lines.get(i); if (lineNr == widgetUsage.lineNr) { int begin = widgetUsage.columnNr + (testWrite ? 0 : existing * 6); int end = begin + widgetUsage.widgetVar.length(); String newLine = replace(line, begin, end, "PF('" + widgetUsage.widgetVar + "')", false); if (testWrite) { System.out.println(newLine); } else { pw.println(newLine); } } else { if (!testWrite) { pw.println(line); } } } } catch (IOException ex) { throw new RuntimeException(ex); } } else { System.out.println("Skipped!"); } }); new TreeSet<>(unusedOrAmbiguous).forEach(widgetUsage -> { int startIndex = widgetUsage.columnNr; int endIndex = startIndex + widgetUsage.widgetVar.length(); String relativePath = widgetUsage.location.toAbsolutePath().toString() .substring(sourceDirectory.toString().length()); String previous = replace(widgetUsage.line, startIndex, endIndex, Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString()); System.out.println("Skipped unused or ambiguous " + relativePath + " at line " + widgetUsage.lineNr + " and col " + widgetUsage.columnNr); System.out.println("\t" + previous); }); threadPool.shutdown(); }
From source file:accinapdf.ACCinaPDF.java
/** * @param args the command line arguments *///from w w w .j a v a2s.c om public static void main(String[] args) { controller.Logger.create(); controller.Bundle.getBundle(); if (GraphicsEnvironment.isHeadless()) { // Headless // Erro String fich; if (args.length != 1) { System.err.println(Bundle.getBundle().getString("invalidArgs")); return; } else { fich = args[0]; } try { System.out.println(Bundle.getBundle().getString("validating") + " " + fich); ArrayList<SignatureValidation> alSv = CCInstance.getInstance().validatePDF(fich, null); if (alSv.isEmpty()) { System.out.println(Bundle.getBundle().getString("notSigned")); } else { String newLine = System.getProperty("line.separator"); String toWrite = "("; int numSigs = alSv.size(); if (numSigs == 1) { toWrite += "1 " + Bundle.getBundle().getString("signature"); } else { toWrite += numSigs + " " + Bundle.getBundle().getString("signatures"); } toWrite += ")" + newLine; for (SignatureValidation sv : alSv) { toWrite += "\t" + sv.getName() + " - "; toWrite += (sv.isCertification() ? WordUtils.capitalize(Bundle.getBundle().getString("certificate")) : WordUtils.capitalize(Bundle.getBundle().getString("signed"))) + " " + Bundle.getBundle().getString("by") + " " + sv.getSignerName(); toWrite += newLine + "\t\t"; if (sv.isChanged()) { toWrite += Bundle.getBundle().getString("certifiedChangedOrCorrupted"); } else { if (sv.isCertification()) { if (sv.isValid()) { if (sv.isChanged() || !sv.isCoversEntireDocument()) { toWrite += Bundle.getBundle().getString("certifiedButChanged"); } else { toWrite += Bundle.getBundle().getString("certifiedOk"); } } else { toWrite += Bundle.getBundle().getString("changedAfterCertified"); } } else { if (sv.isValid()) { if (sv.isChanged()) { toWrite += Bundle.getBundle().getString("signedButChanged"); } else { toWrite += Bundle.getBundle().getString("signedOk"); } } else { toWrite += Bundle.getBundle().getString("signedChangedOrCorrupted"); } } } toWrite += newLine + "\t\t"; if (sv.getOcspCertificateStatus().equals(CertificateStatus.OK) || sv.getCrlCertificateStatus().equals(CertificateStatus.OK)) { toWrite += Bundle.getBundle().getString("certOK"); } else if (sv.getOcspCertificateStatus().equals(CertificateStatus.REVOKED) || sv.getCrlCertificateStatus().equals(CertificateStatus.REVOKED)) { toWrite += Bundle.getBundle().getString("certRevoked"); } else if (sv.getOcspCertificateStatus().equals(CertificateStatus.UNCHECKED) && sv.getCrlCertificateStatus().equals(CertificateStatus.UNCHECKED)) { toWrite += Bundle.getBundle().getString("certNotVerified"); } else if (sv.getOcspCertificateStatus().equals(CertificateStatus.UNCHAINED)) { toWrite += Bundle.getBundle().getString("certNotChained"); } else if (sv.getOcspCertificateStatus().equals(CertificateStatus.EXPIRED)) { toWrite += Bundle.getBundle().getString("certExpired"); } else if (sv.getOcspCertificateStatus().equals(CertificateStatus.CHAINED_LOCALLY)) { toWrite += Bundle.getBundle().getString("certChainedLocally"); } toWrite += newLine + "\t\t"; if (sv.isValidTimeStamp()) { toWrite += Bundle.getBundle().getString("validTimestamp"); } else { toWrite += Bundle.getBundle().getString("signerDateTime"); } toWrite += newLine + "\t\t"; toWrite += WordUtils.capitalize(Bundle.getBundle().getString("revision")) + ": " + sv.getRevision() + " " + Bundle.getBundle().getString("of") + " " + sv.getNumRevisions(); toWrite += newLine + "\t\t"; final DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); final SimpleDateFormat sdf = new SimpleDateFormat("Z"); if (sv.getSignature().getTimeStampToken() == null) { Calendar cal = sv.getSignature().getSignDate(); String date = sdf.format(cal.getTime().toLocaleString()); toWrite += date + " " + sdf.format(cal.getTime()) + " (" + Bundle.getBundle().getString("signerDateTimeSmall") + ")"; } else { Calendar ts = sv.getSignature().getTimeStampDate(); String date = df.format(ts.getTime()); toWrite += Bundle.getBundle().getString("date") + " " + date + " " + sdf.format(ts.getTime()); } toWrite += newLine + "\t\t"; boolean ltv = (sv.getOcspCertificateStatus() == CertificateStatus.OK || sv.getCrlCertificateStatus() == CertificateStatus.OK); toWrite += Bundle.getBundle().getString("isLtv") + ": " + (ltv ? Bundle.getBundle().getString("yes") : Bundle.getBundle().getString("no")); String reason = sv.getSignature().getReason(); toWrite += newLine + "\t\t"; toWrite += Bundle.getBundle().getString("reason") + ": "; if (reason == null) { toWrite += Bundle.getBundle().getString("notDefined"); } else if (reason.isEmpty()) { toWrite += Bundle.getBundle().getString("notDefined"); } else { toWrite += reason; } String location = sv.getSignature().getLocation(); toWrite += newLine + "\t\t"; toWrite += Bundle.getBundle().getString("location") + ": "; if (location == null) { toWrite += Bundle.getBundle().getString("notDefined"); } else if (location.isEmpty()) { toWrite += Bundle.getBundle().getString("notDefined"); } else { toWrite += location; } toWrite += newLine + "\t\t"; toWrite += Bundle.getBundle().getString("allowsChanges") + ": "; try { int certLevel = CCInstance.getInstance().getCertificationLevel(sv.getFilename()); if (certLevel == PdfSignatureAppearance.CERTIFIED_FORM_FILLING) { toWrite += Bundle.getBundle().getString("onlyAnnotations"); } else if (certLevel == PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS) { toWrite += Bundle.getBundle().getString("annotationsFormFilling"); } else if (certLevel == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED) { toWrite += Bundle.getBundle().getString("no"); } else { toWrite += Bundle.getBundle().getString("yes"); } } catch (IOException ex) { controller.Logger.getLogger().addEntry(ex); } toWrite += newLine + "\t\t"; if (sv.getOcspCertificateStatus() == CertificateStatus.OK || sv.getCrlCertificateStatus() == CertificateStatus.OK) { toWrite += (Bundle.getBundle().getString("validationCheck1") + " " + (sv.getOcspCertificateStatus() == CertificateStatus.OK ? Bundle.getBundle().getString("validationCheck2") + ": " + CCInstance.getInstance().getCertificateProperty( sv.getSignature().getOcsp().getCerts()[0].getSubject(), "CN") + " " + Bundle.getBundle().getString("at") + " " + df.format(sv.getSignature().getOcsp().getProducedAt()) : (sv.getCrlCertificateStatus() == CertificateStatus.OK ? "CRL" : "")) + (sv.getSignature().getTimeStampToken() != null ? Bundle.getBundle().getString("validationCheck3") + ": " + CCInstance.getInstance() .getCertificateProperty(sv.getSignature() .getTimeStampToken().getSID().getIssuer(), "O") : "")); } else if (sv.getSignature().getTimeStampToken() != null) { toWrite += (Bundle.getBundle().getString("validationCheck3") + ": " + CCInstance.getInstance().getCertificateProperty( sv.getSignature().getTimeStampToken().getSID().getIssuer(), "O")); } toWrite += newLine; } System.out.println(toWrite); System.out.println(Bundle.getBundle().getString("validationFinished")); } } catch (IOException | DocumentException | GeneralSecurityException ex) { System.err.println(Bundle.getBundle().getString("validationError")); Logger.getLogger(ACCinaPDF.class.getName()).log(Level.SEVERE, null, ex); } } else { // GUI CCSignatureSettings defaultSettings = new CCSignatureSettings(false); if (SystemUtils.IS_OS_WINDOWS) { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { try { UIManager.setLookAndFeel(info.getClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { Logger.getLogger(ACCinaPDF.class.getName()).log(Level.SEVERE, null, ex); } break; } } } else if (SystemUtils.IS_OS_LINUX) { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { try { UIManager.setLookAndFeel(info.getClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { Logger.getLogger(ACCinaPDF.class.getName()).log(Level.SEVERE, null, ex); } break; } } } else if (SystemUtils.IS_OS_MAC_OSX) { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.mac.MacLookAndFeel"); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { Logger.getLogger(ACCinaPDF.class.getName()).log(Level.SEVERE, null, ex); } } new SplashScreen().setVisible(true); } }
From source file:it.codestudio.callbyj.CallByJ.java
/** * The main method./*ww w . j a v a 2 s . c o m*/ * * @param args the arguments */ public static void main(String[] args) { options.addOption("aCom", "audio_com", true, "Specify serial COM port for audio streaming (3G APPLICATION ...)"); options.addOption("cCom", "command_com", true, "Specify serial COM port for modem AT command (PC UI INTERFACE ...)"); options.addOption("p", "play_message", false, "Play recorded message instead to respond with audio from mic"); options.addOption("h", "help", false, "Print help for this application"); try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String audioCOM = ""; String commandCOM = ""; Boolean playMessage = false; args = Utils.fitlerNullString(args); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("aCom")) { audioCOM = cmd.getOptionValue("aCom"); ; } if (cmd.hasOption("cCom")) { commandCOM = cmd.getOptionValue("cCom"); ; } if (cmd.hasOption("p")) { playMessage = true; } if (audioCOM != null && commandCOM != null && !audioCOM.isEmpty() && !commandCOM.isEmpty()) { comManager = ComManager.getInstance(commandCOM, audioCOM, playMessage); } else { HelpFormatter f = new HelpFormatter(); f.printHelp("\r Exaple: CallByJ -aCom COM11 -cCom COM10 \r OptionsTip", options); return; } options = new Options(); options.addOption("h", "help", false, "Print help for this application"); options.addOption("p", "pin", true, "Specify pin of device, if present"); options.addOption("c", "call", true, "Start call to specified number"); options.addOption("e", "end", false, "End all active call"); options.addOption("t", "terminate", false, "Terminate application"); options.addOption("r", "respond", false, "Respond to incoming call"); comManager.startModemCommandManager(); while (true) { try { String[] commands = { br.readLine() }; commands = Utils.fitlerNullString(commands); cmd = parser.parse(options, commands); if (cmd.hasOption('h')) { HelpFormatter f = new HelpFormatter(); f.printHelp("OptionsTip", options); } if (cmd.hasOption('p')) { String devicePin = cmd.getOptionValue("p"); comManager.insertPin(devicePin); } if (cmd.hasOption('c')) { String numberToCall = cmd.getOptionValue("c"); comManager.sendCommandToModem(ATCommands.CALL, numberToCall); } if (cmd.hasOption('r')) { comManager.respondToIncomingCall(); } if (cmd.hasOption('e')) { comManager.sendCommandToModem(ATCommands.END_CALL); } if (cmd.hasOption('t')) { comManager.sendCommandToModem(ATCommands.END_CALL); comManager.terminate(); System.out.println("CallByJ closed!"); break; //System.exit(0); } } catch (Exception e) { logger.error(e.getMessage(), e); } } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (comManager != null) comManager.terminate(); } }
From source file:com.linkedin.databus2.client.util.DatabusClusterUtil.java
/** * @param args// www. j ava 2 s .c om * 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:org.nira.wso2.nexus.ComponentVersion.java
public static void main(String[] args) { urlList.add(Constants.REPO_MAVEN);/* ww w .j a v a 2 s.c o m*/ urlList.add(Constants.REPO_MAVEN_WSO2_RELEASES); urlList.add(Constants.REPO_MAVEN_WSO2_PUBLIC); String pomFilePath = ""; boolean ignoreSameVersion = false; for (String arg : args) { if (arg.startsWith(Constants.CMD_POM_FILE)) { pomFilePath = arg.substring(Constants.CMD_POM_FILE.length() + 1); } else if (arg.startsWith(Constants.CMD_IGNORE_SAME_VERSION)) { String param = arg.substring(Constants.CMD_IGNORE_SAME_VERSION.length() + 1); if ("true".equals(param)) { ignoreSameVersion = true; } } } // pomFilePath = "C:\\Users\\Nira\\Desktop\\as_pom.xml"; if (pomFilePath.isEmpty()) { throw new ComponentException("Pom File path not specified!"); } readPomFile(pomFilePath); displayComponents(ignoreSameVersion); }
From source file:dk.netarkivet.deploy.DeployApplication.java
/** * Run deploy./* ww w . ja v a 2s. com*/ * * @param args The Command-line arguments in no particular order: * * -C The deploy configuration file (ends with .xml). -Z The NetarchiveSuite file to be unpacked (ends with .zip). * -S The security policy file (ends with .policy). -L The logging property file (ends with .prop). -O [OPTIONAL] * The output directory -D [OPTIONAL] The harvest definition database -T [OPTIONAL] The test arguments * (httpportoffset, port, environmentName, mailReceiver) -R [OPTIONAL] For resetting the tempDir (takes arguments * 'y' or 'yes') -E [OPTIONAL] Evaluating the deployConfig file (arguments: 'y' or 'yes') -A [OPTIONAL] For archive * database. -J [OPTIONAL] For deploying with external jar files. Must be the total path to the directory containing * jar-files. These external files will be placed on every machine, and they have to manually be put into the * classpath, where they should be used. */ public static void main(String[] args) { try { // Make sure the arguments can be parsed. if (!ap.parseParameters(args)) { System.err.print(Constants.MSG_ERROR_PARSE_ARGUMENTS); System.out.println(ap.listArguments()); System.exit(1); } // Check arguments if (ap.getCommandLine().getOptions().length < Constants.ARGUMENTS_REQUIRED) { System.err.print(Constants.MSG_ERROR_NOT_ENOUGH_ARGUMENTS); System.out.println(); System.out.println("Use DeployApplication with following arguments:"); System.out.println(ap.listArguments()); System.out.println("outputdir defaults to ./environmentName (set in config file)"); System.exit(1); } // test if more arguments than options is given if (args.length > ap.getOptions().getOptions().size()) { System.err.print(Constants.MSG_ERROR_TOO_MANY_ARGUMENTS); System.out.println(); System.out.println("Maximum " + ap.getOptions().getOptions().size() + "arguments."); System.exit(1); } // Retrieving the configuration filename String deployConfigFileName = ap.getCommandLine().getOptionValue(Constants.ARG_CONFIG_FILE); // Retrieving the NetarchiveSuite filename String netarchiveSuiteFileName = ap.getCommandLine() .getOptionValue(Constants.ARG_NETARCHIVE_SUITE_FILE); // Retrieving the security policy filename String secPolicyFileName = ap.getCommandLine().getOptionValue(Constants.ARG_SECURITY_FILE); // Retrieving the SLF4J xml filename String slf4jConfigFileName = ap.getCommandLine().getOptionValue(Constants.ARG_SLF4J_CONFIG_FILE); // Retrieving the output directory name String outputDir = ap.getCommandLine().getOptionValue(Constants.ARG_OUTPUT_DIRECTORY); // Retrieving the database filename String databaseFileName = ap.getCommandLine().getOptionValue(Constants.ARG_DATABASE_FILE); // Retrieving the test arguments String testArguments = ap.getCommandLine().getOptionValue(Constants.ARG_TEST); // Retrieving the reset argument String resetArgument = ap.getCommandLine().getOptionValue(Constants.ARG_RESET); // Retrieving the evaluate argument String evaluateArgument = ap.getCommandLine().getOptionValue(Constants.ARG_EVALUATE); // Retrieve the archive database filename. String arcDbFileName = ap.getCommandLine().getOptionValue(Constants.ARG_ARC_DB); // Retrieves the jar-folder name. String jarFolderName = ap.getCommandLine().getOptionValue(Constants.ARG_JAR_FOLDER); // Retrieves the source encoding. // If not specified get system default String sourceEncoding = ap.getCommandLine().getOptionValue(Constants.ARG_SOURCE_ENCODING); String msgTail = ""; if (sourceEncoding == null || sourceEncoding.isEmpty()) { sourceEncoding = Charset.defaultCharset().name(); msgTail = " (defaulted)"; } System.out.println("Will read source files using encoding '" + sourceEncoding + "'" + msgTail); // check deployConfigFileName and retrieve the corresponding file initConfigFile(deployConfigFileName); // check netarchiveSuiteFileName and retrieve the corresponding file initNetarchiveSuiteFile(netarchiveSuiteFileName); // check secPolicyFileName and retrieve the corresponding file initSecPolicyFile(secPolicyFileName); initSLF4JXmlFile(slf4jConfigFileName); // check database initDatabase(databaseFileName); // check and apply the test arguments initTestArguments(testArguments); // check reset arguments. initReset(resetArgument); // evaluates the config file initEvaluate(evaluateArgument, sourceEncoding); // check the archive database initArchiveDatabase(arcDbFileName); // check the external jar-files library folder. initJarFolder(jarFolderName); //initBundlerZip(Optional.ofNullable( // ap.getCommandLine().getOptionValue(Constants.ARG_DEFAULT_BUNDLER_ZIP))); initBundlerZip(ap.getCommandLine().getOptionValue(Constants.ARG_DEFAULT_BUNDLER_ZIP)); // Make the configuration based on the input data deployConfig = new DeployConfiguration(deployConfigFile, netarchiveSuiteFile, secPolicyFile, slf4jConfigFile, outputDir, dbFile, arcDbFile, resetDirectory, externalJarFolder, sourceEncoding, defaultBundlerZip); // Write the scripts, directories and everything deployConfig.write(); } catch (SecurityException e) { // This problem should only occur in tests -> thus not err message. System.out.println("SECURITY ERROR: "); e.printStackTrace(); } catch (Throwable e) { System.err.println("DEPLOY APPLICATION ERROR: "); e.printStackTrace(); } }
From source file:GossipP2PServer.java
public static void main(String args[]) { // Arguments that should be passed in int port = -1; String databasePath = ""; // Set up arg options Options options = new Options(); Option p = new Option("p", true, "Port for server to listen on."); options.addOption(p);//from w ww . ja v a 2s. c o m Option d = new Option("d", true, "Path to database."); options.addOption(d); CommandLineParser clp = new DefaultParser(); try { CommandLine cl = clp.parse(options, args); if (cl.hasOption("p")) { port = Integer.parseInt(cl.getOptionValue("p")); } if (cl.hasOption("d")) { databasePath = cl.getOptionValue("d"); } // If we have all we need start the server and setup database. if (port != -1 && !databasePath.isEmpty() && databasePath != null) { Database.getInstance().initializeDatabase(databasePath); runConcurrentServer(port); } else { showArgMenu(options); } } catch (Exception e) { e.printStackTrace(); } }
From source file:DataCrawler.OpenAIRE.XMLGenerator.java
public static void main(String[] args) { String text = ""; try {/*w w w. j av a 2 s . c om*/ if (args.length < 4) { System.out.println("<command> template_file csv_file output_dir log_file [start_id]"); } // InputStream fis = new FileInputStream("E:/Downloads/result-r-00000"); InputStream fis = new FileInputStream(args[1]); BufferedReader br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8"))); // String content = new String(Files.readAllBytes(Paths.get("publications_template.xml"))); String content = new String(Files.readAllBytes(Paths.get(args[0]))); Document doc = Jsoup.parse(content, "UTF-8", Parser.xmlParser()); // String outputDirectory = "G:/"; String outputDirectory = args[2]; // PrintWriter logWriter = new PrintWriter(new FileOutputStream("publication.log",false)); PrintWriter logWriter = new PrintWriter(new FileOutputStream(args[3], false)); Element objectId = null, title = null, publisher = null, dateofacceptance = null, bestlicense = null, resulttype = null, originalId = null, originalId2 = null; boolean start = true; // String startID = "dedup_wf_001::207a098867b64f3b5af505fa3aeecd24"; String startID = ""; if (args.length >= 5) { start = false; startID = args[4]; } String previousText = ""; while ((text = br.readLine()) != null) { /* For publications: 0. dri:objIdentifier context 9. title context 12. publisher context 18. dateofacceptance 19. bestlicense @classname 21. resulttype @classname 26. originalId context (Notice that the prefix is null and will use space to separate two different "originalId") */ if (!previousText.isEmpty()) { text = previousText + text; start = true; previousText = ""; } String[] items = text.split("!"); for (int i = 0; i < items.length; ++i) { items[i] = StringUtils.strip(items[i], "#"); } if (objectId == null) objectId = doc.getElementsByTag("dri:objIdentifier").first(); objectId.text(items[0]); if (!start && items[0].equals(startID)) { start = true; } if (title == null) title = doc.getElementsByTag("title").first(); title.text(items[9]); if (publisher == null) publisher = doc.getElementsByTag("publisher").first(); if (items.length < 12) { previousText = text; continue; } publisher.text(items[12]); if (dateofacceptance == null) dateofacceptance = doc.getElementsByTag("dateofacceptance").first(); dateofacceptance.text(items[18]); if (bestlicense == null) bestlicense = doc.getElementsByTag("bestlicense").first(); bestlicense.attr("classname", items[19]); if (resulttype == null) resulttype = doc.getElementsByTag("resulttype").first(); resulttype.attr("classname", items[21]); if (originalId == null || originalId2 == null) { Elements elements = doc.getElementsByTag("originalId"); String[] context = items[26].split(" "); if (elements.size() > 0) { if (elements.size() >= 1) { originalId = elements.get(0); if (context.length >= 1) { int indexOfnull = context[0].trim().indexOf("null"); String value = ""; if (indexOfnull != -1) { if (context[0].trim().length() >= (indexOfnull + 5)) value = context[0].trim().substring(indexOfnull + 5); } else { value = context[0].trim(); } originalId.text(value); } } if (elements.size() >= 2) { originalId2 = elements.get(1); if (context.length >= 2) { int indexOfnull = context[1].trim().indexOf("null"); String value = ""; if (indexOfnull != -1) { if (context[1].trim().length() >= (indexOfnull + 5)) value = context[1].trim().substring(indexOfnull + 5); } else { value = context[1].trim(); } originalId2.text(value); } } } } else { String[] context = items[26].split(" "); if (context.length >= 1) { int indexOfnull = context[0].trim().indexOf("null"); String value = ""; if (indexOfnull != -1) { if (context[0].trim().length() >= (indexOfnull + 5)) value = context[0].trim().substring(indexOfnull + 5); } else { value = context[0].trim(); } originalId.text(value); } if (context.length >= 2) { int indexOfnull = context[1].trim().indexOf("null"); String value = ""; if (indexOfnull != -1) { if (context[1].trim().length() >= (indexOfnull + 5)) value = context[1].trim().substring(indexOfnull + 5); } else { value = context[1].trim(); } originalId2.text(value); } } if (start) { String filePath = outputDirectory + items[0].replace(":", "#") + ".xml"; PrintWriter writer = new PrintWriter(new FileOutputStream(filePath, false)); logWriter.write(filePath + " > Start" + System.lineSeparator()); writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + System.lineSeparator()); writer.write(doc.getElementsByTag("response").first().toString()); writer.close(); logWriter.write(filePath + " > OK" + System.lineSeparator()); logWriter.flush(); } } logWriter.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:Inmemantlr.java
public static void main(String[] args) { LOGGER.info("Inmemantlr tool"); HelpFormatter hformatter = new HelpFormatter(); Options options = new Options(); // Binary arguments options.addOption("h", "print this message"); Option grmr = Option.builder().longOpt("grmrfiles").hasArgs().desc("comma-separated list of ANTLR files") .required(true).argName("grmrfiles").type(String.class).valueSeparator(',').build(); Option infiles = Option.builder().longOpt("infiles").hasArgs() .desc("comma-separated list of files to parse").required(true).argName("infiles").type(String.class) .valueSeparator(',').build(); Option utilfiles = Option.builder().longOpt("utilfiles").hasArgs() .desc("comma-separated list of utility files to be added for " + "compilation").required(false) .argName("utilfiles").type(String.class).valueSeparator(',').build(); Option odir = Option.builder().longOpt("outdir") .desc("output directory in which the dot files will be " + "created").required(false).hasArg(true) .argName("outdir").type(String.class).build(); options.addOption(infiles);/*from ww w . j a va 2 s . co m*/ options.addOption(grmr); options.addOption(utilfiles); options.addOption(odir); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); if (cmd.hasOption('h')) { hformatter.printHelp("java -jar inmemantlr.jar", options); System.exit(0); } } catch (ParseException e) { hformatter.printHelp("java -jar inmemantlr.jar", options); LOGGER.error(e.getMessage()); System.exit(-1); } // input files Set<File> ins = getFilesForOption(cmd, "infiles"); // grammar files Set<File> gs = getFilesForOption(cmd, "grmrfiles"); // utility files Set<File> uf = getFilesForOption(cmd, "utilfiles"); // output dir Set<File> od = getFilesForOption(cmd, "outdir"); if (od.size() > 1) { LOGGER.error("output directories must be less than or equal to 1"); System.exit(-1); } if (ins.size() <= 0) { LOGGER.error("no input files were specified"); System.exit(-1); } if (gs.size() <= 0) { LOGGER.error("no grammar files were specified"); System.exit(-1); } LOGGER.info("create generic parser"); GenericParser gp = null; try { gp = new GenericParser(gs.toArray(new File[gs.size()])); } catch (FileNotFoundException e) { LOGGER.error(e.getMessage()); System.exit(-1); } if (!uf.isEmpty()) { try { gp.addUtilityJavaFiles(uf.toArray(new String[uf.size()])); } catch (FileNotFoundException e) { LOGGER.error(e.getMessage()); System.exit(-1); } } LOGGER.info("create and add parse tree listener"); DefaultTreeListener dt = new DefaultTreeListener(); gp.setListener(dt); LOGGER.info("compile generic parser"); try { gp.compile(); } catch (CompilationException e) { LOGGER.error("cannot compile generic parser: {}", e.getMessage()); System.exit(-1); } String fpfx = ""; for (File of : od) { if (!of.exists() || !of.isDirectory()) { LOGGER.error("output directory does not exist or is not a " + "directory"); System.exit(-1); } fpfx = of.getAbsolutePath(); } Ast ast; for (File f : ins) { try { gp.parse(f); } catch (IllegalWorkflowException | FileNotFoundException e) { LOGGER.error(e.getMessage()); System.exit(-1); } ast = dt.getAst(); if (!fpfx.isEmpty()) { String of = fpfx + "/" + FilenameUtils.removeExtension(f.getName()) + ".dot"; LOGGER.info("write file {}", of); try { FileUtils.writeStringToFile(new File(of), ast.toDot(), "UTF-8"); } catch (IOException e) { LOGGER.error(e.getMessage()); System.exit(-1); } } else { LOGGER.info("Tree for {} \n {}", f.getName(), ast.toDot()); } } System.exit(0); }