Author: sebb Date: Thu Jan 15 23:09:20 2015 New Revision: 1652307 URL: http://svn.apache.org/r1652307 Log: Simplify examples/Main - use predefined properties file to define aliases
Added: commons/proper/net/trunk/src/main/java/examples/examples.properties commons/proper/net/trunk/src/main/java/examples/telnet/Copy of TelnetClientScript.txt commons/proper/net/trunk/src/test/java/examples/ commons/proper/net/trunk/src/test/java/examples/MainTest.java Modified: commons/proper/net/trunk/src/changes/changes.xml commons/proper/net/trunk/src/main/java/examples/Main.java Modified: commons/proper/net/trunk/src/changes/changes.xml URL: http://svn.apache.org/viewvc/commons/proper/net/trunk/src/changes/changes.xml?rev=1652307&r1=1652306&r2=1652307&view=diff ============================================================================== --- commons/proper/net/trunk/src/changes/changes.xml [utf-8] (original) +++ commons/proper/net/trunk/src/changes/changes.xml [utf-8] Thu Jan 15 23:09:20 2015 @@ -68,6 +68,9 @@ This is mainly a bug-fix release. See fu IMAPExportMbox (example app) allows IMAP folders to be exported into an mbox file. This is the inverse of the IMAPImportMbox example added previously "> + <action type="update" dev="sebb"> + examples/Main now uses a property file to define aliases instead of scanning class files + </action> <action issue="NET-552" type="fix" dev="sebb" due-to="Quentin Devriendt"> SocketTimeoutException connecting a FTP server via an HTTP Proxy </action> Modified: commons/proper/net/trunk/src/main/java/examples/Main.java URL: http://svn.apache.org/viewvc/commons/proper/net/trunk/src/main/java/examples/Main.java?rev=1652307&r1=1652306&r2=1652307&view=diff ============================================================================== --- commons/proper/net/trunk/src/main/java/examples/Main.java (original) +++ commons/proper/net/trunk/src/main/java/examples/Main.java Thu Jan 15 23:09:20 2015 @@ -18,15 +18,12 @@ package examples; -import java.io.File; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.CodeSource; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; +import java.util.Collections; +import java.util.List; +import java.util.Properties; public class Main { @@ -43,46 +40,31 @@ public class Main { * @throws Exception */ public static void main(String[] args) throws Throwable { - CodeSource codeSource = Main.class.getProtectionDomain().getCodeSource(); - Map<String, String> map = new HashMap<String, String>(); - final boolean noArgsProvided = args.length == 0; - if ( codeSource != null) { - final String sourceFile = codeSource.getLocation().getFile(); - if (sourceFile.endsWith(".jar")) { - if (noArgsProvided) { - System.out.println("Usage: java -jar commons-net-examples-m.n.jar <exampleClass> <exampleClass parameters>"); - System.out.println("\nClasses found in the jar:"); - } - JarFile jf = new JarFile(sourceFile); - Enumeration<JarEntry> e = jf.entries(); - while (e.hasMoreElements()) { - JarEntry je = e.nextElement(); - String name = je.getName(); - processFileName(name, map, noArgsProvided); - } - jf.close(); + final Properties fp = new Properties(); + fp.load(Main.class.getResourceAsStream("examples.properties")); + if (args.length == 0) { + if (Thread.currentThread().getStackTrace().length > 2) { // called by Maven + System.out.println("Usage: mvn -q exec:java -Dexec.arguments=<alias or exampleClass>,<exampleClass parameters> (comma-separated, no spaces)"); + System.out.println("Or : mvn -q exec:java -Dexec.args=\"<alias or exampleClass> <exampleClass parameters>\" (space separated)"); } else { - if (noArgsProvided) { - System.out.println("Usage: mvn -q exec:java -Dexec.arguments=<exampleClass>,<exampleClass parameters>"); - System.out.println("\nClasses found in the jar:"); - } - File examples = new File(sourceFile, "examples"); - if (examples.exists()) { - scanForClasses(sourceFile.length(), examples, map, noArgsProvided); + if (fromJar()) { + System.out.println("Usage: java -jar commons-net-examples-m.n.jar <alias or exampleClass> <exampleClass parameters>"); + } else { + System.out.println("Usage: java -cp target/classes examples/Main <alias or exampleClass> <exampleClass parameters>"); } } - } else { - if (noArgsProvided) { - System.out.println("Usage: java -jar commons-net-examples-m.n.jar <exampleClass> <exampleClass parameters>"); + System.out.println("\nAliases and their classes:"); + @SuppressWarnings("unchecked") // property names are Strings + List<String> l = (List<String>) Collections.list(fp.propertyNames()); + Collections.sort(l); + for(String s : l) { + System.out.printf("%-25s %s%n",s,fp.getProperty(s)); } - } - - if (noArgsProvided) { return; } String shortName = args[0]; - String fullName = map.get(shortName); + String fullName = fp.getProperty(shortName); if (fullName == null) { fullName = shortName; } @@ -107,36 +89,11 @@ public class Main { } } - private static void scanForClasses(int rootLength, File current, Map<String, String> map, boolean printAlias) { - for(File file : current.listFiles()) { - if (file.isDirectory()) { - scanForClasses(rootLength, file, map, printAlias); - } else { - - processFileName(file.getPath().substring(rootLength), map, printAlias); - - } - } - - } - - private static void processFileName(String name, Map<String, String> map, boolean printAlias) { - if (!name.endsWith(".class") - || name.contains("$") // subclasses - // TODO use reflection to eliminate non-main classes? - // however that would entail loading the class. - || name.equals("examples/nntp/NNTPUtils.class") // no main class - || name.equals("examples/util/IOUtil.class") // no main class - || name.equals("examples/mail/IMAPUtils.class") // no main class - || name.equals("examples/Main.class")) { // ourself - return; - } - name = name.replace(".class", ""); - final int lastSep = name.lastIndexOf('/'); - final String alias = name.substring(lastSep+1); - if (printAlias) { - System.out.printf("%-25s %s%n",alias,name); + private static boolean fromJar() { + final CodeSource codeSource = Main.class.getProtectionDomain().getCodeSource(); + if ( codeSource != null) { + return codeSource.getLocation().getFile().endsWith(".jar"); } - map.put(alias, name); + return false; // No idea if this can happen } } Added: commons/proper/net/trunk/src/main/java/examples/examples.properties URL: http://svn.apache.org/viewvc/commons/proper/net/trunk/src/main/java/examples/examples.properties?rev=1652307&view=auto ============================================================================== --- commons/proper/net/trunk/src/main/java/examples/examples.properties (added) +++ commons/proper/net/trunk/src/main/java/examples/examples.properties Thu Jan 15 23:09:20 2015 @@ -0,0 +1,51 @@ +################################################################################ +# Apache Commons Net Examples Property file +################################################################################ + +## Licensed to the Apache Software Foundation (ASF) under one or more +## contributor license agreements. See the NOTICE file distributed with +## this work for additional information regarding copyright ownership. +## The ASF licenses this file to You under the Apache License, Version 2.0 +## (the "License"); you may not use this file except in compliance with +## the License. You may obtain a copy of the License at +## +## http://www.apache.org/licenses/LICENSE-2.0 +## +## Unless required by applicable law or agreed to in writing, software +## distributed under the License is distributed on an "AS IS" BASIS, +## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +## See the License for the specific language governing permissions and +## limitations under the License. + +# List of aliases for example class names. +# Note that the "/" separators are converted to "." + +# alias full class name +SubnetUtilsExample examples/cidr/SubnetUtilsExample +FTPClientExample examples/ftp/FTPClientExample +ServerToServerFTP examples/ftp/ServerToServerFTP +TFTPExample examples/ftp/TFTPExample +IMAPExportMbox examples/mail/IMAPExportMbox +IMAPImportMbox examples/mail/IMAPImportMbox +IMAPMail examples/mail/IMAPMail +POP3Mail examples/mail/POP3Mail +SMTPMail examples/mail/SMTPMail +ArticleReader examples/nntp/ArticleReader +ExtendedNNTPOps examples/nntp/ExtendedNNTPOps +ListNewsgroups examples/nntp/ListNewsgroups +MessageThreading examples/nntp/MessageThreading +PostMessage examples/nntp/PostMessage +NTPClient examples/ntp/NTPClient +SimpleNTPServer examples/ntp/SimpleNTPServer +TimeClient examples/ntp/TimeClient +TelnetClientExample examples/telnet/TelnetClientExample +WeatherTelnet examples/telnet/WeatherTelnet +chargen examples/unix/chargen +daytime examples/unix/daytime +echo examples/unix/echo +finger examples/unix/finger +fwhois examples/unix/fwhois +rdate examples/unix/rdate +rexec examples/unix/rexec +rlogin examples/unix/rlogin +rshell examples/unix/rshell Added: commons/proper/net/trunk/src/main/java/examples/telnet/Copy of TelnetClientScript.txt URL: http://svn.apache.org/viewvc/commons/proper/net/trunk/src/main/java/examples/telnet/Copy%20of%20TelnetClientScript.txt?rev=1652307&view=auto ============================================================================== --- commons/proper/net/trunk/src/main/java/examples/telnet/Copy of TelnetClientScript.txt (added) +++ commons/proper/net/trunk/src/main/java/examples/telnet/Copy of TelnetClientScript.txt Thu Jan 15 23:09:20 2015 @@ -0,0 +1,75 @@ +package examples.telnet; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.SocketTimeoutException; + +import org.apache.commons.net.telnet.TelnetClient; + +public class TelnetClientScript { + + private final InputStream in; + private final OutputStream out; + private final TelnetClient telnet = new TelnetClient(); + TelnetClientScript(String host, int port) throws IOException { + telnet.connect(host, port); + telnet.setSoTimeout(1000); + this.in=telnet.getInputStream(); + this.out=telnet.getOutputStream(); + } + + void login() { + + } + void write(String command) throws IOException { + out.write(command.getBytes()); + out.write('\r'); + out.write('\n'); + } + + void readResponse() { + int i; + try { + while((i=in.read()) != -1){ + System.out.print((char) i); + } + } catch (SocketTimeoutException e) { + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + public static void main(String [] args) throws IOException{ + if(args.length < 1) + { + System.err.println("Usage: TelnetClientScriptExample <remote-ip> [<remote-port>]"); + System.exit(1); + } + + String remoteip = args[0]; + + int remoteport; + + if (args.length > 1) + { + remoteport = (new Integer(args[1])).intValue(); + } + else + { + remoteport = 23; + } + + TelnetClientScript script = new TelnetClientScript(remoteip, remoteport); + + script.login(); + script.write("INFORMATION"); + script.readResponse(); + System.out.println("--------------------"); + + script.write("INFORMATION"); + script.readResponse(); + System.out.println("--------------------"); + } + +} Added: commons/proper/net/trunk/src/test/java/examples/MainTest.java URL: http://svn.apache.org/viewvc/commons/proper/net/trunk/src/test/java/examples/MainTest.java?rev=1652307&view=auto ============================================================================== --- commons/proper/net/trunk/src/test/java/examples/MainTest.java (added) +++ commons/proper/net/trunk/src/test/java/examples/MainTest.java Thu Jan 15 23:09:20 2015 @@ -0,0 +1,102 @@ +package examples; + +import static org.junit.Assert.fail; + +import java.io.File; +import java.io.IOException; +import java.security.CodeSource; +import java.util.Enumeration; +import java.util.Properties; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +import org.junit.Test; + +public class MainTest { + + @Test + public void checkExamplesPropertiesIsComplete() throws Exception { + Properties cp = scanClasses(); + Properties fp = new Properties(); + fp.load(this.getClass().getResourceAsStream("examples.properties")); + for(String c : cp.stringPropertyNames()) { + String fv = fp.getProperty(c); + final String cv = cp.getProperty(c); + if (fv == null) { + System.out.printf("%-25s %s - missing from examples.properties%n",c,cv); + } else if (!fv.equals(cv)) { + System.out.printf("%-25s %s - expected value %s %n",c,fv,cv); + } + } + } + + private Properties scanClasses() throws IOException { + CodeSource codeSource = Main.class.getProtectionDomain().getCodeSource(); + final String sourceFile = codeSource.getLocation().getFile(); + Properties p = new Properties(); + if (sourceFile.endsWith(".jar")) { + JarFile jf = new JarFile(sourceFile); + Enumeration<JarEntry> e = jf.entries(); + while (e.hasMoreElements()) { + JarEntry je = e.nextElement(); + String name = je.getName(); + processFileName(name, p); + } + jf.close(); + } else { + File examples = new File(sourceFile, "examples"); // must match top level examples package name + if (examples.exists()) { + scanForClasses(sourceFile.length(), examples, p); + } else { + fail("Could not find examples classes"); + } + } + return p; + } + + private static void scanForClasses(int rootLength, File current, Properties p) { + for(File file : current.listFiles()) { + if (file.isDirectory()) { + scanForClasses(rootLength, file, p); + } else { + processFileName(file.getPath().substring(rootLength), p); + } + } + } + + private static void processFileName(String name, Properties p) { + if (!name.endsWith(".class") + || name.contains("$") // subclasses + || name.equals("examples/Main.class") // the initial class, don't want to add that + || !hasMainMethod(name) + ) { + return; + } + name = name.replace(".class", ""); + final int lastSep = name.lastIndexOf('/'); + final String alias = name.substring(lastSep+1); + if (p.containsKey(alias)) { + System.out.printf("Duplicate alias: %-25s %s %s %n",alias,name,p.getProperty(alias)); + } else { + p.setProperty(alias, name); + } + } + + private static boolean hasMainMethod(String name) { + name = name.replace(".class", ""); + name = name.replace("/", "."); + try { + Class<?> clazz = Class.forName(name, false, MainTest.class.getClassLoader()); + clazz.getMethod("main", new Class[]{String[].class}); + return true; + } catch (ClassNotFoundException e) { + System.out.println("Cannot find " + name); + return false; + } catch (NoSuchMethodException e) { + return false; + } catch (SecurityException e) { + e.printStackTrace(); + } + return true; + } +}