Path: blob/master/test/jdk/com/sun/jndi/dns/lib/DNSTestUtils.java
41155 views
/*1* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import javax.naming.Context;24import javax.naming.NamingException;25import javax.naming.directory.Attributes;26import java.io.PrintStream;27import java.nio.file.Files;28import java.nio.file.Path;29import java.nio.file.Paths;30import java.util.Hashtable;3132/**33* This is utility class for DNS test, it contains many helper methods to34* support test construction.35*36* For basic test sequence see TestBase and DNSTestBase.37*/38public class DNSTestUtils {39public static final String TEST_DNS_SERVER_THREAD = "test.dns.server.thread";40public static final String TEST_DNS_ROOT_URL = "test.dns.root.url";41public static final int HOSTS_LOOKUP_MAX_DEPTH = 3;4243protected static boolean debug = true;4445/**46* Check that attributes contains the mandatory attributes and the right47* objectclass attribute.48*49* @param attrs given attributes to verify50* @param mandatory given mandatory for verification51* @param optional given optional for verification52* @return <tt>true</tt> if check ok53*/54public static boolean checkSchema(Attributes attrs, String[] mandatory,55String[] optional) {56// Check mandatory attributes57for (String mandatoryAttr : mandatory) {58if (attrs.get(mandatoryAttr) == null) {59debug("missing mandatory attribute: " + mandatoryAttr);60return false;61}62}6364// Check optional attributes65int optMissing = 0;66for (String optionalAttr : optional) {67if (attrs.get(optionalAttr) == null) {68debug("warning: missing optional attribute: " + optionalAttr);69++optMissing;70}71}7273if (attrs.size() > (mandatory.length + (optional.length74- optMissing))) {75debug("too many attributes: " + attrs);76return false;77}7879return true;80}8182/**83* Process command line arguments and init env.84* This method will prepare default environments which to be used to initial85* DirContext.86*87* @param localServer <tt>true</tt> if this test will run against with local88* server against dump message playback89* @param testname test case name to identify playback file90* @param args additional arguments for env preparation91* @return prepared env which will be used later to initial DirContext92*/93public static Hashtable<Object, Object> initEnv(boolean localServer,94String testname, String[] args) {9596Hashtable<Object, Object> env = new Hashtable<>();9798// set some default parameters if no additional specified99env.put("DNS_DOMAIN", "domain1.com.");100env.put("FOREIGN_DOMAIN", "Central.Sun.COM.");101env.put("FOREIGN_LEAF", "sunweb");102103// set defaults for some JNDI properties104env.put(Context.INITIAL_CONTEXT_FACTORY,105"com.sun.jndi.dns.DnsContextFactory");106107boolean traceEnable = false;108boolean loopPlayback = false;109for (String arg : args) {110if (arg.startsWith("-D")) {111extractProperty(arg.substring(2), env);112} else if (arg.equalsIgnoreCase("-trace")) {113traceEnable = true;114} else if (arg.equalsIgnoreCase("-loop")) {115loopPlayback = true;116}117}118119debug = Boolean.valueOf(System.getProperty("debug", "true"));120121// override testname here if it's been specified122String newTestName = (String) env.get("testname");123if (newTestName != null && !newTestName.isEmpty()) {124testname = newTestName;125}126127if (env.get("DNS_SERVER") != null) {128String port = (String) env.get("DNS_PORT");129String portSuffix = (port == null) ? "" : ":" + port;130String url = "dns://" + env.get("DNS_SERVER") + portSuffix;131env.put(Context.PROVIDER_URL, url);132env.put(Context.PROVIDER_URL, url + "/" + env.get("DNS_DOMAIN"));133}134135Thread inst = null;136if (traceEnable) {137// if trace is enabled, create DNSTracer to dump those message138inst = createDNSTracer(testname, env);139} else {140if (localServer) {141// if use local server, create local DNSServer for playback142inst = createDNSServer(testname, loopPlayback);143} else {144// for tests which run against remote server145// or no server required146debug("Skip local DNS Server creation ");147}148}149150if (inst != null) {151inst.start();152env.put(TEST_DNS_SERVER_THREAD, inst);153String url = "dns://localhost:" + ((Server) inst).getPort();154155env.put(TEST_DNS_ROOT_URL, url);156env.put(Context.PROVIDER_URL, url + "/" + env.get("DNS_DOMAIN"));157}158159return env;160}161162/**163* Clean-up the given directory context.164*165* @param ctx given context object166*/167public static void cleanup(Context ctx) {168if (ctx != null) {169try {170ctx.close();171} catch (NamingException e) {172// ignore173}174}175}176177private static void extractProperty(String propString,178Hashtable<Object, Object> env) {179int index;180181if ((index = propString.indexOf('=')) > 0) {182env.put(propString.substring(0, index),183propString.substring(index + 1));184} else {185throw new RuntimeException(186"Failed to extract test args property from " + propString);187}188}189190/**191* Return new created DNS tracer.192*193* @param testname test case name to identify playback file194* @param env given env for initialization195* @return created DNS tracer196* @see DNSTracer197*/198public static DNSTracer createDNSTracer(String testname,199Hashtable<Object, Object> env) {200try {201PrintStream outStream = new PrintStream(getCaptureFile(testname));202return new DNSTracer(outStream, (String) env.get("DNS_SERVER"),203Integer.parseInt((String) env.get("DNS_PORT")));204} catch (Exception e) {205throw new RuntimeException(206"Error: failed to create DNSTracer : " + e.getMessage(), e);207}208}209210/**211* Return new created local DNS Server.212*213* @param testname test case name to identify playback file214* @param loop <tt>true</tt> if DNS server required playback message in loop215* @return created local DNS Server216* @see DNSServer217*/218public static DNSServer createDNSServer(String testname, boolean loop) {219String path = getCaptureFile(testname);220if (Files.exists(Paths.get(path))) {221try {222return new DNSServer(path, loop);223} catch (Exception e) {224throw new RuntimeException(225"Error: failed to create DNSServer : " + e.getMessage(),226e);227}228} else {229throw new RuntimeException(230"Error: failed to create DNSServer, not found dns "231+ "cache file " + path);232}233}234235/**236* Return dns message capture file path.237*238* @param testname test case name to identify playback file239* @return capture file path240*/241public static String getCaptureFile(String testname) {242return Paths.get(System.getProperty("test.src"))243.resolve(testname + ".dns").toString();244}245246/**247* Enable hosts file.248*249* @param hostsFile given hosts file250*/251public static void enableHostsFile(String hostsFile) {252System.out.println("Enable jdk.net.hosts.file = " + hostsFile);253System.setProperty("jdk.net.hosts.file", hostsFile);254}255256/**257* Enable hosts file by given searching depth.258*259* @param depth given depth for searching hosts file260*/261public static void enableHostsFile(int depth) {262Path path = Paths.get(System.getProperty("test.src", "."))263.toAbsolutePath();264for (int i = depth; i >= 0; i--) {265Path filePath = path.resolve("hosts");266if (Files.exists(filePath) && !Files.isDirectory(filePath)) {267enableHostsFile(filePath.toString());268break;269}270271path = path.getParent();272if (path == null) {273break;274}275}276}277278/**279* Print given object if debug enabled.280*281* @param object given object to print282*/283public static void debug(Object object) {284if (debug) {285System.out.println(object);286}287}288289/**290* Verify attributes contains the mandatory attributes and the right291* objectclass attribute, will throw RuntimeException if verify failed.292*293* @param attrs given attributes to verify294* @param mandatory given mandatory for verification295* @param optional given optional for verification296*/297public static void verifySchema(Attributes attrs, String[] mandatory,298String[] optional) {299debug(attrs);300if (!checkSchema(attrs, mandatory, optional)) {301throw new RuntimeException("Check schema failed.");302}303}304305/**306* Return dns root url.307*308* @param env given env309* @return dns root url310*/311public static String getRootUrl(Hashtable<Object, Object> env) {312return (String) env.get(TEST_DNS_ROOT_URL);313}314315/**316* Assemble a fully-qualified domain name from the base component and the317* domain name.318*319* @param base given base component320* @param env given env321* @param primary <tt>true</tt> if primary domain322* @return assembled fully-qualified domain name323*/324public static String buildFqdn(String base, Hashtable<Object, Object> env,325boolean primary) {326String domain = (String) (primary ?327env.get("DNS_DOMAIN") :328env.get("FOREIGN_DOMAIN"));329330return base + "." + domain;331}332}333334335