List of usage examples for org.apache.commons.cli BasicParser BasicParser
BasicParser
From source file:op.OPDE.java
/** * Hier ist die main Methode von OPDE. In dieser Methode wird auch festgestellt, wie OPDE gestartet wurde. * <ul>/* w ww . ja va 2 s. co m*/ * <li>Im Standard Modus, das heisst mit graphischer Oberflche. Das drfte der hufigste Fall sein.</li> * <li>Im DFNImport Modus. Der wird meist auf dem Datenbankserver gebraucht um Nachts die Durchfhrungsnachweise anhand der * DFNImport Tabelle zu generieren. Das alles gehrt zu der Pflegeplanung.</li> * <li>Im BHPImport Modus. Auch dieser Modus wird auf dem DB-Server gebraucht um die Behandlungspflege Massnahmen * anhand der rztlichen Verordnungen zu generieren.</li> * </ul> * * @param args Hier stehen die Kommandozeilen Parameter. Diese werden mit */ public static void main(String[] args) throws Exception { /*** * * ____ * ,' , `. * ,-+-,.' _ | ,--, * ,-+-. ; , || ,--.'| ,---, * ,--.'|' | ;| | |, ,-+-. / | * | | ,', | ': ,--.--. `--'_ ,--.'|' | * | | / | | || / \ ,' ,'| | | ,"' | * ' | : | : |,.--. .-. | ' | | | | / | | * ; . | ; |--' \__\/: . . | | : | | | | | * | : | | , ," .--.; | ' : |__ | | | |/ * | : ' |/ / / ,. | | | '.'|| | |--' * ; | |`-' ; : .' \; : ;| |/ * | ;/ | , .-./| , / '---' * '---' `--`---' ---`-' * */ uptime = SYSCalendar.now(); // arial14 = new Font("Arial", Font.PLAIN, 14); // arial28 = new Font("Arial", Font.PLAIN, 28); /*** * _ ____ _ _ * | | __ _ _ __ __ _ _ _ __ _ __ _ ___ | __ ) _ _ _ __ __| | | ___ * | | / _` | '_ \ / _` | | | |/ _` |/ _` |/ _ \ | _ \| | | | '_ \ / _` | |/ _ \ * | |__| (_| | | | | (_| | |_| | (_| | (_| | __/ | |_) | |_| | | | | (_| | | __/ * |_____\__,_|_| |_|\__, |\__,_|\__,_|\__, |\___| |____/ \__,_|_| |_|\__,_|_|\___| * |___/ |___/ */ lang = ResourceBundle.getBundle("languageBundle", Locale.getDefault()); validatorFactory = Validation.buildDefaultValidatorFactory(); /*** * ____ _ _ _ _ _ _ * / ___|__ _| |_ ___| |__ __ _| | | _ __ ___ __ _ _ _ ___ _____ _____ ___ _ __ | |_(_) ___ _ __ ___ * | | / _` | __/ __| '_ \ / _` | | | | '__/ _ \ / _` | | | |/ _ \ / _ \ \/ / __/ _ \ '_ \| __| |/ _ \| '_ \/ __| * | |__| (_| | || (__| | | | | (_| | | | | | | (_) | (_| | |_| | __/ | __/> < (_| __/ |_) | |_| | (_) | | | \__ \ * \____\__,_|\__\___|_| |_| \__,_|_|_| |_| \___/ \__, |\__,_|\___| \___/_/\_\___\___| .__/ \__|_|\___/|_| |_|___/ * |___/ |_| */ Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { OPDE.fatal(e); } }); localProps = new SortedProperties(); props = new Properties(); /*** * _ _ ___ __ * _ __ ___ __ _ __| | / \ _ __ _ __|_ _|_ __ / _| ___ * | '__/ _ \/ _` |/ _` | / _ \ | '_ \| '_ \| || '_ \| |_ / _ \ * | | | __/ (_| | (_| | / ___ \| |_) | |_) | || | | | _| (_) | * |_| \___|\__,_|\__,_| /_/ \_\ .__/| .__/___|_| |_|_| \___/ * |_| |_| */ appInfo = new AppInfo(); /*** * ____ _ _ _ ___ _ _ * / ___|___ _ __ ___ _ __ ___ __ _ _ __ __| | | | (_)_ __ ___ / _ \ _ __ | |_(_) ___ _ __ ___ * | | / _ \| '_ ` _ \| '_ ` _ \ / _` | '_ \ / _` | | | | | '_ \ / _ \ | | | | '_ \| __| |/ _ \| '_ \/ __| * | |__| (_) | | | | | | | | | | | (_| | | | | (_| | | |___| | | | | __/ | |_| | |_) | |_| | (_) | | | \__ \ * \____\___/|_| |_| |_|_| |_| |_|\__,_|_| |_|\__,_| |_____|_|_| |_|\___| \___/| .__/ \__|_|\___/|_| |_|___/ * |_| */ Options opts = new Options(); opts.addOption("h", "hilfe", false, "Gibt die Hilfeseite fr OPDE aus."); opts.addOption("v", "version", false, "Zeigt die Versionsinformationen an."); opts.addOption("x", "experimental", false, "Schaltet experimentelle Programm-Module fr User frei, die Admin Rechte haben. VORSICHT !!!!"); opts.addOption("a", "anonym", false, "Blendet die Bewohnernamen in allen Ansichten aus. Spezieller Modus fr Schulungsmaterial zu erstellen."); opts.addOption("w", "workingdir", true, "Damit kannst Du ein anderes Arbeitsverzeichnis setzen. Wenn Du diese Option weglsst, dann ist das Dein Benutzerverzeichnis: " + System.getProperty("user.home")); opts.addOption("l", "debug", false, "Schaltet alle Ausgaben ein auf der Konsole ein, auch die, die eigentlich nur whrend der Softwareentwicklung angezeigt werden."); opts.addOption("t", "training", false, "Wird fr Einarbeitungsversionen bentigt. Frbt die Oberflche anders ein und zeigt eine Warnmeldung nach jeder Anmeldung."); Option optFTPserver = OptionBuilder.withLongOpt("ftpserver").withArgName("ip or hostname").hasArgs(1) .withDescription(lang.getString("cmdline.ftpserver")).create("f"); opts.addOption(optFTPserver); // opts.addOption("p", "pidfile", false, "Path to the pidfile which needs to be deleted when this application ends properly."); Option notification = OptionBuilder.withLongOpt("notification").hasOptionalArg() .withDescription("Schickt allen festgelegten Empfngern die jeweilige Benachrichtungs-Mail.") .create("n"); notification.setArgName( "Liste der Empfnger (durch Komma getrennt, ohne Leerzeichen. UID verwenden). Damit kannst Du die Benachrichtigungen einschrnken. Fehlt diese Liste, erhalten ALLE Empfnger eine Mail."); opts.addOption(notification); opts.addOption(OptionBuilder.withLongOpt("jdbc").hasArg().withDescription(lang.getString("cmdline.jdbc")) .create("j")); Option dfnimport = OptionBuilder //.withArgName("datum") .withLongOpt("dfnimport").hasOptionalArg() .withDescription("Startet OPDE im DFNImport Modus fr den aktuellen Tag.").create("d"); dfnimport.setArgName( "Anzahl der Tage (+ oder -) abweichend vom aktuellen Tag fr den der Import durchgefhrt werden soll. Nur in Ausnahmefllen anzuwenden."); opts.addOption(dfnimport); Option bhpimport = OptionBuilder.withLongOpt("bhpimport").hasOptionalArg() .withDescription("Startet OPDE im BHPImport Modus fr den aktuellen Tag.").create("b"); // bhpimport.setOptionalArg(true); bhpimport.setArgName( "Anzahl der Tage (+ oder -) abweichend vom aktuellen Tag fr den der Import durchgefhrt werden soll. Nur in Ausnahmefllen anzuwenden."); opts.addOption(bhpimport); BasicParser parser = new BasicParser(); CommandLine cl = null; String footer = "http://www.Offene-Pflege.de"; /*** * _ _ * | |__ ___| |_ __ ___ ___ _ __ ___ ___ _ __ * | '_ \ / _ \ | '_ \ / __|/ __| '__/ _ \/ _ \ '_ \ * | | | | __/ | |_) | \__ \ (__| | | __/ __/ | | | * |_| |_|\___|_| .__/ |___/\___|_| \___|\___|_| |_| * |_| */ try { cl = parser.parse(opts, args); } catch (ParseException ex) { HelpFormatter f = new HelpFormatter(); f.printHelp("OffenePflege.jar [OPTION]", "Offene-Pflege.de, Version " + appInfo.getVersion() + " Build:" + appInfo.getBuildnum(), opts, footer); System.exit(0); } // Alternative FTP-Server if (cl.hasOption("f")) { UPDATE_FTPSERVER = cl.getOptionValue("f"); } if (cl.hasOption("h")) { HelpFormatter f = new HelpFormatter(); f.printHelp("OffenePflege.jar [OPTION]", "Offene-Pflege.de, Version " + appInfo.getVersion() + " Build:" + appInfo.getBuildnum(), opts, footer); System.exit(0); } String homedir = System.getProperty("user.home"); // alternatice working dir if (cl.hasOption("w")) { File dir = new File(cl.getOptionValue("w")); if (dir.exists() && dir.isDirectory()) { homedir = dir.getAbsolutePath(); } } opwd = homedir + sep + AppInfo.dirBase; /*** * ___ * __ _ _ __ ___ _ __ _ _ _ __ ___ ___ _ _ ___ |__ \ * / _` | '_ \ / _ \| '_ \| | | | '_ ` _ \ / _ \| | | / __| / / * | (_| | | | | (_) | | | | |_| | | | | | | (_) | |_| \__ \ |_| * \__,_|_| |_|\___/|_| |_|\__, |_| |_| |_|\___/ \__,_|___/ (_) * |___/ */ if (cl.hasOption("a")) { // anonym Modus //localProps.put("anonym", "true"); anonym = true; anonymize = new HashMap[] { SYSConst.getNachnamenAnonym(), SYSConst.getVornamenFrauAnonym(), SYSConst.getVornamenMannAnonym() }; } else { anonym = false; } /*** * _ _ _ _ _ * (_)_ __ (_) |_ _ __ _ __(_)_ __ | |_ ___ _ __ ___ * | | '_ \| | __| | '_ \| '__| | '_ \| __/ _ \ '__/ __| * | | | | | | |_ | |_) | | | | | | | || __/ | \__ \ * |_|_| |_|_|\__| | .__/|_| |_|_| |_|\__\___|_| |___/ * |_| */ printers = new LogicalPrinters(); /*** * _ _ _ _ _ _ * | | ___ __ _ __| | | | ___ ___ __ _| | _ __ _ __ ___ _ __ ___ _ __| |_(_) ___ ___ * | |/ _ \ / _` |/ _` | | |/ _ \ / __/ _` | | | '_ \| '__/ _ \| '_ \ / _ \ '__| __| |/ _ \/ __| * | | (_) | (_| | (_| | | | (_) | (_| (_| | | | |_) | | | (_) | |_) | __/ | | |_| | __/\__ \ * |_|\___/ \__,_|\__,_| |_|\___/ \___\__,_|_| | .__/|_| \___/| .__/ \___|_| \__|_|\___||___/ * |_| |_| */ if (loadLocalProperties()) { // try { // FileAppender fileAppender = new FileAppender(layout, , true); // logger.addAppender(fileAppender); // } catch (IOException ex) { // fatal(ex); // } animation = localProps.containsKey("animation") && localProps.getProperty("animation").equals("true"); logger.info("######### START ########### " + OPDE.getAppInfo().getProgname() + ", v" + OPDE.getAppInfo().getVersion() + "/" + OPDE.getAppInfo().getBuildnum()); logger.info(System.getProperty("os.name").toLowerCase()); /*** * _ ____ _ ___ ___ * (_)___| _ \ ___| |__ _ _ __ _ |__ \__ \ * | / __| | | |/ _ \ '_ \| | | |/ _` | / / / / * | \__ \ |_| | __/ |_) | |_| | (_| | |_| |_| * |_|___/____/ \___|_.__/ \__,_|\__, | (_) (_) * |___/ */ if (cl.hasOption("l") || SYSTools.catchNull(localProps.getProperty("debug")).equalsIgnoreCase("true")) { debug = true; logger.setLevel(Level.DEBUG); } else { debug = false; logger.setLevel(Level.INFO); } Logger.getLogger("org.hibernate").setLevel(Level.OFF); if (cl.hasOption("x") || SYSTools.catchNull(localProps.getProperty("experimental")).equalsIgnoreCase("true")) { experimental = true; } else { experimental = false; } if (cl.hasOption("t") || SYSTools.catchNull(localProps.getProperty("training")).equalsIgnoreCase("true")) { training = true; } else { training = false; } /*** * _ _ _ _ _ _ _ ___ * __| | |____ _____ _ __ ___(_) ___ _ __ ___ ___ _ __ ___ _ __ __ _| |_(_) |__ | | ___ |__ \ * / _` | '_ \ \ / / _ \ '__/ __| |/ _ \| '_ \ / __/ _ \| '_ ` _ \| '_ \ / _` | __| | '_ \| |/ _ \ / / * | (_| | |_) \ V / __/ | \__ \ | (_) | | | | | (_| (_) | | | | | | |_) | (_| | |_| | |_) | | __/ |_| * \__,_|_.__/ \_/ \___|_| |___/_|\___/|_| |_| \___\___/|_| |_| |_| .__/ \__,_|\__|_|_.__/|_|\___| (_) * |_| */ url = cl.hasOption("j") ? cl.getOptionValue("j") : localProps.getProperty("javax.persistence.jdbc.url"); String hostkey = OPDE.getLocalProps().getProperty("hostkey"); String cryptpassword = localProps.getProperty("javax.persistence.jdbc.password"); DesEncrypter desEncrypter = new DesEncrypter(hostkey); Connection jdbcConnection = DriverManager.getConnection(url, localProps.getProperty("javax.persistence.jdbc.user"), desEncrypter.decrypt(cryptpassword)); if (appInfo.getDbversion() != getDBVersion(jdbcConnection)) { SYSFilesTools.print(lang.getString("cant.start.with.version.mismatch"), false); System.exit(1); } jdbcConnection.close(); /*** * _ ____ _ ____ _ _ * | | _ \ / \ | _ \ __ _| |_ __ _| |__ __ _ ___ ___ * _ | | |_) / _ \ | | | |/ _` | __/ _` | '_ \ / _` / __|/ _ \ * | |_| | __/ ___ \ | |_| | (_| | || (_| | |_) | (_| \__ \ __/ * \___/|_| /_/ \_\ |____/ \__,_|\__\__,_|_.__/ \__,_|___/\___| * */ Properties jpaProps = new Properties(); jpaProps.put("javax.persistence.jdbc.user", localProps.getProperty("javax.persistence.jdbc.user")); try { jpaProps.put("javax.persistence.jdbc.password", desEncrypter.decrypt(cryptpassword)); } catch (Exception e) { if (Desktop.isDesktopSupported()) { JOptionPane.showMessageDialog(null, SYSTools.xx("misc.msg.decryption.failure"), appInfo.getProgname(), JOptionPane.ERROR_MESSAGE); } else { OPDE.fatal(e); } System.exit(1); } jpaProps.put("javax.persistence.jdbc.driver", localProps.getProperty("javax.persistence.jdbc.driver")); jpaProps.put("javax.persistence.jdbc.url", url); // if (cl.hasOption("d") || cl.hasOption("d")) { // not for BHP or DFN // jpaProps.put("eclipselink.cache.shared.default", "false"); // } else { // jpaProps.put("eclipselink.cache.shared.default", "true"); // } jpaProps.put("eclipselink.cache.shared.default", "false"); jpaProps.put("eclipselink.session.customizer", "entity.JPAEclipseLinkSessionCustomizer"); emf = Persistence.createEntityManagerFactory("OPDEPU", jpaProps); /*** * __ __ _ * \ \ / /__ _ __ ___(_) ___ _ __ * \ \ / / _ \ '__/ __| |/ _ \| '_ \ * \ V / __/ | \__ \ | (_) | | | | * \_/ \___|_| |___/_|\___/|_| |_| * */ String header = SYSTools.getWindowTitle(""); if (cl.hasOption("v")) { System.out.println(header); System.out.println(footer); System.exit(0); } /*** * ____ _ ____ _____ _ _ * / ___| ___ _ __ ___ _ __ __ _| |_ ___ | _ \| ___| \ | |___ * | | _ / _ \ '_ \ / _ \ '__/ _` | __/ _ \ | | | | |_ | \| / __| * | |_| | __/ | | | __/ | | (_| | || __/ | |_| | _| | |\ \__ \ * \____|\___|_| |_|\___|_| \__,_|\__\___| |____/|_| |_| \_|___/ * */ if (cl.hasOption("d")) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); Users rootUser = em.find(Users.class, "admin"); SYSLogin rootLogin = em.merge(new SYSLogin(rootUser)); OPDE.setLogin(rootLogin); initProps(); // create the new DFNs DFNTools.generate(em); // move over the floating ones that have not yet been clicked to the current day DFNTools.moveFloating(em); em.getTransaction().commit(); } catch (Exception ex) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } fatal(ex); } finally { em.close(); } System.exit(0); } /*** * ____ _ ____ _ _ ____ * / ___| ___ _ __ ___ _ __ __ _| |_ ___ | __ )| | | | _ \ ___ * | | _ / _ \ '_ \ / _ \ '__/ _` | __/ _ \ | _ \| |_| | |_) / __| * | |_| | __/ | | | __/ | | (_| | || __/ | |_) | _ | __/\__ \ * \____|\___|_| |_|\___|_| \__,_|\__\___| |____/|_| |_|_| |___/ * */ if (cl.hasOption("b")) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); Users rootUser = em.find(Users.class, "admin"); SYSLogin rootLogin = em.merge(new SYSLogin(rootUser)); OPDE.setLogin(rootLogin); initProps(); BHPTools.generate(em); em.getTransaction().commit(); } catch (Exception ex) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } fatal(ex); } finally { em.close(); } System.exit(0); } /*** * _ _ _ _ __ _ _ _ * | \ | | ___ | |_(_)/ _(_) ___ __ _| |_(_) ___ _ __ * | \| |/ _ \| __| | |_| |/ __/ _` | __| |/ _ \| '_ \ * | |\ | (_) | |_| | _| | (_| (_| | |_| | (_) | | | | * |_| \_|\___/ \__|_|_| |_|\___\__,_|\__|_|\___/|_| |_| * */ if (cl.hasOption("n")) { EntityManager em = OPDE.createEM(); try { em.getTransaction().begin(); Users rootUser = em.find(Users.class, "admin"); SYSLogin rootLogin = em.merge(new SYSLogin(rootUser)); OPDE.setLogin(rootLogin); initProps(); EMailSystem.notify(cl.getOptionValue("n")); em.getTransaction().commit(); } catch (Exception ex) { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } fatal(ex); } finally { em.close(); } System.exit(0); } // to speed things later. The first connection loads the while JPA system. EntityManager em1 = createEM(); em1.close(); UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); setStandardFont(); try { css = SYSTools.readFileAsString(opwd + sep + AppInfo.dirTemplates + sep + AppInfo.fileStandardCSS); } catch (IOException ie) { css = ""; } // JideSoft Lm.verifyLicense("Torsten Loehr", "Open-Pflege.de", "G9F4JW:Bm44t62pqLzp5woAD4OCSUAr2"); WizardStyle.setStyle(WizardStyle.JAVA_STYLE); // JideSoft /*** * _____ __ __ _ ____ * | ___| __ _ __ ___ | \/ | __ _(_)_ __ / /\ \ * | |_ | '__| '_ ` _ \| |\/| |/ _` | | '_ \| | | | * | _|| | | | | | | | | | | (_| | | | | | | | | * |_| |_| |_| |_| |_|_| |_|\__,_|_|_| |_| | | | * \_\/_/ */ // JFrame frm = new JFrame(); // frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // frm.setLayout(new FlowLayout()); // // frm.getContentPane().add(new PnlBodyScheme(new Properties())); // // frm.setVisible(true); SYSTools.checkForSoftwareupdates(); mainframe = new FrmMain(); mainframe.setVisible(true); } }
From source file:org.akvo.flow.InstanceConfigurator.java
public static void main(String[] args) throws Exception { Options opts = getOptions();/*w w w . jav a 2 s .co m*/ CommandLineParser parser = new BasicParser(); CommandLine cli = null; try { cli = parser.parse(opts, args); } catch (Exception e) { System.err.println(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(InstanceConfigurator.class.getName(), opts); System.exit(1); } String awsAccessKey = cli.getOptionValue("ak"); String awsSecret = cli.getOptionValue("as"); String bucketName = cli.getOptionValue("bn"); String gaeId = cli.getOptionValue("gae"); String outFolder = cli.getOptionValue("o"); String flowServices = cli.getOptionValue("fs"); String alias = cli.getOptionValue("a"); String emailFrom = cli.getOptionValue("ef"); String emailTo = cli.getOptionValue("et"); String orgName = cli.getOptionValue("on"); String signingKey = cli.getOptionValue("sk"); File out = new File(outFolder); if (!out.exists()) { out.mkdirs(); } Map<String, AccessKey> accessKeys = new HashMap<String, AccessKey>(); String apiKey = UUID.randomUUID().toString().replaceAll("-", ""); AWSCredentials creds = new BasicAWSCredentials(awsAccessKey, awsSecret); AmazonIdentityManagementClient iamClient = new AmazonIdentityManagementClient(creds); AmazonS3Client s3Client = new AmazonS3Client(creds); // Creating bucket System.out.println("Creating bucket: " + bucketName); try { if (s3Client.doesBucketExist(bucketName)) { System.out.println(bucketName + " already exists, skipping creation"); } else { s3Client.createBucket(bucketName, Region.EU_Ireland); } } catch (Exception e) { System.err.println("Error trying to create bucket " + bucketName + " : " + e.getMessage()); System.exit(1); } // Creating users and groups String gaeUser = bucketName + GAE_SUFFIX; String apkUser = bucketName + APK_SUFFIX; // GAE System.out.println("Creating user: " + gaeUser); GetUserRequest gaeUserRequest = new GetUserRequest(); gaeUserRequest.setUserName(gaeUser); try { iamClient.getUser(gaeUserRequest); System.out.println("User already exists, skipping creation"); } catch (NoSuchEntityException e) { iamClient.createUser(new CreateUserRequest(gaeUser)); } System.out.println("Requesting security credentials for " + gaeUser); CreateAccessKeyRequest gaeAccessRequest = new CreateAccessKeyRequest(); gaeAccessRequest.setUserName(gaeUser); CreateAccessKeyResult gaeAccessResult = iamClient.createAccessKey(gaeAccessRequest); accessKeys.put(gaeUser, gaeAccessResult.getAccessKey()); // APK System.out.println("Creating user: " + apkUser); GetUserRequest apkUserRequest = new GetUserRequest(); apkUserRequest.setUserName(apkUser); try { iamClient.getUser(apkUserRequest); System.out.println("User already exists, skipping creation"); } catch (NoSuchEntityException e) { iamClient.createUser(new CreateUserRequest(apkUser)); } System.out.println("Requesting security credentials for " + apkUser); CreateAccessKeyRequest apkAccessRequest = new CreateAccessKeyRequest(); apkAccessRequest.setUserName(apkUser); CreateAccessKeyResult apkAccessResult = iamClient.createAccessKey(apkAccessRequest); accessKeys.put(apkUser, apkAccessResult.getAccessKey()); System.out.println("Configuring security policies..."); Configuration cfg = new Configuration(); cfg.setClassForTemplateLoading(InstanceConfigurator.class, "/org/akvo/flow/templates"); cfg.setObjectWrapper(new DefaultObjectWrapper()); cfg.setDefaultEncoding("UTF-8"); Map<String, Object> data = new HashMap<String, Object>(); data.put("bucketName", bucketName); data.put("version", new SimpleDateFormat("yyyy-MM-dd").format(new Date())); data.put("accessKey", accessKeys); Template t1 = cfg.getTemplate("apk-s3-policy.ftl"); StringWriter apkPolicy = new StringWriter(); t1.process(data, apkPolicy); Template t2 = cfg.getTemplate("gae-s3-policy.ftl"); StringWriter gaePolicy = new StringWriter(); t2.process(data, gaePolicy); iamClient.putUserPolicy( new PutUserPolicyRequest(apkUser, apkUser, Policy.fromJson(apkPolicy.toString()).toJson())); iamClient.putUserPolicy( new PutUserPolicyRequest(gaeUser, gaeUser, Policy.fromJson(gaePolicy.toString()).toJson())); System.out.println("Creating configuration files..."); // survey.properties Map<String, Object> apkData = new HashMap<String, Object>(); apkData.put("awsBucket", bucketName); apkData.put("awsAccessKeyId", accessKeys.get(apkUser).getAccessKeyId()); apkData.put("awsSecretKey", accessKeys.get(apkUser).getSecretAccessKey()); apkData.put("serverBase", "https://" + gaeId + ".appspot.com"); apkData.put("restApiKey", apiKey); Template t3 = cfg.getTemplate("survey.properties.ftl"); FileWriter fw = new FileWriter(new File(out, "/survey.properties")); t3.process(apkData, fw); // appengine-web.xml Map<String, Object> webData = new HashMap<String, Object>(); webData.put("awsBucket", bucketName); webData.put("awsAccessKeyId", accessKeys.get(gaeUser).getAccessKeyId()); webData.put("awsSecretAccessKey", accessKeys.get(gaeUser).getSecretAccessKey()); webData.put("s3url", "https://" + bucketName + ".s3.amazonaws.com"); webData.put("instanceId", gaeId); webData.put("alias", alias); webData.put("flowServices", flowServices); webData.put("apiKey", apiKey); webData.put("emailFrom", emailFrom); webData.put("emailTo", emailTo); webData.put("organization", orgName); webData.put("signingKey", signingKey); Template t5 = cfg.getTemplate("appengine-web.xml.ftl"); FileWriter fw3 = new FileWriter(new File(out, "/appengine-web.xml")); t5.process(webData, fw3); System.out.println("Done"); }
From source file:org.apache.accumulo.core.file.rfile.SplitLarge.java
public static void main(String[] args) throws Exception { Configuration conf = CachedConfiguration.getInstance(); FileSystem fs = FileSystem.get(conf); long maxSize = 10 * 1024 * 1024; Options opts = new Options(); Option maxSizeOption = new Option("m", "", true, "the maximum size of the key/value pair to shunt to the small file"); opts.addOption(maxSizeOption);//from ww w .ja v a 2 s .c o m CommandLine commandLine = new BasicParser().parse(opts, args); if (commandLine.hasOption(maxSizeOption.getOpt())) { maxSize = Long.parseLong(commandLine.getOptionValue(maxSizeOption.getOpt())); } for (String arg : commandLine.getArgs()) { Path path = new Path(arg); CachableBlockFile.Reader rdr = new CachableBlockFile.Reader(fs, path, conf, null, null); Reader iter = new RFile.Reader(rdr); if (!arg.endsWith(".rf")) { throw new IllegalArgumentException("File must end with .rf"); } String smallName = arg.substring(0, arg.length() - 3) + "_small.rf"; String largeName = arg.substring(0, arg.length() - 3) + "_large.rf"; int blockSize = (int) DefaultConfiguration.getDefaultConfiguration() .getMemoryInBytes(Property.TABLE_FILE_BLOCK_SIZE); Writer small = new RFile.Writer(new CachableBlockFile.Writer(fs, new Path(smallName), "gz", conf), blockSize); small.startDefaultLocalityGroup(); Writer large = new RFile.Writer(new CachableBlockFile.Writer(fs, new Path(largeName), "gz", conf), blockSize); large.startDefaultLocalityGroup(); iter.seek(new Range(), new ArrayList<ByteSequence>(), false); while (iter.hasTop()) { Key key = iter.getTopKey(); Value value = iter.getTopValue(); if (key.getSize() + value.getSize() < maxSize) { small.append(key, value); } else { large.append(key, value); } iter.next(); } iter.close(); large.close(); small.close(); } }
From source file:org.apache.accumulo.core.trace.TraceDump.java
public static void main(String[] args) throws Exception { CommandLine commandLine = new BasicParser().parse(OPTIONS, args); int code = 0; if (code == 0 && commandLine.hasOption(LIST_SPANS.getLongOpt())) { code = listSpans(commandLine);//from w ww . j av a2s .co m } if (code == 0 && commandLine.hasOption(DUMP_TRACE.getLongOpt())) { code = dumpTrace(commandLine); } System.exit(code); }
From source file:org.apache.accumulo.core.util.shell.Shell.java
public void execCommand(String input, boolean ignoreAuthTimeout, boolean echoPrompt) throws IOException { audit.log(Level.INFO, getDefaultPrompt() + input); if (echoPrompt) { reader.print(getDefaultPrompt()); reader.println(input);//www .j a v a 2 s. c o m } if (input.startsWith(COMMENT_PREFIX)) { return; } String fields[]; try { fields = new QuotedStringTokenizer(input).getTokens(); } catch (BadArgumentException e) { printException(e); ++exitCode; return; } if (fields.length == 0) return; String command = fields[0]; fields = fields.length > 1 ? Arrays.copyOfRange(fields, 1, fields.length) : new String[] {}; Command sc = null; if (command.length() > 0) { try { // Obtain the command from the command table sc = commandFactory.get(command); if (sc == null) { reader.println(String.format( "Unknown command \"%s\". Enter \"help\" for a list possible commands.", command)); reader.flush(); return; } if (!(sc instanceof ExitCommand) && !ignoreAuthTimeout && System.currentTimeMillis() - lastUserActivity > authTimeout) { reader.println("Shell has been idle for too long. Please re-authenticate."); boolean authFailed = true; do { String pwd = readMaskedLine("Enter current password for '" + connector.whoami() + "': ", '*'); if (pwd == null) { reader.println(); return; } // user canceled try { authFailed = !connector.securityOperations().authenticateUser(connector.whoami(), new PasswordToken(pwd)); } catch (Exception e) { ++exitCode; printException(e); } if (authFailed) reader.print("Invalid password. "); } while (authFailed); lastUserActivity = System.currentTimeMillis(); } // Get the options from the command on how to parse the string Options parseOpts = sc.getOptionsWithHelp(); // Parse the string using the given options CommandLine cl = new BasicParser().parse(parseOpts, fields); int actualArgLen = cl.getArgs().length; int expectedArgLen = sc.numArgs(); if (cl.hasOption(helpOption)) { // Display help if asked to; otherwise execute the command sc.printHelp(this); } else if (expectedArgLen != NO_FIXED_ARG_LENGTH_CHECK && actualArgLen != expectedArgLen) { ++exitCode; // Check for valid number of fixed arguments (if not // negative; negative means it is not checked, for // vararg-like commands) printException(new IllegalArgumentException(String.format( "Expected %d argument%s. There %s %d.", expectedArgLen, expectedArgLen == 1 ? "" : "s", actualArgLen == 1 ? "was" : "were", actualArgLen))); sc.printHelp(this); } else { int tmpCode = sc.execute(input, cl, this); exitCode += tmpCode; reader.flush(); } } catch (ConstraintViolationException e) { ++exitCode; printConstraintViolationException(e); } catch (TableNotFoundException e) { ++exitCode; if (getTableName().equals(e.getTableName())) setTableName(""); printException(e); } catch (ParseException e) { // not really an error if the exception is a missing required // option when the user is asking for help if (!(e instanceof MissingOptionException && (Arrays.asList(fields).contains("-" + helpOption) || Arrays.asList(fields).contains("--" + helpLongOption)))) { ++exitCode; printException(e); } if (sc != null) sc.printHelp(this); } catch (Exception e) { ++exitCode; printException(e); } } else { ++exitCode; printException(new BadArgumentException("Unrecognized empty command", command, -1)); } reader.flush(); }
From source file:org.apache.accumulo.examples.simple.client.ReadWriteExample.java
private void configure(String[] args) throws ParseException, AccumuloException, AccumuloSecurityException { usernameOpt.setRequired(true);/*from w w w . j a v a 2s . c o m*/ passwordOpt.setRequired(true); opts = new Options(); addOptions(instanceOpt, zooKeepersOpt, usernameOpt, passwordOpt, scanAuthsOpt, tableNameOpt, createtableOpt, deletetableOpt, createEntriesOpt, deleteEntriesOpt, readEntriesOpt, debugOpt); // parse command line cl = new BasicParser().parse(opts, args); if (cl.getArgs().length != 0) throw new ParseException("unrecognized options " + cl.getArgList()); // optionally enable debugging if (hasOpt(debugOpt)) Logger.getLogger(Constants.CORE_PACKAGE_NAME).setLevel(Level.TRACE); Instance inst = new ZooKeeperInstance(getOpt(instanceOpt, DEFAULT_INSTANCE_NAME), getOpt(zooKeepersOpt, DEFAULT_ZOOKEEPERS)); conn = inst.getConnector(getRequiredOpt(usernameOpt), getRequiredOpt(passwordOpt).getBytes()); }
From source file:org.apache.accumulo.examples.simple.mapreduce.WordCount.java
public int run(String[] unprocessed_args) throws Exception { Parser p = new BasicParser(); CommandLine cl = p.parse(opts, unprocessed_args); String[] args = cl.getArgs(); String username = cl.getOptionValue(usernameOpt.getOpt(), "root"); String password = cl.getOptionValue(passwordOpt.getOpt(), "secret"); if (args.length != 4) { System.out.println("ERROR: Wrong number of parameters: " + args.length + " instead of 4."); return printUsage(); }//from w w w. jav a 2s .c om Job job = new Job(getConf(), WordCount.class.getName()); job.setJarByClass(this.getClass()); job.setInputFormatClass(TextInputFormat.class); TextInputFormat.setInputPaths(job, new Path(args[2])); job.setMapperClass(MapClass.class); job.setNumReduceTasks(0); job.setOutputFormatClass(AccumuloOutputFormat.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Mutation.class); AccumuloOutputFormat.setOutputInfo(job.getConfiguration(), username, password.getBytes(), true, args[3]); AccumuloOutputFormat.setZooKeeperInstance(job.getConfiguration(), args[0], args[1]); job.waitForCompletion(true); return 0; }
From source file:org.apache.accumulo.server.gc.SimpleGarbageCollector.java
public SimpleGarbageCollector(String[] args) throws UnknownHostException { Options opts = new Options(); optVerboseMode = new Option("v", "verbose", false, "extra information will get printed to stdout also"); optSafeMode = new Option("s", "safemode", false, "safe mode will not delete files"); optOffline = new Option("o", "offline", false, "offline mode will run once and check data files directly; this is dangerous if accumulo is running or not shut down properly"); optAddress = new Option("a", "address", true, "specify our local address"); opts.addOption(optVerboseMode);//from w w w . j a v a2 s . co m opts.addOption(optSafeMode); opts.addOption(optOffline); opts.addOption(optAddress); try { commandLine = new BasicParser().parse(opts, args); if (commandLine.getArgs().length != 0) throw new ParseException("Extraneous arguments"); safemode = commandLine.hasOption(optSafeMode.getOpt()); offline = commandLine.hasOption(optOffline.getOpt()); verbose = commandLine.hasOption(optVerboseMode.getOpt()); address = commandLine.getOptionValue(optAddress.getOpt()); } catch (ParseException e) { String str = "Can't parse the command line options"; log.fatal(str, e); throw new IllegalArgumentException(str, e); } }
From source file:org.apache.accumulo.server.logger.LogReader.java
/** * Dump a Log File (Map or Sequence) to stdout. Will read from HDFS or local file system. * // w ww . j a v a 2 s. c o m * @param args * - first argument is the file to print * @throws IOException * @throws ParseException */ public static void main(String[] args) throws IOException { Configuration conf = CachedConfiguration.getInstance(); FileSystem fs = TraceFileSystem .wrap(FileUtil.getFileSystem(conf, ServerConfiguration.getSiteConfiguration())); FileSystem local = TraceFileSystem.wrap(FileSystem.getLocal(conf)); Option rowOpt = new Option("r", "--row", true, "search for a specific row"); Option maxOpt = new Option("m", "--max-mutations", true, "the maximum number of mutations to print per log entry"); Option tabletOpt = new Option("t", "--tablet", true, "key extent"); Option rowPatternOpt = new Option("p", "--row-pattern", true, "search for a row that matches the given regex"); Options options = new Options(); options.addOption(rowOpt); options.addOption(maxOpt); options.addOption(tabletOpt); options.addOption(rowPatternOpt); CommandLine cl; try { cl = new BasicParser().parse(options, args); } catch (ParseException ex) { usage(); return; } Matcher rowMatcher = null; KeyExtent ke = null; Text row = null; int max = 5; String[] files = cl.getArgs(); if (files.length == 0) { usage(); return; } if (cl.hasOption(rowOpt.getOpt())) row = new Text(cl.getOptionValue(rowOpt.getOpt())); if (cl.hasOption(maxOpt.getOpt())) max = Integer.parseInt(cl.getOptionValue(maxOpt.getOpt())); if (cl.hasOption(tabletOpt.getOpt())) { String extent = cl.getOptionValue(tabletOpt.getOpt()); String sa[] = extent.split(";"); ke = new KeyExtent(new Text(sa[0]), new Text(sa[1]), new Text(sa[2])); } if (cl.hasOption(rowPatternOpt.getOpt())) { Pattern pattern = Pattern.compile(cl.getOptionValue(rowPatternOpt.getOpt())); rowMatcher = pattern.matcher(""); } Set<Integer> tabletIds = new HashSet<Integer>(); for (String file : files) { Path path = new Path(file); LogFileKey key = new LogFileKey(); LogFileValue value = new LogFileValue(); if (fs.isFile(path)) { // read log entries from a simple hdfs file org.apache.hadoop.io.SequenceFile.Reader reader = new SequenceFile.Reader(fs, new Path(file), conf); while (reader.next(key, value)) { printLogEvent(key, value, row, rowMatcher, ke, tabletIds, max); } } else if (local.isFile(path)) { // read log entries from a simple file org.apache.hadoop.io.SequenceFile.Reader reader = new SequenceFile.Reader(local, new Path(file), conf); while (reader.next(key, value)) { printLogEvent(key, value, row, rowMatcher, ke, tabletIds, max); } } else { try { // read the log entries sorted in a map file MultiReader input = new MultiReader(fs, conf, file); while (input.next(key, value)) { printLogEvent(key, value, row, rowMatcher, ke, tabletIds, max); } } catch (FileNotFoundException ex) { SequenceFile.Reader input = new SequenceFile.Reader(local, new Path(file), conf); while (input.next(key, value)) { printLogEvent(key, value, row, rowMatcher, ke, tabletIds, max); } } } } }
From source file:org.apache.accumulo.server.test.CreateTestTable.java
public static void main(String[] args) throws Exception { setupOptions();/*ww w . ja v a 2 s . c o m*/ Parser p = new BasicParser(); CommandLine cl = null; try { cl = p.parse(opts, args); } catch (ParseException e) { throw new RuntimeException(e); } String[] rargs = cl.getArgs(); if (rargs.length != 1) { HelpFormatter hf = new HelpFormatter(); hf.printHelp(" <count> ", opts); } count = Integer.parseInt(rargs[0]); readOnly = cl.hasOption(readonlyOpt.getOpt()); user = cl.getOptionValue(usernameOpt.getOpt(), "root"); password = cl.getOptionValue(passwordOpt.getOpt(), "secret"); // create the test table within accumulo String table = "mrtest1"; Connector connector; connector = HdfsZooInstance.getInstance().getConnector(user, password.getBytes()); if (!readOnly) { TreeSet<Text> keys = new TreeSet<Text>(); for (int i = 0; i < count / 100; i++) { keys.add(new Text(String.format("%05d", i * 100))); } // presplit connector.tableOperations().create(table); connector.tableOperations().addSplits(table, keys); BatchWriter b = connector.createBatchWriter(table, 10000000l, 1000000l, 10); // populate for (int i = 0; i < count; i++) { Mutation m = new Mutation(new Text(String.format("%05d", i))); m.put(new Text("col" + Integer.toString((i % 3) + 1)), new Text("qual"), new Value("junk".getBytes())); b.addMutation(m); } b.close(); } readBack(connector, count); }