Example usage for org.apache.commons.lang StringUtils isBlank

List of usage examples for org.apache.commons.lang StringUtils isBlank

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils isBlank.

Prototype

public static boolean isBlank(String str) 

Source Link

Document

Checks if a String is whitespace, empty ("") or null.

Usage

From source file:com.dianping.phoenix.dev.core.tools.generator.stable.ServiceMetaGenerator.java

public static void main(String[] args) throws Exception {
    ServiceMetaGenerator serviceMetaGenerator = new ServiceMetaGenerator();
    if (args == null || args.length == 0) {
        System.out.println(//from  w w w .j a va 2s. com
                "Usage com.dianping.phoenix.dev.core.tools.generator.stable.ServiceMetaGenerator destfile [jdbcUrl] [dbUsername] [dbPassword]");
        System.exit(1);
    }

    String destFile = args[0];
    String jdbcUrl = (args.length < 2 || StringUtils.isBlank(args[1])) ? "jdbc:mysql://192.168.7.105:3306/hawk"
            : args[1];
    String dbUsername = (args.length < 3 || StringUtils.isBlank(args[2])) ? "dpcom_hawk" : args[2];
    String dbPassword = (args.length < 4 || StringUtils.isBlank(args[3])) ? "123456" : args[3];

    serviceMetaGenerator.generate(new File(destFile),
            new ServiceMetaContext("com.mysql.jdbc.Driver", jdbcUrl, dbUsername, dbPassword));
}

From source file:de.codesourcery.eve.skills.ui.model.FilteringTreeModel.java

public static void main(String[] args) {
    final JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    final FilteringTreeModel model = new FilteringTreeModel(createTreeModel());

    // setup text field
    final JTextField filterTextField = new JTextField(30);
    filterTextField.addActionListener(new ActionListener() {

        @Override/*from w  w w  .j a  v a2 s .c o m*/
        public void actionPerformed(ActionEvent e) {
            model.viewFilterChanged();
        }
    });

    // setup tree
    final JTree tree = new JTree();
    final IViewFilter<ITreeNode> filter = new AbstractViewFilter<ITreeNode>() {

        @Override
        public boolean isHiddenUnfiltered(ITreeNode node) {
            final String nodeValue = node.toString();
            final String expected = filterTextField.getText();

            final boolean isHidden = !StringUtils.isBlank(nodeValue) && !StringUtils.isBlank(expected)
                    && nodeValue.startsWith("child")
                    && !nodeValue.toLowerCase().contains(expected.toLowerCase());

            System.out.println(nodeValue + " does not match " + expected + " => " + isHidden);
            return isHidden;
        }
    };
    model.setViewFilter(filter);
    tree.setModel(model);

    // set 
    final JPanel panel = new JPanel();

    new GridLayoutBuilder()
            .add(new GridLayoutBuilder.HorizontalGroup(new GridLayoutBuilder.Cell(new JScrollPane(tree)),
                    new GridLayoutBuilder.FixedCell(filterTextField)))
            .addTo(panel);

    frame.getContentPane().add(panel);

    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

From source file:com.redhat.satellite.search.DeleteIndexes.java

/**
 * @param args//  w  w  w.j a  v  a  2 s .  co m
 */
public static void main(String[] args) {
    try {
        Configuration config = new Configuration();
        DatabaseManager databaseManager = new DatabaseManager(config);
        String indexWorkDir = config.getString("search.index_work_dir", null);
        if (StringUtils.isBlank(indexWorkDir)) {
            log.warn("Couldn't find path for where index files are stored.");
            log.warn("Looked in config for property: search.index_work_dir");
            return;
        }
        List<IndexInfo> indexes = new ArrayList<IndexInfo>();
        indexes.add(new IndexInfo("deleteLastErrata", indexWorkDir + File.separator + "errata"));
        indexes.add(new IndexInfo("deleteLastPackage", indexWorkDir + File.separator + "package"));
        indexes.add(new IndexInfo("deleteLastServer", indexWorkDir + File.separator + "server"));
        indexes.add(new IndexInfo("deleteLastHardwareDevice", indexWorkDir + File.separator + "hwdevice"));
        indexes.add(new IndexInfo("deleteLastSnapshotTag", indexWorkDir + File.separator + "snapshotTag"));
        indexes.add(new IndexInfo("deleteLastServerCustomInfo",
                indexWorkDir + File.separator + "serverCustomInfo"));
        indexes.add(new IndexInfo("deleteLastXccdfIdent", indexWorkDir + File.separator + "xccdfIdent"));
        for (IndexInfo info : indexes) {
            deleteQuery(databaseManager, info.getQueryName());
            if (!deleteIndexPath(info.getDirPath())) {
                log.warn("Failed to delete index for " + info.getDirPath());
            }
        }
    } catch (SQLException e) {
        log.error("Caught Exception: ", e);
        if (e.getErrorCode() == 17002) {
            log.error("Unable to establish database connection.");
            log.error("Ensure database is available and connection details are " + "correct, then retry");
        }
        System.exit(1);
    } catch (IOException e) {
        log.error("Caught Exception: ", e);
        System.exit(1);
    }
    log.info("Index files have been deleted and database has been cleaned up, " + "ready to reindex");
}

From source file:com.cws.esolutions.core.main.SQLUtility.java

public static final void main(final String[] args) {
    final String methodName = SQLUtility.CNAME + "#main(final String[] args)";

    if (DEBUG) {/*  www . j  ava  2 s  .co  m*/
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", (Object) args);
    }

    if (args.length == 0) {
        HelpFormatter usage = new HelpFormatter();
        usage.printHelp(SQLUtility.CNAME, options, true);

        return;
    }

    final String coreConfiguration = (StringUtils.isBlank(System.getProperty("coreConfigFile")))
            ? SQLUtility.CORE_SVC_CONFIG
            : System.getProperty("coreConfigFile");
    final String securityConfiguration = (StringUtils.isBlank(System.getProperty("secConfigFile")))
            ? SQLUtility.CORE_LOG_CONFIG
            : System.getProperty("secConfigFile");
    final String coreLogging = (StringUtils.isBlank(System.getProperty("coreLogConfig")))
            ? SQLUtility.SEC_SVC_CONFIG
            : System.getProperty("coreLogConfig");
    final String securityLogging = (StringUtils.isBlank(System.getProperty("secLogConfig")))
            ? SQLUtility.SEC_LOG_CONFIG
            : System.getProperty("secLogConfig");

    if (DEBUG) {
        DEBUGGER.debug("String coreConfiguration: {}", coreConfiguration);
        DEBUGGER.debug("String securityConfiguration: {}", securityConfiguration);
        DEBUGGER.debug("String coreLogging: {}", coreLogging);
        DEBUGGER.debug("String securityLogging: {}", securityLogging);
    }

    try {
        SecurityServiceInitializer.initializeService(securityConfiguration, securityLogging, false);
        CoreServiceInitializer.initializeService(coreConfiguration, coreLogging, false, true);
    } catch (CoreServiceException csx) {
        System.err
                .println("An error occurred while loading configuration data: " + csx.getCause().getMessage());

        System.exit(1);
    } catch (SecurityServiceException sx) {
        System.err.println("An error occurred while loading configuration data: " + sx.getCause().getMessage());

        System.exit(1);
    }

    Options options = new Options();

    try {
        throw new ParseException("nothing to see here");
    } catch (ParseException px) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(SQLUtility.CNAME, options, true);
    }
}

From source file:com.mozilla.socorro.RawDumpSizeScan.java

public static void main(String[] args) throws ParseException {
    String startDateStr = args[0];
    String endDateStr = args[1];/* w  ww  . j a  v  a2 s  .  c om*/

    // Set both start/end time and start/stop row
    Calendar startCal = Calendar.getInstance();
    Calendar endCal = Calendar.getInstance();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    if (!StringUtils.isBlank(startDateStr)) {
        startCal.setTime(sdf.parse(startDateStr));
    }
    if (!StringUtils.isBlank(endDateStr)) {
        endCal.setTime(sdf.parse(endDateStr));
    }

    DescriptiveStatistics stats = new DescriptiveStatistics();
    long numNullRawBytes = 0L;
    HTable table = null;
    Map<String, Integer> rowValueSizeMap = new HashMap<String, Integer>();
    try {
        table = new HTable(TABLE_NAME_CRASH_REPORTS);
        Scan[] scans = generateScans(startCal, endCal);
        for (Scan s : scans) {
            ResultScanner rs = table.getScanner(s);
            Iterator<Result> iter = rs.iterator();
            while (iter.hasNext()) {
                Result r = iter.next();
                ImmutableBytesWritable rawBytes = r.getBytes();
                //length = r.getValue(RAW_DATA_BYTES, DUMP_BYTES);
                if (rawBytes != null) {
                    int length = rawBytes.getLength();
                    if (length > 20971520) {
                        rowValueSizeMap.put(new String(r.getRow()), length);
                    }
                    stats.addValue(length);
                } else {
                    numNullRawBytes++;
                }

                if (stats.getN() % 10000 == 0) {
                    System.out.println("Processed " + stats.getN());
                    System.out.println(String.format("Min: %.02f Max: %.02f Mean: %.02f", stats.getMin(),
                            stats.getMax(), stats.getMean()));
                    System.out.println(
                            String.format("1st Quartile: %.02f 2nd Quartile: %.02f 3rd Quartile: %.02f",
                                    stats.getPercentile(25.0d), stats.getPercentile(50.0d),
                                    stats.getPercentile(75.0d)));
                    System.out.println("Number of large entries: " + rowValueSizeMap.size());
                }
            }
            rs.close();
        }

        System.out.println("Finished Processing!");
        System.out.println(String.format("Min: %.02f Max: %.02f Mean: %.02f", stats.getMin(), stats.getMax(),
                stats.getMean()));
        System.out.println(String.format("1st Quartile: %.02f 2nd Quartile: %.02f 3rd Quartile: %.02f",
                stats.getPercentile(25.0d), stats.getPercentile(50.0d), stats.getPercentile(75.0d)));

        for (Map.Entry<String, Integer> entry : rowValueSizeMap.entrySet()) {
            System.out.println(String.format("RowId: %s => Length: %d", entry.getKey(), entry.getValue()));
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (table != null) {
            try {
                table.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

From source file:backtype.storm.command.gray_upgrade.java

public static void main(String[] args) throws Exception {
    if (args == null || args.length < 1) {
        System.out.println("Invalid parameter");
        usage();/*from w w  w . j ava2 s.co  m*/
        return;
    }
    String topologyName = args[0];
    String[] str2 = Arrays.copyOfRange(args, 1, args.length);
    CommandLineParser parser = new GnuParser();
    Options r = buildGeneralOptions(new Options());
    CommandLine commandLine = parser.parse(r, str2, true);

    int workerNum = 0;
    String component = null;
    List<String> workers = null;
    if (commandLine.hasOption("n")) {
        workerNum = Integer.valueOf(commandLine.getOptionValue("n"));
    }
    if (commandLine.hasOption("p")) {
        component = commandLine.getOptionValue("p");
    }
    if (commandLine.hasOption("w")) {
        String w = commandLine.getOptionValue("w");
        if (!StringUtils.isBlank(w)) {
            workers = Lists.newArrayList();
            String[] parts = w.split(",");
            for (String part : parts) {
                if (part.split(":").length == 2) {
                    workers.add(part.trim());
                }
            }
        }
    }
    upgradeTopology(topologyName, component, workers, workerNum);
}

From source file:com.cws.esolutions.security.main.UserManagementUtility.java

public static final void main(final String[] args) {
    final String methodName = UserManagementUtility.CNAME + "#main(final String[] args)";

    if (DEBUG) {//from   ww w .  j av  a2s . c  o m
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", (Object) args);
    }

    if (args.length == 0) {
        HelpFormatter usage = new HelpFormatter();
        usage.printHelp(UserManagementUtility.CNAME, options, true);

        return;
    }

    try {
        CommandLineParser parser = new PosixParser();
        CommandLine commandLine = parser.parse(options, args);

        if (DEBUG) {
            DEBUGGER.debug("CommandLineParser parser: {}", parser);
            DEBUGGER.debug("CommandLine commandLine: {}", commandLine);
            DEBUGGER.debug("CommandLine commandLine.getOptions(): {}", (Object[]) commandLine.getOptions());
            DEBUGGER.debug("CommandLine commandLine.getArgList(): {}", commandLine.getArgList());
        }

        if ((commandLine.hasOption("configFile"))
                && (!(StringUtils.isBlank(commandLine.getOptionValue("configFile"))))) {
            SecurityServiceInitializer.initializeService(commandLine.getOptionValue("configFile"),
                    UserManagementUtility.LOG_CONFIG, true);
        } else {
            SecurityServiceInitializer.initializeService(UserManagementUtility.SEC_CONFIG,
                    UserManagementUtility.LOG_CONFIG, true);
        }

        AccountControlResponse response = null;

        final UserAccount userAccount = new UserAccount();
        final RequestHostInfo reqInfo = new RequestHostInfo();
        final SecurityConfigurationData secConfigData = UserManagementUtility.svcBean.getConfigData();
        final SecurityConfig secConfig = secConfigData.getSecurityConfig();

        try {
            reqInfo.setHostAddress(InetAddress.getLocalHost().getHostAddress());
            reqInfo.setHostName(InetAddress.getLocalHost().getHostName());
        } catch (UnknownHostException uhx) {
            reqInfo.setHostAddress("127.0.0.1");
            reqInfo.setHostName("localhost");
        }

        if (DEBUG) {
            DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData);
            DEBUGGER.debug("SecurityConfig secConfig: {}", secConfig);
            DEBUGGER.debug("RequestHostInfo reqInfo: {}", reqInfo);
        }

        AccountControlRequest request = new AccountControlRequest();
        request.setApplicationId(secConfig.getApplicationId());
        request.setApplicationName(secConfig.getApplicationName());
        request.setHostInfo(reqInfo);
        request.setRequestor(secConfig.getSvcAccount());

        if (DEBUG) {
            DEBUGGER.debug("AccountControlRequest request: {}", request);
        }

        if (commandLine.hasOption("search")) {
            if (StringUtils.isEmpty(commandLine.getOptionValue("search"))) {
                throw new ParseException("No entry option was provided. Cannot continue.");
            }

            userAccount.setEmailAddr(commandLine.getOptionValue("search"));

            if (DEBUG) {
                DEBUGGER.debug("UserAccount userAccount: {}", userAccount);
            }

            request.setUserAccount(userAccount);

            if (DEBUG) {
                DEBUGGER.debug("AccountControlRequest: {}", request);
            }

            response = processor.searchAccounts(request);
        } else if (commandLine.hasOption("load")) {
            if (StringUtils.isEmpty(commandLine.getOptionValue("load"))) {
                throw new ParseException("No entry option was provided. Cannot continue.");
            }

            userAccount.setGuid(commandLine.getOptionValue("load"));

            request.setUserAccount(userAccount);

            if (DEBUG) {
                DEBUGGER.debug("AccountControlRequest: {}", request);
            }

            response = processor.loadUserAccount(request);
        }

        if (DEBUG) {
            DEBUGGER.debug("AccountControlResponse response: {}", response);
        }

        if ((response != null) && (response.getRequestStatus() == SecurityRequestStatus.SUCCESS)) {
            UserAccount account = response.getUserAccount();

            if (DEBUG) {
                DEBUGGER.debug("UserAccount: {}", account);
            }

            System.out.println(account);
        }
    } catch (ParseException px) {
        ERROR_RECORDER.error(px.getMessage(), px);

        System.err.println("An error occurred during processing: " + px.getMessage());
    } catch (SecurityException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        System.err.println("An error occurred during processing: " + sx.getMessage());
    } catch (SecurityServiceException ssx) {
        ERROR_RECORDER.error(ssx.getMessage(), ssx);

        System.err.println("An error occurred during processing: " + ssx.getMessage());
    }
}

From source file:com.cws.esolutions.security.main.PasswordUtility.java

public static void main(final String[] args) {
    final String methodName = PasswordUtility.CNAME + "#main(final String[] args)";

    if (DEBUG) {//from ww  w .j  a va 2 s  . c om
        DEBUGGER.debug("Value: {}", methodName);
    }

    if (args.length == 0) {
        HelpFormatter usage = new HelpFormatter();
        usage.printHelp(PasswordUtility.CNAME, options, true);

        System.exit(1);
    }

    BufferedReader bReader = null;
    BufferedWriter bWriter = null;

    try {
        // load service config first !!
        SecurityServiceInitializer.initializeService(PasswordUtility.SEC_CONFIG, PasswordUtility.LOG_CONFIG,
                false);

        if (DEBUG) {
            DEBUGGER.debug("Options options: {}", options);

            for (String arg : args) {
                DEBUGGER.debug("Value: {}", arg);
            }
        }

        CommandLineParser parser = new PosixParser();
        CommandLine commandLine = parser.parse(options, args);

        if (DEBUG) {
            DEBUGGER.debug("CommandLineParser parser: {}", parser);
            DEBUGGER.debug("CommandLine commandLine: {}", commandLine);
            DEBUGGER.debug("CommandLine commandLine.getOptions(): {}", (Object[]) commandLine.getOptions());
            DEBUGGER.debug("CommandLine commandLine.getArgList(): {}", commandLine.getArgList());
        }

        final SecurityConfigurationData secConfigData = PasswordUtility.svcBean.getConfigData();
        final SecurityConfig secConfig = secConfigData.getSecurityConfig();
        final PasswordRepositoryConfig repoConfig = secConfigData.getPasswordRepo();
        final SystemConfig systemConfig = secConfigData.getSystemConfig();

        if (DEBUG) {
            DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData);
            DEBUGGER.debug("SecurityConfig secConfig: {}", secConfig);
            DEBUGGER.debug("RepositoryConfig secConfig: {}", repoConfig);
            DEBUGGER.debug("SystemConfig systemConfig: {}", systemConfig);
        }

        if (commandLine.hasOption("encrypt")) {
            if ((StringUtils.isBlank(repoConfig.getPasswordFile()))
                    || (StringUtils.isBlank(repoConfig.getSaltFile()))) {
                System.err.println("The password/salt files are not configured. Entries will not be stored!");
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            final String entryName = commandLine.getOptionValue("entry");
            final String username = commandLine.getOptionValue("username");
            final String password = commandLine.getOptionValue("password");
            final String salt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength());

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
                DEBUGGER.debug("String password: {}", password);
                DEBUGGER.debug("String salt: {}", salt);
            }

            final String encodedSalt = PasswordUtils.base64Encode(salt);
            final String encodedUserName = PasswordUtils.base64Encode(username);
            final String encryptedPassword = PasswordUtils.encryptText(password, salt,
                    secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                    secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                    systemConfig.getEncoding());
            final String encodedPassword = PasswordUtils.base64Encode(encryptedPassword);

            if (DEBUG) {
                DEBUGGER.debug("String encodedSalt: {}", encodedSalt);
                DEBUGGER.debug("String encodedUserName: {}", encodedUserName);
                DEBUGGER.debug("String encodedPassword: {}", encodedPassword);
            }

            if (commandLine.hasOption("store")) {
                try {
                    new File(passwordFile.getParent()).mkdirs();
                    new File(saltFile.getParent()).mkdirs();

                    boolean saltFileExists = (saltFile.exists()) ? true : saltFile.createNewFile();

                    if (DEBUG) {
                        DEBUGGER.debug("saltFileExists: {}", saltFileExists);
                    }

                    // write the salt out first
                    if (!(saltFileExists)) {
                        throw new IOException("Unable to create salt file");
                    }

                    boolean passwordFileExists = (passwordFile.exists()) ? true : passwordFile.createNewFile();

                    if (!(passwordFileExists)) {
                        throw new IOException("Unable to create password file");
                    }

                    if (commandLine.hasOption("replace")) {
                        File[] files = new File[] { saltFile, passwordFile };

                        if (DEBUG) {
                            DEBUGGER.debug("File[] files: {}", (Object) files);
                        }

                        for (File file : files) {
                            if (DEBUG) {
                                DEBUGGER.debug("File: {}", file);
                            }

                            String currentLine = null;
                            File tmpFile = new File(FileUtils.getTempDirectory() + "/" + "tmpFile");

                            if (DEBUG) {
                                DEBUGGER.debug("File tmpFile: {}", tmpFile);
                            }

                            bReader = new BufferedReader(new FileReader(file));
                            bWriter = new BufferedWriter(new FileWriter(tmpFile));

                            while ((currentLine = bReader.readLine()) != null) {
                                if (!(StringUtils.equals(currentLine.trim().split(",")[0], entryName))) {
                                    bWriter.write(currentLine + System.getProperty("line.separator"));
                                    bWriter.flush();
                                }
                            }

                            bWriter.close();

                            FileUtils.deleteQuietly(file);
                            FileUtils.copyFile(tmpFile, file);
                            FileUtils.deleteQuietly(tmpFile);
                        }
                    }

                    FileUtils.writeStringToFile(saltFile, entryName + "," + encodedUserName + "," + encodedSalt
                            + System.getProperty("line.separator"), true);
                    FileUtils.writeStringToFile(passwordFile, entryName + "," + encodedUserName + ","
                            + encodedPassword + System.getProperty("line.separator"), true);
                } catch (IOException iox) {
                    ERROR_RECORDER.error(iox.getMessage(), iox);
                }
            }

            System.out.println("Entry Name " + entryName + " stored.");
        }

        if (commandLine.hasOption("decrypt")) {
            String saltEntryName = null;
            String saltEntryValue = null;
            String decryptedPassword = null;
            String passwordEntryName = null;

            if ((StringUtils.isEmpty(commandLine.getOptionValue("entry"))
                    && (StringUtils.isEmpty(commandLine.getOptionValue("username"))))) {
                throw new ParseException("No entry or username was provided to decrypt.");
            }

            if (StringUtils.isEmpty(commandLine.getOptionValue("username"))) {
                throw new ParseException("no entry provided to decrypt");
            }

            String entryName = commandLine.getOptionValue("entry");
            String username = commandLine.getOptionValue("username");

            if (DEBUG) {
                DEBUGGER.debug("String entryName: {}", entryName);
                DEBUGGER.debug("String username: {}", username);
            }

            File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile());
            File saltFile = FileUtils.getFile(repoConfig.getSaltFile());

            if (DEBUG) {
                DEBUGGER.debug("File passwordFile: {}", passwordFile);
                DEBUGGER.debug("File saltFile: {}", saltFile);
            }

            if ((!(saltFile.canRead())) || (!(passwordFile.canRead()))) {
                throw new IOException(
                        "Unable to read configured password/salt file. Please check configuration and/or permissions.");
            }

            for (String lineEntry : FileUtils.readLines(saltFile, systemConfig.getEncoding())) {
                saltEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String saltEntryName: {}", saltEntryName);
                }

                if (StringUtils.equals(saltEntryName, entryName)) {
                    saltEntryValue = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    break;
                }
            }

            if (StringUtils.isEmpty(saltEntryValue)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            for (String lineEntry : FileUtils.readLines(passwordFile, systemConfig.getEncoding())) {
                passwordEntryName = lineEntry.split(",")[0];

                if (DEBUG) {
                    DEBUGGER.debug("String passwordEntryName: {}", passwordEntryName);
                }

                if (StringUtils.equals(passwordEntryName, saltEntryName)) {
                    String decodedPassword = PasswordUtils.base64Decode(lineEntry.split(",")[2]);

                    decryptedPassword = PasswordUtils.decryptText(decodedPassword, saltEntryValue,
                            secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(),
                            secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(),
                            systemConfig.getEncoding());

                    break;
                }
            }

            if (StringUtils.isEmpty(decryptedPassword)) {
                throw new SecurityException("No entries were found that matched the provided information");
            }

            System.out.println(decryptedPassword);
        } else if (commandLine.hasOption("encode")) {
            System.out.println(PasswordUtils.base64Encode((String) commandLine.getArgList().get(0)));
        } else if (commandLine.hasOption("decode")) {
            System.out.println(PasswordUtils.base64Decode((String) commandLine.getArgList().get(0)));
        }
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        System.err.println("An error occurred during processing: " + iox.getMessage());
        System.exit(1);
    } catch (ParseException px) {
        ERROR_RECORDER.error(px.getMessage(), px);

        System.err.println("An error occurred during processing: " + px.getMessage());
        System.exit(1);
    } catch (SecurityException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        System.err.println("An error occurred during processing: " + sx.getMessage());
        System.exit(1);
    } catch (SecurityServiceException ssx) {
        ERROR_RECORDER.error(ssx.getMessage(), ssx);
        System.exit(1);
    } finally {
        try {
            if (bReader != null) {
                bReader.close();
            }

            if (bWriter != null) {
                bReader.close();
            }
        } catch (IOException iox) {
        }
    }

    System.exit(0);
}

From source file:de.codesourcery.geoip.Main.java

public static void main(String[] args) throws Exception {
    final IGeoLocator<StringSubject> locator = createGeoLocator();

    final JFrame frame = new JFrame("GeoIP");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(java.awt.event.WindowEvent e) {
            try {
                locator.dispose();/*  ww w  .j a  va 2s .  c o m*/
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        };
    });

    final MapImage image = MapImage.getRobinsonWorldMap(); // MapImage.getMillerWorldMap();      
    final MapCanvas canvas = new MapCanvas(image);

    for (GeoLocation<StringSubject> loc : locator.locate(getSpammers())) {
        if (loc.hasValidCoordinates()) {
            canvas.addCoordinate(PointRenderer.createPoint(loc, Color.YELLOW));
        }
    }

    //      canvas.addCoordinate( PointRenderer.createPoint( ZERO , Color.YELLOW ) );
    //      canvas.addCoordinate( PointRenderer.createPoint( WELLINGTON , Color.RED ) );
    //      canvas.addCoordinate( PointRenderer.createPoint( MELBOURNE , Color.RED ) );
    //      canvas.addCoordinate( PointRenderer.createPoint( HAMBURG , Color.RED ) );

    final double heightToWidth = image.height() / (double) image.width(); // preserve aspect ratio of map
    canvas.setPreferredSize(new Dimension(640, (int) Math.round(640 * heightToWidth)));

    JPanel panel = new JPanel();
    panel.setLayout(new FlowLayout());

    panel.add(new JLabel("Scale-X"));
    final JTextField scaleX = new JTextField(Double.toString(image.getScaleX()));
    scaleX.setColumns(5);

    final JTextField scaleY = new JTextField(Double.toString(image.getScaleY()));
    scaleY.setColumns(5);

    final ActionListener listener = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            double x = Double.parseDouble(scaleX.getText());
            double y = Double.parseDouble(scaleY.getText());
            image.setScale(x, y);
            canvas.repaint();
        }
    };
    scaleX.addActionListener(listener);
    scaleY.addActionListener(listener);

    panel.add(new JLabel("Scale-X"));
    panel.add(scaleX);

    panel.add(new JLabel("Scale-Y"));
    panel.add(scaleY);

    final JTextField ipAddress = new JTextField("www.kickstarter.com");
    ipAddress.setColumns(20);

    final ActionListener ipListener = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final String destinationIP = ipAddress.getText();
            if (StringUtils.isBlank(destinationIP)) {
                return;
            }

            /*
             * Perform traceroute.
             */
            final List<String> hops;
            try {
                if (TracePath.isPathTracingAvailable()) {
                    hops = TracePath.trace(destinationIP);
                } else {
                    System.err.println("tracepath not available.");
                    if (TracePath.isValidAddress(destinationIP)) {
                        hops = new ArrayList<>();
                        hops.add(destinationIP);
                    } else {
                        System.err.println(destinationIP + " is no valid IP");
                        return;
                    }
                }
            } catch (Exception ex) {
                System.err.println("Failed to trace " + destinationIP);
                ex.printStackTrace();
                return;
            }

            System.out.println("Trace contains " + hops.size() + " IPs");

            /*
             * Gather locations.
             */
            final List<StringSubject> subjects = new ArrayList<>();
            for (String ip : hops) {
                subjects.add(new StringSubject(ip));
            }

            final List<GeoLocation<StringSubject>> locations;
            try {
                long time = -System.currentTimeMillis();
                locations = locator.locate(subjects);
                time += System.currentTimeMillis();

                System.out.println("Locating hops for " + destinationIP + " returned " + locations.size()
                        + " valid locations ( time: " + time + " ms)");
                System.out.flush();

            } catch (Exception e2) {
                e2.printStackTrace();
                return;
            }

            /*
             * Weed-out invalid/unknown locations.
             */
            {
                GeoLocation<StringSubject> previous = null;
                for (Iterator<GeoLocation<StringSubject>> it = locations.iterator(); it.hasNext();) {
                    final GeoLocation<StringSubject> location = it.next();
                    if (!location.hasValidCoordinates()
                            || (previous != null && previous.coordinate().equals(location.coordinate()))) {
                        it.remove();
                        System.err.println("Ignoring invalid/duplicate location for " + location);
                    } else {
                        previous = location;
                    }
                }
            }

            /*
             * Populate chart.
             */

            System.out.println("Adding " + locations.size() + " hops to chart");
            System.out.flush();

            canvas.removeAllCoordinates();

            if (locations.size() == 1) {
                canvas.addCoordinate(
                        PointRenderer.createPoint(locations.get(0), getLabel(locations.get(0)), Color.BLACK));
            } else if (locations.size() > 1) {
                GeoLocation<StringSubject> previous = locations.get(0);
                MapPoint previousPoint = PointRenderer.createPoint(previous, getLabel(previous), Color.BLACK);
                final int len = locations.size();
                for (int i = 1; i < len; i++) {
                    final GeoLocation<StringSubject> current = locations.get(i);
                    //                  final MapPoint currentPoint = PointRenderer.createPoint( current , getLabel( current ) , Color.BLACK );
                    final MapPoint currentPoint = PointRenderer.createPoint(current, Color.BLACK);

                    //                  canvas.addCoordinate( LineRenderer.createLine( previousPoint , currentPoint , Color.RED ) );
                    canvas.addCoordinate(CurvedLineRenderer.createLine(previousPoint, currentPoint, Color.RED));

                    previous = locations.get(i);
                    previousPoint = currentPoint;
                }
            }
            System.out.println("Finished adding");
            System.out.flush();
            canvas.repaint();
        }
    };
    ipAddress.addActionListener(ipListener);

    panel.add(new JLabel("IP"));
    panel.add(ipAddress);

    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(panel, BorderLayout.NORTH);
    frame.getContentPane().add(canvas, BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
}

From source file:de.burlov.amazon.s3.dirsync.CLI.java

/**
 * @param args/* w w w .  j a v a 2 s  .  co  m*/
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    Logger.getLogger("").setLevel(Level.OFF);
    Logger deLogger = Logger.getLogger("de");
    deLogger.setLevel(Level.INFO);
    Handler handler = new ConsoleHandler();
    handler.setFormatter(new VerySimpleFormatter());
    deLogger.addHandler(handler);
    deLogger.setUseParentHandlers(false);
    //      if (true)
    //      {
    //         LogFactory.getLog(CLI.class).error("test msg", new Exception("test extception"));
    //         return;
    //      }
    Options opts = new Options();
    OptionGroup gr = new OptionGroup();

    /*
     * Befehlsgruppe initialisieren
     */
    gr = new OptionGroup();
    gr.setRequired(true);
    gr.addOption(OptionBuilder.withArgName("up|down").hasArg()
            .withDescription("Upload/Download changed or new files").create(CMD_UPDATE));
    gr.addOption(OptionBuilder.withArgName("up|down").hasArg()
            .withDescription("Upload/Download directory snapshot").create(CMD_SNAPSHOT));
    gr.addOption(OptionBuilder.withDescription("Delete remote folder").create(CMD_DELETE_DIR));
    gr.addOption(OptionBuilder.withDescription("Delete a bucket").create(CMD_DELETE_BUCKET));
    gr.addOption(OptionBuilder.create(CMD_HELP));
    gr.addOption(OptionBuilder.create(CMD_VERSION));
    gr.addOption(OptionBuilder.withDescription("Prints summary for stored data").create(CMD_SUMMARY));
    gr.addOption(OptionBuilder.withDescription("Clean up orphaned objekts").create(CMD_CLEANUP));
    gr.addOption(OptionBuilder.withDescription("Changes encryption password").withArgName("new password")
            .hasArg().create(CMD_CHANGE_PASSWORD));
    gr.addOption(OptionBuilder.withDescription("Lists all buckets").create(CMD_LIST_BUCKETS));
    gr.addOption(OptionBuilder.withDescription("Lists raw objects in a bucket").create(CMD_LIST_BUCKET));
    gr.addOption(OptionBuilder.withDescription("Lists files in remote folder").create(CMD_LIST_DIR));
    opts.addOptionGroup(gr);
    /*
     * Parametergruppe initialisieren
     */
    opts.addOption(OptionBuilder.withArgName("key").isRequired(false).hasArg().withDescription("S3 access key")
            .create(OPT_S3S_KEY));
    opts.addOption(OptionBuilder.withArgName("secret").isRequired(false).hasArg()
            .withDescription("Secret key for S3 account").create(OPT_S3S_SECRET));
    opts.addOption(OptionBuilder.withArgName("bucket").isRequired(false).hasArg().withDescription(
            "Optional bucket name for storage. If not specified then an unique bucket name will be generated")
            .create(OPT_BUCKET));
    // opts.addOption(OptionBuilder.withArgName("US|EU").hasArg().
    // withDescription(
    // "Where the new bucket should be created. Default US").create(
    // OPT_LOCATION));
    opts.addOption(OptionBuilder.withArgName("path").isRequired(false).hasArg()
            .withDescription("Local directory path").create(OPT_LOCAL_DIR));
    opts.addOption(OptionBuilder.withArgName("name").isRequired(false).hasArg()
            .withDescription("Remote directory name").create(OPT_REMOTE_DIR));
    opts.addOption(OptionBuilder.withArgName("password").isRequired(false).hasArg()
            .withDescription("Encryption password").create(OPT_ENC_PASSWORD));
    opts.addOption(OptionBuilder.withArgName("patterns").hasArgs()
            .withDescription("Comma separated exclude file patterns like '*.tmp,*/dir/*.tmp'")
            .create(OPT_EXCLUDE_PATTERNS));
    opts.addOption(OptionBuilder.withArgName("patterns").hasArgs().withDescription(
            "Comma separated include patterns like '*.java'. If not specified, then all files in specified local directory will be included")
            .create(OPT_INCLUDE_PATTERNS));

    if (args.length == 0) {
        printUsage(opts);
        return;
    }

    CommandLine cmd = null;
    try {
        cmd = new GnuParser().parse(opts, args);
        if (cmd.hasOption(CMD_HELP)) {
            printUsage(opts);
            return;
        }
        if (cmd.hasOption(CMD_VERSION)) {
            System.out.println("s3dirsync version " + Version.CURRENT_VERSION);
            return;
        }
        String awsKey = cmd.getOptionValue(OPT_S3S_KEY);
        String awsSecret = cmd.getOptionValue(OPT_S3S_SECRET);
        String bucket = cmd.getOptionValue(OPT_BUCKET);
        String bucketLocation = cmd.getOptionValue(OPT_LOCATION);
        String localDir = cmd.getOptionValue(OPT_LOCAL_DIR);
        String remoteDir = cmd.getOptionValue(OPT_REMOTE_DIR);
        String password = cmd.getOptionValue(OPT_ENC_PASSWORD);
        String exclude = cmd.getOptionValue(OPT_EXCLUDE_PATTERNS);
        String include = cmd.getOptionValue(OPT_INCLUDE_PATTERNS);

        if (StringUtils.isBlank(awsKey) || StringUtils.isBlank(awsSecret)) {
            System.out.println("S3 account data required");
            return;
        }

        if (StringUtils.isBlank(bucket)) {
            bucket = awsKey + ".dirsync";
        }

        if (cmd.hasOption(CMD_DELETE_BUCKET)) {
            if (StringUtils.isBlank(bucket)) {
                System.out.println("Bucket name required");
                return;
            }
            int deleted = S3Utils.deleteBucket(awsKey, awsSecret, bucket);
            System.out.println("Deleted objects: " + deleted);
            return;
        }
        if (cmd.hasOption(CMD_LIST_BUCKETS)) {
            for (String str : S3Utils.listBuckets(awsKey, awsSecret)) {
                System.out.println(str);
            }
            return;
        }
        if (cmd.hasOption(CMD_LIST_BUCKET)) {
            if (StringUtils.isBlank(bucket)) {
                System.out.println("Bucket name required");
                return;
            }
            for (String str : S3Utils.listObjects(awsKey, awsSecret, bucket)) {
                System.out.println(str);
            }
            return;
        }
        if (StringUtils.isBlank(password)) {
            System.out.println("Encryption password required");
            return;
        }
        char[] psw = password.toCharArray();
        DirSync ds = new DirSync(awsKey, awsSecret, bucket, bucketLocation, psw);
        ds.setExcludePatterns(parseSubargumenths(exclude));
        ds.setIncludePatterns(parseSubargumenths(include));
        if (cmd.hasOption(CMD_SUMMARY)) {
            ds.printStorageSummary();
            return;
        }
        if (StringUtils.isBlank(remoteDir)) {
            System.out.println("Remote directory name required");
            return;
        }
        if (cmd.hasOption(CMD_DELETE_DIR)) {
            ds.deleteFolder(remoteDir);
            return;
        }
        if (cmd.hasOption(CMD_LIST_DIR)) {
            Folder folder = ds.getFolder(remoteDir);
            if (folder == null) {
                System.out.println("No such folder found: " + remoteDir);
                return;
            }
            for (Map.Entry<String, FileInfo> entry : folder.getIndexData().entrySet()) {
                System.out.println(entry.getKey() + " ("
                        + FileUtils.byteCountToDisplaySize(entry.getValue().getLength()) + ")");
            }
            return;
        }
        if (cmd.hasOption(CMD_CLEANUP)) {
            ds.cleanUp();
            return;
        }
        if (cmd.hasOption(CMD_CHANGE_PASSWORD)) {
            String newPassword = cmd.getOptionValue(CMD_CHANGE_PASSWORD);
            if (StringUtils.isBlank(newPassword)) {
                System.out.println("new password required");
                return;
            }
            char[] chars = newPassword.toCharArray();
            ds.changePassword(chars);
            newPassword = null;
            Arrays.fill(chars, ' ');
            return;
        }
        if (StringUtils.isBlank(localDir)) {
            System.out.println(OPT_LOCAL_DIR + " argument required");
            return;
        }
        String direction = "";
        boolean up = false;
        boolean snapshot = false;
        if (StringUtils.isNotBlank(cmd.getOptionValue(CMD_UPDATE))) {
            direction = cmd.getOptionValue(CMD_UPDATE);
        } else if (StringUtils.isNotBlank(cmd.getOptionValue(CMD_SNAPSHOT))) {
            direction = cmd.getOptionValue(CMD_SNAPSHOT);
            snapshot = true;
        }
        if (StringUtils.isBlank(direction)) {
            System.out.println("Operation direction required");
            return;
        }
        up = StringUtils.equalsIgnoreCase(OPT_UP, direction);
        File baseDir = new File(localDir);
        if (!baseDir.exists() && !baseDir.mkdirs()) {
            System.out.println("Invalid local directory: " + baseDir.getAbsolutePath());
            return;
        }
        ds.syncFolder(baseDir, remoteDir, up, snapshot);

    } catch (DirSyncException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        printUsage(opts);

    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}