List of usage examples for java.io IOException getMessage
public String getMessage()
From source file:com.igormaznitsa.jcp.JCPreprocessor.java
public static void main(@Nonnull @MustNotContainNull final String... args) { printHeader();/*from w w w . j a v a 2 s . c o m*/ final String[] normalizedStrings = PreprocessorUtils.replaceStringPrefix(new String[] { "--", "-" }, "/", PreprocessorUtils.replaceChar(args, '$', '\"')); final PreprocessorContext preprocessorContext; try { preprocessorContext = processCommandString(null, args, normalizedStrings); } catch (IOException ex) { System.err.println("Error during command line processing [" + ex.getMessage() + ']'); System.exit(1); throw new RuntimeException("To show compiler executiion stop"); } final JCPreprocessor preprocessor = new JCPreprocessor(preprocessorContext); try { preprocessor.execute(); } catch (Exception unexpected) { System.err.println(PreprocessorException.referenceAsString(' ', unexpected)); System.exit(1); } System.exit(0); }
From source file:eu.sonata.nfv.nec.validate.cli.Main.java
/** * Go, go, go, ... move it!//from w w w . j av a 2 s .co m * * @param args The command line arguments. */ public static void main(String[] args) { // Set the log level to ERROR. setLogLevel(1); // Parse the command line. parseCliOptions(args); // Initialize the Guice modules. initGuice(); // Read the JSON schema specifications. String jsonSchemaDraft04 = null; try { jsonSchemaDraft04 = loadJsonSchema(JSON_DRAFT_04); } catch (IOException e) { System.err.println(e.getMessage()); } // Read the actual file. String fileContent = loadAndSanitizeFile(jsonFile); if (fileContent == null) { System.err.println(getFAILURE() + " Could not read file from path: " + jsonFile); System.exit(EXIT_CODE_ERROR); } String schemaContent; // If a schema file was provided, read the schema file. With a lot of error handling. if (schemaFile != null) { schemaContent = loadAndSanitizeFile(schemaFile); if (schemaContent == null) { System.err.println(getFAILURE() + " Could not read schema file from path: " + schemaFile); System.exit(EXIT_CODE_ERROR); } if (checkSchema && jsonSchemaDraft04 == null) { System.err.println(getFAILURE() + " The default schema file '" + JSON_DRAFT_04 + "' is null."); System.exit(EXIT_CODE_ERROR); } if (checkSchema && !validator.isValid(schemaContent, jsonSchemaDraft04)) { System.err.println(getFAILURE() + " The schema file is no valid JSON."); System.exit(EXIT_CODE_ERROR); } // If no schema was provided, but the 's' option was used, just use the default schema. // We re-use the checkSchema here to state whether to check the default or not. } else if (!checkSchema) { if (jsonSchemaDraft04 == null) { System.err.println(getFAILURE() + " The default schema file '" + JSON_DRAFT_04 + "' is null."); System.exit(EXIT_CODE_ERROR); } schemaContent = jsonSchemaDraft04; // Try to get the schema file from a $schema URL in the json file. } else { JSONObject jSONObject = new JSONObject(fileContent); // If there was an schema key provided explicitly, check ... if (!schemaKey.equals(DEFAULT_SCHEMA_KEY) && !jSONObject.has(schemaKey)) { System.err.println(getFAILURE() + " The file does not contain the given schema key: " + schemaKey); System.exit(EXIT_CODE_ERROR); } // We re-use schemaFile here to store the URI of the schema. schemaFile = jSONObject.get(schemaKey).toString(); schemaContent = loadAndSanitizeFile(schemaFile); if (schemaContent == null) { System.err.println(getFAILURE() + " Could not read schema from path: " + schemaFile); System.exit(EXIT_CODE_ERROR); } } // Check and output. if (validator.isValid(fileContent, schemaContent)) { if (schemaFile != null) { System.out.println(getSUCCESS() + " The file '" + jsonFile + "' is valid according to the given schema '" + schemaFile + "'."); } else { System.out.println(getSUCCESS() + " The file '" + jsonFile + "' is valid according to the default schema '" + JSON_DRAFT_04 + "'."); } System.exit(EXIT_CODE_SUCCESS); } else { if (schemaFile != null) { System.out.println(getFAILURE() + " The file '" + jsonFile + "' does NOT meet the schema '" + schemaFile + "'."); } else { System.out.println(getFAILURE() + " The file '" + jsonFile + "' does NOT meet the schema '" + JSON_DRAFT_04 + "'."); } System.exit(EXIT_CODE_ERROR); } }
From source file:de.micromata.tpsb.doc.StaticTestDocGenerator.java
public static void main(String[] args) { ParserConfig.Builder bCfg = new ParserConfig.Builder(); ParserConfig.Builder tCfg = new ParserConfig.Builder(); tCfg.generateIndividualFiles(true);//from ww w. j av a 2s .c o m bCfg.generateIndividualFiles(true); List<String> la = Arrays.asList(args); Iterator<String> it = la.iterator(); boolean baseDirSet = false; boolean ignoreLocalSettings = false; List<String> addRepos = new ArrayList<String>(); StringResourceLoader.setRepository(StringResourceLoader.REPOSITORY_NAME_DEFAULT, new StringResourceRepositoryImpl()); try { while (it.hasNext()) { String arg = it.next(); String value = null; if ((value = getArgumentOption(it, arg, "--project-root", "-pr")) != null) { File f = new File(value); if (f.exists() == false) { System.err.print("project root doesn't exists: " + f.getAbsolutePath()); continue; } TpsbEnvironment.get().addProjectRoots(f); File ts = new File(f, "src/test"); if (ts.exists() == true) { tCfg.addSourceFileRespository(new FileSystemSourceFileRepository(ts.getAbsolutePath())); bCfg.addSourceFileRespository(new FileSystemSourceFileRepository(ts.getAbsolutePath())); } continue; } if ((value = getArgumentOption(it, arg, "--test-input", "-ti")) != null) { File f = new File(value); if (f.exists() == false) { System.err.print("test-input doesn't exists: " + f.getAbsolutePath()); } tCfg.addSourceFileRespository(new FileSystemSourceFileRepository(value)); bCfg.addSourceFileRespository(new FileSystemSourceFileRepository(value)); continue; } if ((value = getArgumentOption(it, arg, "--output-path", "-op")) != null) { if (baseDirSet == false) { tCfg.outputDir(value); bCfg.outputDir(value); TpsbEnvironment.setBaseDir(value); baseDirSet = true; } else { addRepos.add(value); } continue; } if ((value = getArgumentOption(it, arg, "--index-vmtemplate", "-ivt")) != null) { try { String content = FileUtils.readFileToString(new File(value), CharEncoding.UTF_8); StringResourceRepository repo = StringResourceLoader.getRepository(); repo.putStringResource("customIndexTemplate", content, CharEncoding.UTF_8); tCfg.indexTemplate("customIndexTemplate"); } catch (IOException ex) { throw new RuntimeException( "Cannot load file " + new File(value).getAbsolutePath() + ": " + ex.getMessage(), ex); } continue; } if ((value = getArgumentOption(it, arg, "--test-vmtemplate", "-tvt")) != null) { try { String content = FileUtils.readFileToString(new File(value), CharEncoding.UTF_8); StringResourceRepository repo = StringResourceLoader.getRepository(); repo.putStringResource("customTestTemplate", content, CharEncoding.UTF_8); tCfg.testTemplate("customTestTemplate"); } catch (IOException ex) { throw new RuntimeException( "Cannot load file " + new File(value).getAbsolutePath() + ": " + ex.getMessage(), ex); } continue; } if (arg.equals("--singlexml") == true) { tCfg.generateIndividualFiles(false); bCfg.generateIndividualFiles(false); } else if (arg.equals("--ignore-local-settings") == true) { ignoreLocalSettings = true; continue; } } } catch (RuntimeException ex) { System.err.print(ex.getMessage()); return; } if (ignoreLocalSettings == false) { readLocalSettings(bCfg, tCfg); } bCfg// .addSourceFileFilter(new MatcherSourceFileFilter("*Builder,*App,*builder")) // .addSourceFileFilter(new AnnotationSourceFileFilter(TpsbBuilder.class)) // .addSourceFileFilter(new AnnotationSourceFileFilter(TpsbApplication.class)) // ; tCfg// .addSourceFileFilter(new MatcherSourceFileFilter("*Test,*TestCase")) // .addSourceFileFilter(new AnnotationSourceFileFilter(TpsbTestSuite.class)) // ; StaticTestDocGenerator docGenerator = new StaticTestDocGenerator(bCfg.build(), tCfg.build()); TpsbEnvironment env = TpsbEnvironment.get(); if (addRepos.isEmpty() == false) { env.setIncludeRepos(addRepos); } docGenerator.parseTestBuilders(); docGenerator.parseTestCases(); }
From source file:de.fraunhofer.iosb.ivct.IVCTcommander.java
/** * Main entry point from the command line. * * @param args The command line arguments *///from w w w .ja v a 2s. c o m public static void main(final String[] args) { // LogConfigurationHelper.configureLogging(IVCTcommander.class); // LogConfigurationHelper.configureLogging(); try { final IVCTcommander runner = new IVCTcommander(); String userCommand = "Freddy"; runner.sendToJms(userCommand); runner.listenToJms(); } catch (final IOException ex) { LOGGER.error(ex.getMessage(), ex); } }
From source file:correospingtelnet.Telnet.java
public static void main(String[] args) throws Exception { FileOutputStream fout = null; String remoteip = "64.62.142.154"; int remoteport = 23; try {//from w ww. j a v a 2 s . c o m fout = new FileOutputStream("spy.log", true); } catch (IOException e) { System.err.println("Exception while opening the spy file: " + e.getMessage()); } tc = new TelnetClient(); TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false); EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false); SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true); try { tc.addOptionHandler(ttopt); tc.addOptionHandler(echoopt); tc.addOptionHandler(gaopt); } catch (InvalidTelnetOptionException e) { System.err.println("Error registering option handlers: " + e.getMessage()); } while (true) { boolean end_loop = false; try { tc.connect(remoteip, remoteport); Thread reader = new Thread(new Telnet()); tc.registerNotifHandler(new Telnet()); System.out.println("TelnetClientExample"); System.out.println("Type AYT to send an AYT telnet command"); System.out.println("Type OPT to print a report of status of options (0-24)"); System.out.println("Type REGISTER to register a new SimpleOptionHandler"); System.out.println("Type UNREGISTER to unregister an OptionHandler"); System.out.println("Type SPY to register the spy (connect to port 3333 to spy)"); System.out.println("Type UNSPY to stop spying the connection"); System.out.println("Type ^[A-Z] to send the control character; use ^^ to send ^"); reader.start(); OutputStream outstr = tc.getOutputStream(); byte[] buff = new byte[1024]; int ret_read = 0; do { try { ret_read = System.in.read(buff); if (ret_read > 0) { final String line = new String(buff, 0, ret_read); // deliberate use of default charset if (line.startsWith("AYT")) { try { System.out.println("Sending AYT"); System.out.println("AYT response:" + tc.sendAYT(5000)); } catch (IOException e) { System.err.println("Exception waiting AYT response: " + e.getMessage()); } } else if (line.startsWith("OPT")) { System.out.println("Status of options:"); for (int ii = 0; ii < 25; ii++) { System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii) + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii)); } } else if (line.startsWith("REGISTER")) { StringTokenizer st = new StringTokenizer(new String(buff)); try { st.nextToken(); int opcode = Integer.parseInt(st.nextToken()); boolean initlocal = Boolean.parseBoolean(st.nextToken()); boolean initremote = Boolean.parseBoolean(st.nextToken()); boolean acceptlocal = Boolean.parseBoolean(st.nextToken()); boolean acceptremote = Boolean.parseBoolean(st.nextToken()); SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal, initremote, acceptlocal, acceptremote); tc.addOptionHandler(opthand); } catch (Exception e) { if (e instanceof InvalidTelnetOptionException) { System.err.println("Error registering option: " + e.getMessage()); } else { System.err.println("Invalid REGISTER command."); System.err.println( "Use REGISTER optcode initlocal initremote acceptlocal acceptremote"); System.err.println("(optcode is an integer.)"); System.err.println( "(initlocal, initremote, acceptlocal, acceptremote are boolean)"); } } } else if (line.startsWith("UNREGISTER")) { StringTokenizer st = new StringTokenizer(new String(buff)); try { st.nextToken(); int opcode = (new Integer(st.nextToken())).intValue(); tc.deleteOptionHandler(opcode); } catch (Exception e) { if (e instanceof InvalidTelnetOptionException) { System.err.println("Error unregistering option: " + e.getMessage()); } else { System.err.println("Invalid UNREGISTER command."); System.err.println("Use UNREGISTER optcode"); System.err.println("(optcode is an integer)"); } } } else if (line.startsWith("SPY")) { tc.registerSpyStream(fout); } else if (line.startsWith("UNSPY")) { tc.stopSpyStream(); } else if (line.matches("^\\^[A-Z^]\\r?\\n?$")) { byte toSend = buff[1]; if (toSend == '^') { outstr.write(toSend); } else { outstr.write(toSend - 'A' + 1); } outstr.flush(); } else { try { outstr.write(buff, 0, ret_read); outstr.flush(); } catch (IOException e) { end_loop = true; } } } } catch (IOException e) { System.err.println("Exception while reading keyboard:" + e.getMessage()); end_loop = true; } } while ((ret_read > 0) && (end_loop == false)); try { tc.disconnect(); } catch (IOException e) { System.err.println("Exception while connecting:" + e.getMessage()); } } catch (IOException e) { System.err.println("Exception while connecting:" + e.getMessage()); System.exit(1); } } }
From source file:com.google.api.ads.adwords.jaxws.extensions.AwReporting.java
/** * Main method./*from ww w . j a va 2s . c o m*/ * * @param args the command line arguments. */ public static void main(String args[]) { // Proxy JaxWsProxySelector ps = new JaxWsProxySelector(ProxySelector.getDefault()); ProxySelector.setDefault(ps); Options options = createCommandLineOptions(); boolean errors = false; String propertiesPath = null; try { CommandLineParser parser = new BasicParser(); CommandLine cmdLine = parser.parse(options, args); // Print full help and quit if (cmdLine.hasOption("help")) { printHelpMessage(options); printSamplePropertiesFile(); System.exit(0); } setLogLevel(cmdLine); if (cmdLine.hasOption("file")) { propertiesPath = cmdLine.getOptionValue("file"); } else { LOGGER.error("Missing required option: 'file'"); System.exit(0); } LOGGER.info("Using properties file: " + propertiesPath); Set<Long> accountIdsSet = Sets.newHashSet(); if (cmdLine.hasOption("accountIdsFile")) { String accountsFileName = cmdLine.getOptionValue("accountIdsFile"); addAccountsFromFile(accountIdsSet, accountsFileName); } Properties properties = initApplicationContextAndProperties(propertiesPath); ReportModeService.setReportMode(properties.getProperty("reportMode")); //TODO Any other approach? LOGGER.debug("Creating ReportProcessor bean..."); ReportProcessor processor = createReportProcessor(); LOGGER.debug("... success."); if (cmdLine.hasOption("generatePdf")) { LOGGER.debug("GeneratePDF option detected."); // Get HTML template and output directoy String[] pdfFiles = cmdLine.getOptionValues("generatePdf"); File htmlTemplateFile = new File(pdfFiles[0]); File outputDirectory = new File(pdfFiles[1]); LOGGER.debug("Html template file to be used: " + htmlTemplateFile); LOGGER.debug("Output directory for PDF: " + outputDirectory); // Generate PDFs generatePdf(processor, cmdLine.getOptionValue("startDate"), cmdLine.getOptionValue("endDate"), properties, htmlTemplateFile, outputDirectory); } else if (cmdLine.hasOption("startDate") && cmdLine.hasOption("endDate")) { // Generate Reports String dateStart = cmdLine.getOptionValue("startDate"); String dateEnd = cmdLine.getOptionValue("endDate"); LOGGER.info("Starting report download for dateStart: " + dateStart + " and dateEnd: " + dateEnd); processor.generateReportsForMCC(ReportDefinitionDateRangeType.CUSTOM_DATE, dateStart, dateEnd, accountIdsSet, properties); } else if (cmdLine.hasOption("dateRange")) { ReportDefinitionDateRangeType dateRangeType = ReportDefinitionDateRangeType .fromValue(cmdLine.getOptionValue("dateRange")); LOGGER.info("Starting report download for dateRange: " + dateRangeType.name()); processor.generateReportsForMCC(dateRangeType, null, null, accountIdsSet, properties); } else { errors = true; LOGGER.error("Configuration incomplete. Missing options for command line."); } } catch (IOException e) { errors = true; LOGGER.error("File not found: " + e.getMessage()); } catch (ParseException e) { errors = true; System.err.println("Error parsing the values for the command line options: " + e.getMessage()); } catch (Exception e) { errors = true; LOGGER.error("Unexpected error accessing the API: " + e.getMessage()); e.printStackTrace(); } if (errors) { System.exit(1); } else { System.exit(0); } }
From source file:ProductionJS.java
/** * @param args// w w w . j av a 2s.c o m */ public static void main(String[] args) { boolean precondition = true; BackupLog backupLog = new BackupLog("log/backupLog.txt"); Property properties = null; Settings settings = null; // Load main cfg file try { properties = new Property("cfg/cfg"); } catch (IOException e) { backupLog.log("ERROR : Config file not found"); precondition = false; } // Load cfg for Log4J if (precondition) { try { DOMConfigurator.configureAndWatch(properties.getProperty("loggerConfiguration")); logger.info("ProductionJS is launched\n_______________________"); } catch (Exception e) { backupLog.log(e.getMessage()); precondition = false; } } // Load settings for current execution if (precondition) { try { settings = new Settings(new File(properties.getProperty("importConfiguration"))); } catch (IOException e) { logger.error("Properties file not found"); precondition = false; } catch (org.json.simple.parser.ParseException e) { logger.error("Properties file reading error : JSON may be invalid, check it!"); precondition = false; } } // All is OK : GO! if (precondition) { logger.info("Configuration OK"); logger.info("\"_______________________\nConcat BEGIN\n_______________________\n"); Concat concat = new Concat(); try { if (settings.getPrior() != null) { logger.info("Add Prior files\n_______________________\n"); concat.addJSONArray(settings.getPrior()); } for (int i = 0; i < settings.getIn().size(); i++) { ProductionJS.logger.info("Importation number " + (i + 1)); ProductionJS.logger.info("Directory imported " + settings.getIn().get(i)); Directory dir = new Directory(new File(settings.getIn().get(i).toString())); dir.scan(); concat.add(dir.getFiles()); } concat.output(settings.getOut()); logger.info("\"_______________________\nConcat END\n_______________________\n"); if (settings.getMinify() != null && settings.getMinify() == true) { logger.info( "\"_______________________\nMinify of concatened file BEGIN\n_______________________\n"); new Minify(new File(settings.getOut()), settings.getOut()); logger.info( "\"_______________________\nMinify of concatened file END\n_______________________\n"); } if (settings.getLicense() != null) { logger.info("Add License\n_______________________\n"); concat = new Concat(); UUID uniqueID = UUID.randomUUID(); PrintWriter tmp = new PrintWriter(uniqueID.toString() + ".txt"); tmp.println(settings.getLicense()); tmp.close(); File license = new File(uniqueID.toString() + ".txt"); concat.add(license); File out = new File(settings.getOut()); File tmpOut = new File(uniqueID + out.getName()); out.renameTo(tmpOut); concat.add(tmpOut); concat.output(settings.getOut()); license.delete(); tmpOut.delete(); } } catch (IOException e) { StackTrace stackTrace = new StackTrace(e.getStackTrace()); logger.error("An error occurred " + e.getMessage() + " " + stackTrace.toString()); } } }
From source file:com.google.api.ads.adwords.awreporting.AwReporting.java
/** * Main method.//from w w w . j av a 2s . c o m * * @param args the command line arguments. */ public static void main(String args[]) { // Proxy JaxWsProxySelector ps = new JaxWsProxySelector(ProxySelector.getDefault()); ProxySelector.setDefault(ps); Options options = createCommandLineOptions(); boolean errors = false; String propertiesPath = null; try { CommandLineParser parser = new BasicParser(); CommandLine cmdLine = parser.parse(options, args); // Print full help and quit if (cmdLine.hasOption("help")) { printHelpMessage(options); printSamplePropertiesFile(); System.exit(0); } setLogLevel(cmdLine); if (cmdLine.hasOption("file")) { propertiesPath = cmdLine.getOptionValue("file"); } else { LOGGER.error("Missing required option: 'file'"); System.exit(0); } LOGGER.info("Using properties file: " + propertiesPath); Set<Long> accountIdsSet = Sets.newHashSet(); if (cmdLine.hasOption("accountIdsFile")) { String accountsFileName = cmdLine.getOptionValue("accountIdsFile"); addAccountsFromFile(accountIdsSet, accountsFileName); } boolean forceOnFileProcessor = false; if (cmdLine.hasOption("onFileReport")) { if (!cmdLine.hasOption("csvReportFile") || !cmdLine.hasOption("startDate") || !cmdLine.hasOption("endDate")) { LOGGER.error("Missing one or more of the required options: " + "'csvReportFile', 'startDate' or 'endDate'"); System.exit(0); } forceOnFileProcessor = true; } Properties properties = initApplicationContextAndProperties(propertiesPath, forceOnFileProcessor); LOGGER.debug("Creating ReportProcessor bean..."); ReportProcessor processor = createReportProcessor(); LOGGER.debug("... success."); String mccAccountId = properties.getProperty("mccAccountId").replaceAll("-", ""); if (cmdLine.hasOption("startDate") && cmdLine.hasOption("endDate")) { // Generate Reports String dateStart = cmdLine.getOptionValue("startDate"); String dateEnd = cmdLine.getOptionValue("endDate"); if (cmdLine.hasOption("onFileReport")) { String reportTypeName = cmdLine.getOptionValue("onFileReport"); String csvReportFile = cmdLine.getOptionValue("csvReportFile"); File csvFile = new File(csvReportFile); if (!csvFile.exists()) { LOGGER.error("Could not find CSV file: " + csvReportFile); System.exit(0); } ReportProcessorOnFile onFileProcessor = (ReportProcessorOnFile) processor; List<File> localFiles = new ArrayList<File>(); localFiles.add(csvFile); LOGGER.info( "Starting report processing for dateStart: " + dateStart + " and dateEnd: " + dateEnd); onFileProcessor.processInputFiles(mccAccountId, reportTypeName, localFiles, dateStart, dateEnd, ReportDefinitionDateRangeType.CUSTOM_DATE); } else { LOGGER.info( "Starting report download for dateStart: " + dateStart + " and dateEnd: " + dateEnd); processor.generateReportsForMCC(mccAccountId, ReportDefinitionDateRangeType.CUSTOM_DATE, dateStart, dateEnd, accountIdsSet, properties, null, null); } } else if (cmdLine.hasOption("dateRange")) { ReportDefinitionDateRangeType dateRangeType = ReportDefinitionDateRangeType .fromValue(cmdLine.getOptionValue("dateRange")); LOGGER.info("Starting report download for dateRange: " + dateRangeType.name()); processor.generateReportsForMCC(mccAccountId, dateRangeType, null, null, accountIdsSet, properties, null, null); } else { errors = true; LOGGER.error("Configuration incomplete. Missing options for command line."); } } catch (IOException e) { errors = true; if (e.getMessage().contains("Insufficient Permission")) { LOGGER.error("Insufficient Permission error accessing the API" + e.getMessage()); } else { LOGGER.error("File not found: " + e.getMessage()); } } catch (ParseException e) { errors = true; System.err.println("Error parsing the values for the command line options: " + e.getMessage()); } catch (Exception e) { errors = true; LOGGER.error("Unexpected error accessing the API: " + e.getMessage()); e.printStackTrace(); } if (errors) { System.exit(1); } else { System.exit(0); } }
From source file:com.ontotext.s4.service.S4ServiceClient.java
public static void main(String... args) { if (args == null || args.length == 0) { printUsageAndTerminate(null);//from w ww .ja v a2s . co m } Parameters params = new Parameters(args); String serviceID = params.getValue("service"); if (serviceID == null) { printUsageAndTerminate("No service name provided"); } ServiceDescriptor service = null; try { service = ServicesCatalog.getItem(serviceID); } catch (UnsupportedOperationException uoe) { printUsageAndTerminate("Unsupported service '" + serviceID + '\''); } SupportedMimeType mimetype = SupportedMimeType.PLAINTEXT; if (params.getValue("dtype") != null) { try { mimetype = SupportedMimeType.valueOf(params.getValue("dtype")); } catch (IllegalArgumentException iae) { printUsageAndTerminate("Unsupported document type (dtype) : " + params.getValue("dtype")); } } String inFile = params.getValue("file"); String url = params.getValue("url"); String outFile = params.getValue("out", "result.json"); if (inFile != null) { if (!new File(inFile).exists()) { printUsageAndTerminate("Input file is not found : " + inFile); } } else { if (url == null) { printUsageAndTerminate("Neither input file, nor remote URL provided"); } } Properties creds = readCredentials(params); if (!creds.containsKey("apikey") || !creds.containsKey("secret")) { printUsageAndTerminate("No credentials details found"); } S4ServiceClient client = new S4ServiceClient(service, creds.getProperty("apikey"), creds.getProperty("secret")); try { InputStream resultData = null; if (service.getName().equals("news-classifier")) { resultData = (inFile != null) ? client.classifyFileContentsAsStream(new File(inFile), Charset.forName("UTF-8"), mimetype) : client.classifyDocumentFromUrlAsStream(new URL(url), mimetype); } else { resultData = (inFile != null) ? client.annotateFileContentsAsStream(new File(inFile), Charset.forName("UTF-8"), mimetype, ResponseFormat.JSON) : client.annotateDocumentFromUrlAsStream(new URL(url), mimetype, ResponseFormat.JSON); } FileOutputStream outStream = new FileOutputStream(outFile); IOUtils.copy(resultData, outStream); outStream.close(); resultData.close(); } catch (IOException ioe) { System.out.println(ioe.getMessage()); System.exit(1); } }
From source file:de.prozesskraft.pkraft.Merge.java
public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException { /*---------------------------- get options from ini-file// ww w . j av a 2s . c o m ----------------------------*/ java.io.File inifile = new java.io.File( WhereAmI.getInstallDirectoryAbsolutePath(Merge.class) + "/" + "../etc/pkraft-merge.ini"); if (inifile.exists()) { try { ini = new Ini(inifile); } catch (InvalidFileFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } else { System.err.println("ini file does not exist: " + inifile.getAbsolutePath()); System.exit(1); } /*---------------------------- create boolean options ----------------------------*/ Option ohelp = new Option("help", "print this message"); Option ov = new Option("v", "prints version and build-date"); /*---------------------------- create argument options ----------------------------*/ Option oinstance = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory] instance you want to merge another instance into.") // .isRequired() .create("instance"); Option oguest = OptionBuilder.withArgName("FILE").hasArg() .withDescription("[mandatory] this instance will be merged into -instance.") // .isRequired() .create("guest"); Option obasedir = OptionBuilder.withArgName("DIR").hasArg().withDescription( "[optional] in this base-directory the result instance (merge of -instance and -guest) will be placed. this directory has to exist. omit to use the base-directory of -instance.") // .isRequired() .create("basedir"); /*---------------------------- create options object ----------------------------*/ Options options = new Options(); options.addOption(ohelp); options.addOption(ov); options.addOption(oinstance); options.addOption(oguest); options.addOption(obasedir); /*---------------------------- create the parser ----------------------------*/ CommandLineParser parser = new GnuParser(); // parse the command line arguments commandline = parser.parse(options, args); /*---------------------------- usage/help ----------------------------*/ if (commandline.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("merge", options); System.exit(0); } if (commandline.hasOption("v")) { System.out.println("author: alexander.vogel@caegroup.de"); System.out.println("version: [% version %]"); System.out.println("date: [% date %]"); System.exit(0); } /*---------------------------- ueberpruefen ob eine schlechte kombination von parametern angegeben wurde ----------------------------*/ if (!(commandline.hasOption("instance"))) { System.err.println("option -instance is mandatory"); exiter(); } if (!(commandline.hasOption("guest"))) { System.err.println("at least one option -guest is mandatory"); exiter(); } /*---------------------------- die lizenz ueberpruefen und ggf abbrechen ----------------------------*/ // check for valid license ArrayList<String> allPortAtHost = new ArrayList<String>(); allPortAtHost.add(ini.get("license-server", "license-server-1")); allPortAtHost.add(ini.get("license-server", "license-server-2")); allPortAtHost.add(ini.get("license-server", "license-server-3")); MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1"); // lizenz-logging ausgeben for (String actLine : (ArrayList<String>) lic.getLog()) { System.err.println(actLine); } // abbruch, wenn lizenz nicht valide if (!lic.isValid()) { System.exit(1); } /*---------------------------- die eigentliche business logic ----------------------------*/ String pathToInstance = commandline.getOptionValue("instance"); java.io.File fileInstance = new java.io.File(pathToInstance); String[] pathToGuest = commandline.getOptionValues("guest"); String baseDir = null; if (commandline.hasOption("basedir")) { java.io.File fileBaseDir = new java.io.File(commandline.getOptionValue("basedir")); if (!fileBaseDir.exists()) { System.err.println("basedir does not exist: " + fileBaseDir.getAbsolutePath()); exiter(); } else if (!fileBaseDir.isDirectory()) { System.err.println("basedir is not a directory: " + fileBaseDir.getAbsolutePath()); exiter(); } baseDir = commandline.getOptionValue("basedir"); } // ueberpruefen ob die process.pmb files vorhanden sind // wenn es nicht vorhanden ist, dann mit fehlermeldung abbrechen if (!fileInstance.exists()) { System.err.println("instance file does not exist: " + fileInstance.getAbsolutePath()); exiter(); } for (String pathGuest : pathToGuest) { java.io.File fileGuest = new java.io.File(pathGuest); // wenn es nicht vorhanden ist, dann mit fehlermeldung abbrechen if (!fileGuest.exists()) { System.err.println("guest file does not exist: " + fileGuest.getAbsolutePath()); exiter(); } } // base - instance einlesen Process p1 = new Process(); p1.setInfilebinary(pathToInstance); p1.setOutfilebinary(pathToInstance); Process p2 = p1.readBinary(); // alle guests einlesen ArrayList<Process> alleGuests = new ArrayList<Process>(); for (String actPathGuest : pathToGuest) { Process p30 = new Process(); p30.setInfilebinary(actPathGuest); Process pGuest = p30.readBinary(); // testen ob base-instanz und aktuelle guestinstanz vom gleichen typ sind if (!p2.getName().equals(pGuest.getName())) { System.err.println("error: instances are not from the same type (-instance=" + p2.getName() + " != -guest=" + pGuest.getName()); exiter(); } // testen ob base-instanz und aktuelle guestinstanz von gleicher version sind if (!p2.getVersion().equals(pGuest.getVersion())) { System.err.println("error: instances are not from the same version (" + p2.getVersion() + "!=" + pGuest.getVersion()); exiter(); } alleGuests.add(pGuest); } // den main-prozess trotzdem nochmal einlesen um subprozesse extrahieren zu koennen Process p3 = new Process(); p3.setInfilebinary(pathToInstance); Process process = p3.readBinary(); // den main-prozess ueber die static function klonen // das anmelden bei pradar erfolgt erst ganz zum schluss, denn beim clonen werden nachfolgende steps resettet, die zu diesem zeitpunkt noch intakt sind Process clonedProcess = cloneProcess(process, null); // alle steps durchgehen und falls subprocesses existieren auch fuer diese ein cloning durchfuehren for (Step actStep : process.getStep()) { if (actStep.getSubprocess() != null) { Process pDummy = new Process(); pDummy.setInfilebinary(actStep.getAbsdir() + "/process.pmb"); Process processInSubprocess = pDummy.readBinary(); // System.err.println("info: reading process freshly from file: " + actStep.getAbsdir() + "/process.pmb"); if (processInSubprocess != null) { Process clonedSubprocess = cloneProcess(processInSubprocess, clonedProcess); // den prozess in pradar anmelden durch aufruf des tools: pradar-attend String call2 = ini.get("apps", "pradar-attend") + " -instance " + clonedSubprocess.getRootdir() + "/process.pmb"; System.err.println("info: calling: " + call2); try { java.lang.Process sysproc = Runtime.getRuntime().exec(call2); } catch (IOException e) { System.err.println("error: " + e.getMessage()); } } } } // alle dependent steps der zielinstanz einsammeln // dies wird zum resetten benoetigt, damit steps nicht doppelt resettet werden Map<Step, String> dependentSteps = new HashMap<Step, String>(); // alle guest prozesse merge durchfuehren for (Process actGuestProcess : alleGuests) { System.err.println("info: merging guest process " + actGuestProcess.getInfilebinary()); // alle fanned steps (ehemalige multisteps) des zu mergenden prozesses in die fanned multisteps des bestehenden prozesses integrieren for (Step actStep : actGuestProcess.getStep()) { if (actStep.isAFannedMultistep()) { System.err.println("info: merging from guest instance step " + actStep.getName()); Step clonedStepForIntegrationInClonedProcess = actStep.clone(); if (clonedProcess.integrateStep(clonedStepForIntegrationInClonedProcess)) { System.err.println("info: merging step successfully."); // die downstream steps vom merge-punkt merken for (Step actStepToResetBecauseOfDependency : clonedProcess .getStepDependent(actStep.getName())) { dependentSteps.put(actStepToResetBecauseOfDependency, "dummy"); } // der step einen subprocess enthaelt muss der subprocess nach der integration bei pradar gemeldet werden // den prozess in pradar anmelden durch aufruf des tools: pradar-attend if (clonedStepForIntegrationInClonedProcess.getSubprocess() != null && clonedStepForIntegrationInClonedProcess.getSubprocess().getProcess() != null) { String call5 = ini.get("apps", "pradar-attend") + " -instance " + clonedStepForIntegrationInClonedProcess.getAbsdir() + "/process.pmb"; System.err.println("info: calling: " + call5); try { java.lang.Process sysproc = Runtime.getRuntime().exec(call5); } catch (IOException e) { System.err.println("error: " + e.getMessage()); } } } else { System.err.println("error: merging step failed."); } } else { System.err.println("debug: because it's not a multistep, ignoring from guest instance step " + actStep.getName()); } } } // alle steps downstream der merge-positionen resetten for (Step actStep : dependentSteps.keySet()) { actStep.resetBecauseOfDependency(); } // speichern der ergebnis instanz clonedProcess.writeBinary(); // den prozess in pradar anmelden durch aufruf des tools: pradar-attend String call2 = ini.get("apps", "pradar-attend") + " -instance " + clonedProcess.getRootdir() + "/process.pmb"; System.err.println("info: calling: " + call2); try { java.lang.Process sysproc = Runtime.getRuntime().exec(call2); } catch (IOException e) { System.err.println("error: " + e.getMessage()); } }