package org.ngbw.utils; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.regex.Pattern; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.ngbw.cipres.sdk.api.bean.ResourceResponse; import org.ngbw.cipres.sdk.api.v1.NoAuthorizationResource; import org.ngbw.sdk.Workbench; import org.ngbw.sdk.common.util.JsonUtils; import org.ngbw.sdk.common.util.StringUtils; import org.ngbw.sdk.database.Country; import org.ngbw.sdk.database.User; /** * This is the new version 2 utilizing Apache Commons CLI library. By utilizing the library, * it effectively eliminates "Array out of bound" exception when parsing command line options and parameters. * * @author Tony Chen * * @version 2.0.0 */ public class UserCountryIs { private static final String VERSION = "2.0.0"; public static void main ( String[] args ) throws Throwable { // Main program. Print all output (including errors) to stdout so that we can run with stderr // redirected to /dev/null to avoid seeing all the sdk logging. int status = 0; try { //logger.info(String.format("CMD: '%s'", toString(args, " "))); processOptions(args); } catch ( Throwable e ) { status = 1; System.out.println(e.getMessage()); } System.out.println(); System.exit(status); } private static synchronized Options buildOptions () throws Throwable { final Options options = new Options(); options.addOption(Option.builder("u").hasArg().argName("username").desc("The username.").build()); options.addOption(Option.builder("c").hasArg().argName("country").desc("Set the user's country.").build()); options.addOption(Option.builder("log").hasArg().argName("log4j").desc("Configure Log4j with this Log4j XML file (optional).").build()); options.addOption(Option.builder("query").hasArg().argName("ip-address").desc("Query user's country from the IP address.").build()); options.addOption(Option.builder("help").hasArg(false).desc("Print help information.").build()); options.addOption(Option.builder("list").hasArg(false).desc("List details of the user.").build()); options.addOption(Option.builder("version").hasArg(false).desc("Show version and description.").build()); return options; } private static synchronized void processOptions ( String[] args ) throws Throwable { Workbench.getInstance(); final Options options = buildOptions(); if (null == args || args.length == 0) { printHelp(options); } else { CommandLineParser parser = new DefaultParser(); CommandLine cmdln = parser.parse(options, args, Boolean.FALSE); if (cmdln.hasOption("log")) { loadLog4jConfigs(cmdln.getOptionValue("log")); } else { Logger.getRootLogger().setLevel(Level.OFF); } if (cmdln.hasOption("help")) { printHelp(options); } else if (cmdln.hasOption("version")) { printVersion(); } else if (cmdln.hasOption("query")) { query(cmdln.getOptionValue("query")); //queryAPI(cmdln.getOptionValue("query")); } else if (!cmdln.hasOption("u")) { throw new RuntimeException("You must specify a username with the option 'u'."); } else { final User user; final String value = cmdln.getOptionValue("u"); if (StringUtils.hasPattern(value, Pattern.compile("^[0-9]+$"))) { user = User.findUser(Long.parseLong(value)); } else { user = User.findUser(value); } if (null == user) { throw new RuntimeException("User '" + value + "' not found."); } if (cmdln.hasOption("c")) { setCountry(user, cmdln.getOptionValue("c")); } list(user); } } } private static synchronized void setCountry ( final User user, final String value ) throws Throwable { if (null != user) { final Country newCountry = Country.getCountry(value); final Country currCountry = Country.getCountry(user.getCountry()); if (null == newCountry) { System.out.println("Unknown country name: " + value); } else { System.out.println(); System.out.print( String.format( "Changing user's country from '%s' to '%s' ", currCountry.getName(), newCountry.getName())); for (int i = 0; i < 2; i++) { Thread.sleep(1000); System.out.print("."); } user.setCountry(newCountry.getAbbreviation()); user.save(); for (int i = 0; i < 3; i++) { Thread.sleep(1000); System.out.print("."); } Thread.sleep(1000); System.out.println(" done."); System.out.println(); System.out.println( String.format( "User's country changed from '%s' to '%s'", currCountry.getName(), newCountry.getName())); } } } /** * Queries user's country from the IP address. * *
* The IP is in IPv4 format. * * @param ipAddress the user's IP address * * @throws Throwable */ private static synchronized void query ( final String ipAddress ) throws Throwable { try { final String countryCode = Workbench.getInstance().getCountryCodeFromIP(ipAddress); if (null != countryCode) { System.out.println(); System.out.println("The country code of the IP " + ipAddress + " is " + countryCode + "."); } else { System.err.println("Unable to find country code of the IP: " + ipAddress); } } catch ( Throwable t ) { t.printStackTrace(); throw t; } } private static synchronized void queryAPI ( final String ipAddress ) throws Throwable { final String BASE_URI = "http://www.geoplugin.net/json.gp"; try { NoAuthorizationResource resource = new NoAuthorizationResource(); resource.addPath(BASE_URI); resource.addQueryParameters("ip", ipAddress); ResourceResponse response = new ResourceResponse(); resource.get(response); if (response.hasApiError()) { System.err.println(); System.err.println(response.getContent()); } else { //System.out.println(); //System.out.println(JsonUtils.format(response.getContent())); final String countryCode = JsonUtils.getFieldValueString(response.getContent(), "geoplugin_countryCode", null); if (null != countryCode) { System.out.println(); System.out.println("The country code of the IP " + ipAddress + " is " + countryCode + "."); } else { System.err.println("Unable to find country code of the IP: " + ipAddress); } } } catch ( Throwable t ) { t.printStackTrace(); throw t; } } private static synchronized void list ( final User user ) throws Throwable { if (null != user) { final Country country = Country.getCountry(user.getCountry()); System.out.println(); System.out.println("User: " + user.getUsername()); System.out.println(String.format("Country: %s (%s)", country.getName(), country.getAbbreviation())); } } private static synchronized void printHelp ( Options options ) { //printOldHelpMsg(); usage(options); } private static synchronized void printVersion () { System.out.println("CIPRES " + UserCountryIs.class.getSimpleName() + " " + VERSION); //System.out.println(VERSION_DESCRIPTION); } private static synchronized void usage ( Options options ) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("UserCountryIs", options, Boolean.TRUE); } public static synchronized void loadLog4jConfigs ( final String log4jConfigsFile ) throws IOException { try { if (null == log4jConfigsFile || log4jConfigsFile.trim().isEmpty()) { throw new IllegalArgumentException("Log4j configs filename cannot be empty or null. "); } else if (!Files.exists(Paths.get(log4jConfigsFile))) { throw new FileNotFoundException(String.format("Log4j properties file [%s] not found.", log4jConfigsFile)); } org.apache.log4j.xml.DOMConfigurator.configure(log4jConfigsFile); } catch ( IOException e ) { throw e; } } }