From 0c91d185c6b169cb4faa10ba55f9573a538a1d70 Mon Sep 17 00:00:00 2001 From: Ronald Roskens Date: Fri, 21 Feb 2014 23:08:13 -0600 Subject: [PATCH 1/1] first pass at removing jakarta-regexp --- opennms-provision/opennms-detector-ssh/pom.xml | 4 - .../provision/detector/ssh/client/SshClient.java | 48 ++++----- opennms-services/pom.xml | 5 - .../org/opennms/netmgt/capsd/plugins/GpPlugin.java | 34 +++--- .../opennms/netmgt/capsd/plugins/NrpePlugin.java | 82 +++++++------- .../opennms/netmgt/capsd/plugins/SmtpPlugin.java | 22 ++-- .../opennms/netmgt/capsd/plugins/TcpPlugin.java | 25 ++--- .../netmgt/poller/monitors/SmtpMonitor.java | 46 ++++---- .../opennms/netmgt/poller/monitors/SshMonitor.java | 32 +++--- opennms-web-dependencies/pom.xml | 4 - .../svclayer/support/DefaultRrdGraphService.java | 119 ++++++++++----------- .../admin/notification/noticeWizard/buildRule.jsp | 33 +++--- pom.xml | 6 -- .../org/opennms/netmgt/protocols/xmp/XmpUtil.java | 60 +++++------ .../netmgt/protocols/xmp/capsd/XmpPlugin.java | 56 +++++----- .../netmgt/protocols/xmp/monitor/XmpMonitor.java | 58 +++++----- 16 files changed, 298 insertions(+), 336 deletions(-) diff --git a/opennms-provision/opennms-detector-ssh/pom.xml b/opennms-provision/opennms-detector-ssh/pom.xml index 4e64ff9..31356b7 100644 --- a/opennms-provision/opennms-detector-ssh/pom.xml +++ b/opennms-provision/opennms-detector-ssh/pom.xml @@ -33,10 +33,6 @@ opennms-provision-api - jakarta-regexp - jakarta-regexp - - org.opennms opennms-model diff --git a/opennms-provision/opennms-detector-ssh/src/main/java/org/opennms/netmgt/provision/detector/ssh/client/SshClient.java b/opennms-provision/opennms-detector-ssh/src/main/java/org/opennms/netmgt/provision/detector/ssh/client/SshClient.java index b99b2b9..03c895e 100644 --- a/opennms-provision/opennms-detector-ssh/src/main/java/org/opennms/netmgt/provision/detector/ssh/client/SshClient.java +++ b/opennms-provision/opennms-detector-ssh/src/main/java/org/opennms/netmgt/provision/detector/ssh/client/SshClient.java @@ -32,8 +32,8 @@ import java.io.IOException; import java.net.InetAddress; import java.util.Collections; import java.util.Map; +import java.util.regex.Pattern; -import org.apache.regexp.RE; import org.opennms.core.utils.TimeoutTracker; import org.opennms.netmgt.model.PollStatus; import org.opennms.netmgt.provision.detector.ssh.request.NullRequest; @@ -51,47 +51,47 @@ import org.slf4j.LoggerFactory; * @version $Id: $ */ public class SshClient implements Client { - + private static final Logger LOG = LoggerFactory.getLogger(SshClient.class); private boolean m_isAvailable = false; - + private String m_banner = null; private String m_match = null; private String m_clientBanner = Ssh.DEFAULT_CLIENT_BANNER; - + public static final int DEFAULT_RETRY = 0; - + /** *

close

*/ @Override public void close() { - + } /** {@inheritDoc} */ @Override - public void connect(InetAddress address, int port, int timeout) throws IOException, Exception { + public void connect(final InetAddress address, final int port, final int timeout) throws Exception { Map emptyMap = Collections.emptyMap(); TimeoutTracker tracker = new TimeoutTracker(emptyMap, SshClient.DEFAULT_RETRY, timeout); - + String banner = m_banner; String match = m_match; String clientBanner = m_clientBanner; PollStatus ps = PollStatus.unavailable(); - + Ssh ssh = new Ssh(address, port, tracker.getConnectionTimeout()); ssh.setClientBanner(clientBanner); - - RE regex = null; + + Pattern regex = null; if (match == null && (banner == null || banner.equals("*"))) { regex = null; } else if (match != null) { - regex = new RE(match); + regex = Pattern.compile(match); } else if (banner != null) { - regex = new RE(banner); + regex = Pattern.compile(banner); } - + for (tracker.reset(); tracker.shouldRetry() && !ps.isAvailable(); tracker.nextAttempt()) { try { ps = ssh.poll(tracker); @@ -99,20 +99,20 @@ public class SshClient implements Client { LOG.error("Caught InsufficientParametersException: {}", e.getMessage(), e); break; } - + } - + // If banner matching string is null or wildcard ("*") then we // only need to test connectivity and we've got that! - + if (regex != null && ps.isAvailable()) { String response = ssh.getServerBanner(); - + if (response == null) { ps = PollStatus.unavailable("server closed connection before banner was recieved."); } - - if (!regex.match(response)) { + + if (!regex.matcher(response).find()) { // Got a response but it didn't match... no need to attempt // retries LOG.debug("isServer: NON-matching response='{}'", response); @@ -122,7 +122,7 @@ public class SshClient implements Client { } } PollStatus result = ps; - + m_isAvailable = result.isAvailable(); } @@ -152,7 +152,7 @@ public class SshClient implements Client { public SshResponse sendRequest(NullRequest request) throws IOException, Exception { return null; } - + /** *

setBanner

* @@ -161,7 +161,7 @@ public class SshClient implements Client { public void setBanner(String banner) { m_banner = banner; } - + /** *

setMatch

* @@ -170,7 +170,7 @@ public class SshClient implements Client { public void setMatch(String match) { m_match = match; } - + /** *

setClientBanner

* diff --git a/opennms-services/pom.xml b/opennms-services/pom.xml index 4b1dc0d..e522c87 100644 --- a/opennms-services/pom.xml +++ b/opennms-services/pom.xml @@ -274,11 +274,6 @@ compile - jakarta-regexp - jakarta-regexp - compile - - org.easymock easymock test diff --git a/opennms-services/src/main/java/org/opennms/netmgt/capsd/plugins/GpPlugin.java b/opennms-services/src/main/java/org/opennms/netmgt/capsd/plugins/GpPlugin.java index 669d008..364902a 100644 --- a/opennms-services/src/main/java/org/opennms/netmgt/capsd/plugins/GpPlugin.java +++ b/opennms-services/src/main/java/org/opennms/netmgt/capsd/plugins/GpPlugin.java @@ -32,9 +32,9 @@ import java.io.IOException; import java.io.InterruptedIOException; import java.net.InetAddress; import java.util.Map; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; -import org.apache.regexp.RE; -import org.apache.regexp.RESyntaxException; import org.opennms.core.utils.ExecRunner; import org.opennms.core.utils.InetAddressUtils; import org.opennms.core.utils.ParameterMap; @@ -82,7 +82,7 @@ public final class GpPlugin extends AbstractPlugin { * generate a banner line which contains the text from the banner or match * argument. *

- * + * * @param host * The host to pass to the script * @param retry @@ -100,12 +100,12 @@ public final class GpPlugin extends AbstractPlugin { * The option string passed to the exec for the IP address (hostname) * @param toption * The option string passed to the exec for the timeout - * + * * @return True if a connection is established with the script and the * banner line returned by the script matches the regular expression * regex. */ - private boolean isServer(InetAddress host, int retry, int timeout, String script, String args, RE regex, StringBuffer bannerResult, String hoption, String toption) { + private boolean isServer(InetAddress host, int retry, int timeout, String script, String args, Pattern regex, StringBuffer bannerResult, String hoption, String toption) { boolean isAServer = false; @@ -116,10 +116,11 @@ public final class GpPlugin extends AbstractPlugin { int exitStatus = 100; ExecRunner er = new ExecRunner(); er.setMaxRunTimeSecs(timeout); - if (args == null) + if (args == null) { exitStatus = er.exec(script + " " + hoption + " " + InetAddressUtils.str(host) + " " + toption + " " + timeout); - else + } else { exitStatus = er.exec(script + " " + hoption + " " + InetAddressUtils.str(host) + " " + toption + " " + timeout + " " + args); + } if (exitStatus != 0) { LOG.debug("{} failed with exit code {}", script, exitStatus); isAServer = false; @@ -133,16 +134,19 @@ public final class GpPlugin extends AbstractPlugin { String error = ""; response = er.getOutString(); error = er.getErrString(); - if (response.equals("")) + if (response.equals("")) { LOG.debug("{} returned no output", script); - if (!error.equals("")) + } + if (!error.equals("")) { LOG.debug("{} error = {}", script, error); - if (regex == null || regex.match(response)) { + } + if (regex == null || regex.matcher(response).find()) { LOG.debug("isServer: matching response = {}", response); isAServer = true; - if (bannerResult != null) + if (bannerResult != null) { bannerResult.append(response); + } } else { isAServer = false; @@ -241,14 +245,14 @@ public final class GpPlugin extends AbstractPlugin { try { StringBuffer bannerResult = null; - RE regex = null; + Pattern regex = null; if (match == null && (banner == null || banner.equals("*"))) { regex = null; } else if (match != null) { - regex = new RE(match); + regex = Pattern.compile(match); bannerResult = new StringBuffer(); } else if (banner != null) { - regex = new RE(banner); + regex = Pattern.compile(banner); bannerResult = new StringBuffer(); } @@ -259,7 +263,7 @@ public final class GpPlugin extends AbstractPlugin { } return result; - } catch (RESyntaxException e) { + } catch (PatternSyntaxException e) { throw new java.lang.reflect.UndeclaredThrowableException(e); } } diff --git a/opennms-services/src/main/java/org/opennms/netmgt/capsd/plugins/NrpePlugin.java b/opennms-services/src/main/java/org/opennms/netmgt/capsd/plugins/NrpePlugin.java index f61665e..3bf1261 100644 --- a/opennms-services/src/main/java/org/opennms/netmgt/capsd/plugins/NrpePlugin.java +++ b/opennms-services/src/main/java/org/opennms/netmgt/capsd/plugins/NrpePlugin.java @@ -38,9 +38,9 @@ import java.net.InetSocketAddress; import java.net.NoRouteToHostException; import java.net.Socket; import java.util.Map; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; -import org.apache.regexp.RE; -import org.apache.regexp.RESyntaxException; import org.opennms.core.utils.InetAddressUtils; import org.opennms.core.utils.ParameterMap; import org.opennms.core.utils.SocketUtils; @@ -63,8 +63,8 @@ import org.slf4j.LoggerFactory; * @author OpenNMS */ public final class NrpePlugin extends AbstractPlugin { - - + + private static final Logger LOG = LoggerFactory.getLogger(NrpePlugin.class); /** @@ -81,17 +81,17 @@ public final class NrpePlugin extends AbstractPlugin { * Default timeout (in milliseconds) for TCP requests */ private final static int DEFAULT_TIMEOUT = 5000; // in milliseconds - + /** * Default whether to use SSL */ private final static boolean DEFAULT_USE_SSL = true; - + /** * List of cipher suites to use when talking SSL to NRPE, which uses anonymous DH */ private static final String[] ADH_CIPHER_SUITES = new String[] {"TLS_DH_anon_WITH_AES_128_CBC_SHA"}; - + /** * Whether to use SSL for this instantiation */ @@ -105,7 +105,7 @@ public final class NrpePlugin extends AbstractPlugin { * caller. In order to return true the remote host must generate a banner * line which contains the text from the bannerMatch argument. *

- * + * * @param host * The remote host to connect to. * @param port @@ -113,11 +113,11 @@ public final class NrpePlugin extends AbstractPlugin { * @param bannerResult * Banner line generated by the remote host must contain this * text. - * + * * @return True if a connection is established with the host and the banner * line contains the bannerMatch text. */ - private boolean isServer(InetAddress host, int port, String command, int padding, int retries, int timeout, RE regex, StringBuffer bannerResult) { + private boolean isServer(InetAddress host, int port, String command, int padding, int retries, int timeout, Pattern regex, StringBuffer bannerResult) { boolean isAServer = false; for (int attempts = 0; attempts <= retries && !isAServer; attempts++) { Socket socket = null; @@ -129,33 +129,32 @@ public final class NrpePlugin extends AbstractPlugin { socket = wrapSocket(socket, host.toString(), port); socket.setSoTimeout(timeout); LOG.debug("NrpePlugin: connected to host: {} on port: {}", host, port); - - NrpePacket p = new NrpePacket(NrpePacket.QUERY_PACKET, (short) 0, - command); - byte[] b = p.buildPacket(padding); - OutputStream o = socket.getOutputStream(); - o.write(b); - NrpePacket response = NrpePacket.receivePacket(socket.getInputStream(), padding); - if (response.getResultCode() == 0) { + NrpePacket p = new NrpePacket(NrpePacket.QUERY_PACKET, (short) 0, command); + byte[] b = p.buildPacket(padding); + OutputStream o = socket.getOutputStream(); + o.write(b); + + NrpePacket response = NrpePacket.receivePacket(socket.getInputStream(), padding); + if (response.getResultCode() == 0) { isAServer = true; - } else if (response.getResultCode() <= 2) { - String response_msg = response.getBuffer(); - RE r = new RE("OK|WARNING|CRITICAL"); - if (r.match(response_msg)) { - isAServer = true; - } else { - LOG.info("received 1-2 return code, {}, with message: {}", response.getResultCode(), response.getBuffer()); - isAServer = false; - break; - } - } else { - LOG.info("received 3+ return code, {}, with message: {}", response.getResultCode(), response.getBuffer()); + } else if (response.getResultCode() <= 2) { + String response_msg = response.getBuffer(); + Pattern r = Pattern.compile("OK|WARNING|CRITICAL"); + if (r.matcher(response_msg).find()) { + isAServer = true; + } else { + LOG.info("received 1-2 return code, {}, with message: {}", response.getResultCode(), response.getBuffer()); isAServer = false; - break; + break; + } + } else { + LOG.info("received 3+ return code, {}, with message: {}", response.getResultCode(), response.getBuffer()); + isAServer = false; + break; } - /* + /* // If banner matching string is null or wildcard ("*") then we // only need to test connectivity and we've got that! // @@ -214,8 +213,9 @@ public final class NrpePlugin extends AbstractPlugin { LOG.warn("NrpePlugin: An undeclared throwable exception was caught connecting to host {} on port {}", InetAddressUtils.str(host), port, t); } finally { try { - if (socket != null) + if (socket != null) { socket.close(); + } } catch (IOException e) { } } @@ -271,9 +271,9 @@ public final class NrpePlugin extends AbstractPlugin { String command = null; if (qualifiers != null) { - command = ParameterMap.getKeyedString(qualifiers, "command", NrpePacket.HELLO_COMMAND); - port = ParameterMap.getKeyedInteger(qualifiers, "port", CheckNrpe.DEFAULT_PORT); - padding = ParameterMap.getKeyedInteger(qualifiers, "padding", NrpePacket.DEFAULT_PADDING); + command = ParameterMap.getKeyedString(qualifiers, "command", NrpePacket.HELLO_COMMAND); + port = ParameterMap.getKeyedInteger(qualifiers, "port", CheckNrpe.DEFAULT_PORT); + padding = ParameterMap.getKeyedInteger(qualifiers, "padding", NrpePacket.DEFAULT_PADDING); retries = ParameterMap.getKeyedInteger(qualifiers, "retry", DEFAULT_RETRY); timeout = ParameterMap.getKeyedInteger(qualifiers, "timeout", DEFAULT_TIMEOUT); banner = ParameterMap.getKeyedString(qualifiers, "banner", null); @@ -283,14 +283,14 @@ public final class NrpePlugin extends AbstractPlugin { try { StringBuffer bannerResult = null; - RE regex = null; + Pattern regex = null; if (match == null && (banner == null || banner.equals("*"))) { regex = null; } else if (match != null) { - regex = new RE(match); + regex = Pattern.compile(match); bannerResult = new StringBuffer(); } else if (banner != null) { - regex = new RE(banner); + regex = Pattern.compile(banner); bannerResult = new StringBuffer(); } @@ -301,11 +301,11 @@ public final class NrpePlugin extends AbstractPlugin { } return result; - } catch (RESyntaxException e) { + } catch (PatternSyntaxException e) { throw new java.lang.reflect.UndeclaredThrowableException(e); } } - + /** *

wrapSocket

* diff --git a/opennms-services/src/main/java/org/opennms/netmgt/capsd/plugins/SmtpPlugin.java b/opennms-services/src/main/java/org/opennms/netmgt/capsd/plugins/SmtpPlugin.java index ef5b60b..f35bf70 100644 --- a/opennms-services/src/main/java/org/opennms/netmgt/capsd/plugins/SmtpPlugin.java +++ b/opennms-services/src/main/java/org/opennms/netmgt/capsd/plugins/SmtpPlugin.java @@ -40,9 +40,9 @@ import java.net.NoRouteToHostException; import java.net.Socket; import java.util.Map; import java.util.StringTokenizer; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; -import org.apache.regexp.RE; -import org.apache.regexp.RESyntaxException; import org.opennms.core.utils.InetAddressUtils; import org.opennms.core.utils.ParameterMap; import org.slf4j.Logger; @@ -68,9 +68,9 @@ public final class SmtpPlugin extends AbstractPlugin { * The regular expression test used to determine if the reply is a multi * line reply. A multi line reply is one that each line, but the last, is in * the form of "ddd-" where 'ddd' is the result code. - * + * */ - private static final RE MULTILINE_RESULT; + private static final Pattern MULTILINE_RESULT; /** *

@@ -103,8 +103,8 @@ public final class SmtpPlugin extends AbstractPlugin { static { try { - MULTILINE_RESULT = new RE("^[1-5][0-9]{2}-"); - } catch (RESyntaxException re) { + MULTILINE_RESULT = Pattern.compile("^[1-5][0-9]{2}-"); + } catch (PatternSyntaxException re) { throw new java.lang.reflect.UndeclaredThrowableException(re); } } @@ -116,12 +116,12 @@ public final class SmtpPlugin extends AbstractPlugin { * true is returned from the method. Otherwise a false value is returned to * the caller. *

- * + * * @param host * The remote host to connect to. * @param port * The remote port on the host. - * + * * @return True if server supports SMTP on the specified port, false * otherwise */ @@ -149,7 +149,7 @@ public final class SmtpPlugin extends AbstractPlugin { do { result = lineRdr.readLine(); - } while (result != null && result.length() > 0 && MULTILINE_RESULT.match(result)); + } while (result != null && result.length() > 0 && MULTILINE_RESULT.matcher(result).find()); if (result == null || result.length() == 0) { LOG.info("Received truncated response from SMTP server {}", InetAddressUtils.str(host)); @@ -186,7 +186,7 @@ public final class SmtpPlugin extends AbstractPlugin { do { result = lineRdr.readLine(); - } while (result != null && result.length() > 0 && MULTILINE_RESULT.match(result)); + } while (result != null && result.length() > 0 && MULTILINE_RESULT.matcher(result).find()); if (result == null || result.length() == 0) { LOG.info("Received truncated response from SMTP server {}", InetAddressUtils.str(host)); @@ -222,7 +222,7 @@ public final class SmtpPlugin extends AbstractPlugin { do { result = lineRdr.readLine(); - } while (result != null && result.length() > 0 && MULTILINE_RESULT.match(result)); + } while (result != null && result.length() > 0 && MULTILINE_RESULT.matcher(result).find()); if (result == null || result.length() == 0) { LOG.info("Received truncated response from SMTP server {}", InetAddressUtils.str(host)); diff --git a/opennms-services/src/main/java/org/opennms/netmgt/capsd/plugins/TcpPlugin.java b/opennms-services/src/main/java/org/opennms/netmgt/capsd/plugins/TcpPlugin.java index 4c1f7ca..0547ae2 100644 --- a/opennms-services/src/main/java/org/opennms/netmgt/capsd/plugins/TcpPlugin.java +++ b/opennms-services/src/main/java/org/opennms/netmgt/capsd/plugins/TcpPlugin.java @@ -39,9 +39,9 @@ import java.net.InetSocketAddress; import java.net.NoRouteToHostException; import java.net.Socket; import java.util.Map; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; -import org.apache.regexp.RE; -import org.apache.regexp.RESyntaxException; import org.opennms.core.utils.InetAddressUtils; import org.opennms.core.utils.ParameterMap; import org.slf4j.Logger; @@ -86,7 +86,7 @@ public final class TcpPlugin extends AbstractPlugin { * caller. In order to return true the remote host must generate a banner * line which contains the text from the bannerMatch argument. *

- * + * * @param host * The remote host to connect to. * @param port @@ -94,11 +94,11 @@ public final class TcpPlugin extends AbstractPlugin { * @param bannerResult * Banner line generated by the remote host must contain this * text. - * + * * @return True if a connection is established with the host and the banner * line contains the bannerMatch text. */ - private boolean isServer(InetAddress host, int port, int retries, int timeout, RE regex, StringBuffer bannerResult) { + private boolean isServer(InetAddress host, int port, int retries, int timeout, Pattern regex, StringBuffer bannerResult) { boolean isAServer = false; for (int attempts = 0; attempts <= retries && !isAServer; attempts++) { @@ -128,7 +128,7 @@ public final class TcpPlugin extends AbstractPlugin { // service. // String response = lineRdr.readLine(); - if (regex.match(response)) { + if (regex.matcher(response).find()) { LOG.debug("isServer: matching response= {}", response); isAServer = true; @@ -237,25 +237,26 @@ public final class TcpPlugin extends AbstractPlugin { try { StringBuffer bannerResult = null; - RE regex = null; + Pattern regex = null; if (match == null && (banner == null || banner.equals("*"))) { regex = null; } else if (match != null) { - regex = new RE(match); + regex = Pattern.compile(match); bannerResult = new StringBuffer(); } else if (banner != null) { - regex = new RE(banner); + regex = Pattern.compile(banner); bannerResult = new StringBuffer(); } - + boolean result = isServer(address, port, retries, timeout, regex, bannerResult); if (result && qualifiers != null) { - if (bannerResult != null && bannerResult.length() > 0) + if (bannerResult != null && bannerResult.length() > 0) { qualifiers.put("banner", bannerResult.toString()); + } } return result; - } catch (RESyntaxException e) { + } catch (PatternSyntaxException e) { throw new java.lang.reflect.UndeclaredThrowableException(e); } } diff --git a/opennms-services/src/main/java/org/opennms/netmgt/poller/monitors/SmtpMonitor.java b/opennms-services/src/main/java/org/opennms/netmgt/poller/monitors/SmtpMonitor.java index f534c8a..cc6132f 100644 --- a/opennms-services/src/main/java/org/opennms/netmgt/poller/monitors/SmtpMonitor.java +++ b/opennms-services/src/main/java/org/opennms/netmgt/poller/monitors/SmtpMonitor.java @@ -39,9 +39,9 @@ import java.net.NoRouteToHostException; import java.net.Socket; import java.util.Map; import java.util.StringTokenizer; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; -import org.apache.regexp.RE; -import org.apache.regexp.RESyntaxException; import org.opennms.core.utils.InetAddressUtils; import org.opennms.core.utils.ParameterMap; import org.opennms.core.utils.TimeoutTracker; @@ -67,9 +67,9 @@ import org.slf4j.LoggerFactory; @Distributable public final class SmtpMonitor extends AbstractServiceMonitor { - + public static final Logger LOG = LoggerFactory.getLogger(SmtpMonitor.class); - + /** * Default SMTP port. @@ -97,15 +97,15 @@ public final class SmtpMonitor extends AbstractServiceMonitor { * the same 3 digit response code, but has a hyphen after the last number * instead of a space. */ - private static final RE MULTILINE; + private static final Pattern MULTILINE; /** * Init MULTILINE */ static { try { - MULTILINE = new RE("^[0-9]{3}-"); - } catch (RESyntaxException ex) { + MULTILINE = Pattern.compile("^[0-9]{3}-"); + } catch (PatternSyntaxException ex) { throw new java.lang.reflect.UndeclaredThrowableException(ex); } } @@ -137,7 +137,7 @@ public final class SmtpMonitor extends AbstractServiceMonitor { if (iface.getType() != NetworkInterface.TYPE_INET) { throw new NetworkInterfaceNotSupportedException("Unsupported interface type, only TYPE_INET currently supported"); } - + TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT); int port = ParameterMap.getKeyedInteger(parameters, "port", DEFAULT_PORT); @@ -179,7 +179,7 @@ public final class SmtpMonitor extends AbstractServiceMonitor { continue; } - if (MULTILINE.match(banner)) { + if (MULTILINE.matcher(banner).matches()) { // Ok we have a multi-line response...first three // chars of the response line are the return code. // The last line of the response will start with @@ -188,10 +188,10 @@ public final class SmtpMonitor extends AbstractServiceMonitor { // Create new regExp to look for last line // of this multi line response - RE endMultiline = null; + Pattern endMultiline = null; try { - endMultiline = new RE(multiLineRC); - } catch (RESyntaxException ex) { + endMultiline = Pattern.compile(multiLineRC); + } catch (PatternSyntaxException ex) { throw new java.lang.reflect.UndeclaredThrowableException(ex); } @@ -199,7 +199,7 @@ public final class SmtpMonitor extends AbstractServiceMonitor { // response do { banner = rdr.readLine(); - } while (banner != null && !endMultiline.match(banner)); + } while (banner != null && !endMultiline.matcher(banner).matches()); if (banner == null) { continue; } @@ -227,7 +227,7 @@ public final class SmtpMonitor extends AbstractServiceMonitor { continue; } - if (MULTILINE.match(response)) { + if (MULTILINE.matcher(response).matches()) { // Ok we have a multi-line response...first three // chars of the response line are the return code. // The last line of the response will start with @@ -236,10 +236,10 @@ public final class SmtpMonitor extends AbstractServiceMonitor { // Create new regExp to look for last line // of this multi line response - RE endMultiline = null; + Pattern endMultiline = null; try { - endMultiline = new RE(multiLineRC); - } catch (RESyntaxException ex) { + endMultiline = Pattern.compile(multiLineRC); + } catch (PatternSyntaxException ex) { throw new java.lang.reflect.UndeclaredThrowableException(ex); } @@ -247,7 +247,7 @@ public final class SmtpMonitor extends AbstractServiceMonitor { // response do { response = rdr.readLine(); - } while (response != null && !endMultiline.match(response)); + } while (response != null && !endMultiline.matcher(response).matches()); if (response == null) { continue; } @@ -267,7 +267,7 @@ public final class SmtpMonitor extends AbstractServiceMonitor { if (response == null) { continue; } - if (MULTILINE.match(response)) { + if (MULTILINE.matcher(response).matches()) { // Ok we have a multi-line response...first three // chars of the response line are the return code. // The last line of the response will start with @@ -276,10 +276,10 @@ public final class SmtpMonitor extends AbstractServiceMonitor { // Create new regExp to look for last line // of this multi line response - RE endMultiline = null; + Pattern endMultiline = null; try { - endMultiline = new RE(multiLineRC); - } catch (RESyntaxException ex) { + endMultiline = Pattern.compile(multiLineRC); + } catch (PatternSyntaxException ex) { throw new java.lang.reflect.UndeclaredThrowableException(ex); } @@ -287,7 +287,7 @@ public final class SmtpMonitor extends AbstractServiceMonitor { // response do { response = rdr.readLine(); - } while (response != null && !endMultiline.match(response)); + } while (response != null && !endMultiline.matcher(response).matches()); if (response == null) { continue; } diff --git a/opennms-services/src/main/java/org/opennms/netmgt/poller/monitors/SshMonitor.java b/opennms-services/src/main/java/org/opennms/netmgt/poller/monitors/SshMonitor.java index 8d8cedc..014637a 100644 --- a/opennms-services/src/main/java/org/opennms/netmgt/poller/monitors/SshMonitor.java +++ b/opennms-services/src/main/java/org/opennms/netmgt/poller/monitors/SshMonitor.java @@ -31,9 +31,9 @@ package org.opennms.netmgt.poller.monitors; import java.net.InetAddress; import java.util.Map; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; -import org.apache.regexp.RE; -import org.apache.regexp.RESyntaxException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.opennms.core.utils.ParameterMap; @@ -60,7 +60,7 @@ import org.opennms.netmgt.protocols.ssh.Ssh; */ @Distributable -final public class SshMonitor extends AbstractServiceMonitor { +public final class SshMonitor extends AbstractServiceMonitor { private static final Logger LOG = LoggerFactory.getLogger(SshMonitor.class); private static final int DEFAULT_RETRY = 0; @@ -80,7 +80,7 @@ final public class SshMonitor extends AbstractServiceMonitor { * to Provided that the interface's response is valid we mark the poll status * as available and return. */ - public PollStatus poll(InetAddress address, Map parameters) { + public PollStatus poll(final InetAddress address, final Map parameters) { TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT); @@ -89,20 +89,20 @@ final public class SshMonitor extends AbstractServiceMonitor { String match = ParameterMap.getKeyedString(parameters, "match", null); String clientBanner = ParameterMap.getKeyedString(parameters, "client-banner", Ssh.DEFAULT_CLIENT_BANNER); PollStatus ps = PollStatus.unavailable(); - + Ssh ssh = new Ssh(address, port, tracker.getConnectionTimeout()); ssh.setClientBanner(clientBanner); - RE regex = null; + Pattern regex = null; try { - if (match == null && (banner == null || banner.equals("*"))) { - regex = null; - } else if (match != null) { - regex = new RE(match); - } else if (banner != null) { - regex = new RE(banner); - } - } catch (final RESyntaxException e) { + if (match == null && (banner == null || banner.equals("*"))) { + regex = null; + } else if (match != null) { + regex = Pattern.compile(match); + } else if (banner != null) { + regex = Pattern.compile(banner); + } + } catch (final PatternSyntaxException e) { final String matchString = match == null? banner : match; LOG.info("Invalid regular expression for SSH banner match /{}/: {}", matchString, e.getMessage()); LOG.debug("Invalid Regular expression for SSH banner match /{}/", matchString, e); @@ -133,7 +133,7 @@ final public class SshMonitor extends AbstractServiceMonitor { return PollStatus.unavailable("server closed connection before banner was received."); } - if (regex.match(response)) { + if (regex.matcher(response).matches()) { LOG.debug("isServer: matching response={}", response); return ps; } else { @@ -144,7 +144,7 @@ final public class SshMonitor extends AbstractServiceMonitor { } } } - return ps; + return ps; } /** diff --git a/opennms-web-dependencies/pom.xml b/opennms-web-dependencies/pom.xml index 66e8bb1..b7a4553 100644 --- a/opennms-web-dependencies/pom.xml +++ b/opennms-web-dependencies/pom.xml @@ -23,10 +23,6 @@ commons-lang commons-lang
- - jakarta-regexp - jakarta-regexp - org.opennms diff --git a/opennms-webapp/src/main/java/org/opennms/web/svclayer/support/DefaultRrdGraphService.java b/opennms-webapp/src/main/java/org/opennms/web/svclayer/support/DefaultRrdGraphService.java index 2fb8a4d..ae87af6 100644 --- a/opennms-webapp/src/main/java/org/opennms/web/svclayer/support/DefaultRrdGraphService.java +++ b/opennms-webapp/src/main/java/org/opennms/web/svclayer/support/DefaultRrdGraphService.java @@ -28,7 +28,6 @@ package org.opennms.web.svclayer.support; - import java.io.File; import java.io.InputStream; import java.text.MessageFormat; @@ -40,9 +39,8 @@ import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; -import org.apache.regexp.RE; -import org.apache.regexp.RESyntaxException; import org.opennms.netmgt.dao.api.GraphDao; import org.opennms.netmgt.dao.api.ResourceDao; import org.opennms.netmgt.dao.api.RrdDao; @@ -69,16 +67,16 @@ import org.springframework.util.StringUtils; * @author Craig Miskell */ public class DefaultRrdGraphService implements RrdGraphService, InitializingBean { - + private static final Logger LOG = LoggerFactory.getLogger(DefaultRrdGraphService.class); // private static final String s_missingParamsPath = "/images/rrd/missingparams.png"; private static final String s_rrdError = "/images/rrd/error.png"; - + private GraphDao m_graphDao; private ResourceDao m_resourceDao; - + private RrdDao m_rrdDao; /** {@inheritDoc} */ @@ -95,12 +93,12 @@ public class DefaultRrdGraphService implements RrdGraphService, InitializingBean Assert.notNull(dataSourceTitles, "dataSourceTitles argument cannot be null"); Assert.notNull(styles, "styles argument cannot be null"); Assert.isTrue(end > start, "end time must be after start time"); - + AdhocGraphType t = m_graphDao.findAdhocGraphTypeByName("performance"); OnmsResource r = m_resourceDao.getResourceById(resourceId); Assert.notNull(r, "resource \"" + resourceId + "\" could not be located"); - + String command = createAdHocCommand(t, r, start, end, @@ -110,7 +108,7 @@ public class DefaultRrdGraphService implements RrdGraphService, InitializingBean colors, dataSourceTitles, styles); - + return getInputStreamForCommand(command); } @@ -133,7 +131,7 @@ public class DefaultRrdGraphService implements RrdGraphService, InitializingBean return tempIn; } - + /** *

returnErrorImage

* @@ -160,12 +158,12 @@ public class DefaultRrdGraphService implements RrdGraphService, InitializingBean throw new IllegalArgumentException("graph type \"" + "performance" + "\" is not valid"); } - + OnmsResource r = m_resourceDao.getResourceById(resourceId); Assert.notNull(r, "resource could not be located"); PrefabGraph prefabGraph = m_graphDao.getPrefabGraph(report); - + Graph graph = new Graph(prefabGraph, r, new Date(start), new Date(end)); String command = createPrefabCommand(graph, @@ -174,10 +172,10 @@ public class DefaultRrdGraphService implements RrdGraphService, InitializingBean report, width, height); - + return getInputStreamForCommand(command); } - + /** *

createAdHocCommand

* @@ -218,7 +216,7 @@ public class DefaultRrdGraphService implements RrdGraphService, InitializingBean buf.append(commandPrefix); buf.append(" "); buf.append(title); - + String[] rrdFiles = getRrdNames(resource, dsNames); List defs = new ArrayList(dsNames.length); @@ -238,13 +236,13 @@ public class DefaultRrdGraphService implements RrdGraphService, InitializingBean dsAbbrev, dsName, dsAggregFxn, dsStyle, color, dsTitle)); - + lines.add(MessageFormat.format(graphline, rrd, starttime, endtime, graphtitle, dsAbbrev, dsName, dsAggregFxn, dsStyle, color, dsTitle)); } - + for (String def : defs) { buf.append(" "); buf.append(def); @@ -260,7 +258,7 @@ public class DefaultRrdGraphService implements RrdGraphService, InitializingBean private static String[] getRrdNames(OnmsResource resource, String[] dsNames) { String[] rrds = new String[dsNames.length]; - + Map attributes = resource.getRrdGraphAttributes(); for (int i=0; i < dsNames.length; i++) { @@ -274,15 +272,15 @@ public class DefaultRrdGraphService implements RrdGraphService, InitializingBean return rrds; } - + private static Map getTranslationsForAttributes(Map attributes, String[] requiredAttributes, String type) { if (requiredAttributes == null) { // XXX Nothing to do; not sure if we need this check return new HashMap(0); } - + Map translations = new HashMap(requiredAttributes.length); - + for (String requiredAttribute : requiredAttributes) { String attributeValue = attributes.get(requiredAttribute); if (attributeValue == null) { @@ -291,7 +289,7 @@ public class DefaultRrdGraphService implements RrdGraphService, InitializingBean // Replace any single backslashes in the value with escaped backslashes so other parsing won't barf String replacedValue = attributeValue.replace("\\", "\\\\"); - translations.put(RE.simplePatternToFullRegularExpression("{" + requiredAttribute + "}"), replacedValue); + translations.put("{" + requiredAttribute + "}", replacedValue); } return translations; @@ -307,24 +305,21 @@ public class DefaultRrdGraphService implements RrdGraphService, InitializingBean * @return a {@link java.lang.String} object. */ - protected String createPrefabCommand(Graph graph, - String commandPrefix, - File workDir, String reportName, - Integer width, Integer height) { + protected String createPrefabCommand(Graph graph, String commandPrefix, File workDir, String reportName, Integer width, Integer height) { PrefabGraph prefabGraph = graph.getPrefabGraph(); String[] rrds = getRrdNames(graph.getResource(), graph.getPrefabGraph().getColumns()); - + StringBuffer buf = new StringBuffer(); buf.append(commandPrefix); buf.append(" "); buf.append(prefabGraph.getCommand()); String command = buf.toString(); - + long startTime = graph.getStart().getTime(); long endTime = graph.getEnd().getTime(); long diffTime = endTime - startTime; - + /* * remember rrdtool wants the time in seconds, not milliseconds; * java.util.Date.getTime() returns milliseconds, so divide by 1000 @@ -332,57 +327,53 @@ public class DefaultRrdGraphService implements RrdGraphService, InitializingBean String startTimeString = Long.toString(startTime / 1000); String endTimeString = Long.toString(endTime / 1000); String diffTimeString = Long.toString(diffTime / 1000); - + HashMap translationMap = new HashMap(); - + for (int i = 0; i < rrds.length; i++) { String key = "{rrd" + (i + 1) + "}"; - translationMap.put(RE.simplePatternToFullRegularExpression(key), rrds[i]); + translationMap.put(key, rrds[i]); } - - translationMap.put(RE.simplePatternToFullRegularExpression("{startTime}"), startTimeString); - translationMap.put(RE.simplePatternToFullRegularExpression("{endTime}"), endTimeString); - translationMap.put(RE.simplePatternToFullRegularExpression("{diffTime}"), diffTimeString); + + translationMap.put("{startTime}", startTimeString); + translationMap.put("{endTime}", endTimeString); + translationMap.put("{diffTime}", diffTimeString); SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); - translationMap.put(RE.simplePatternToFullRegularExpression("{startTimeDate}"), fmt.format(new Date(startTime)).replace(":", "\\:")); - translationMap.put(RE.simplePatternToFullRegularExpression("{endTimeDate}"), fmt.format(new Date(endTime)).replace(":", "\\:")); + translationMap.put("{startTimeDate}", fmt.format(new Date(startTime)).replace(":", "\\:")); + translationMap.put("{endTimeDate}", fmt.format(new Date(endTime)).replace(":", "\\:")); // Handle a start time with a format. - RE stre = new RE("\\{startTime:(.+?)\\}"); - int pos = 0; + Matcher stm = Pattern.compile("\\{startTime:(.+?)\\}").matcher(command); boolean matchFail = false; - while (stre.match(command, pos) && !matchFail) { - String sdfPattern = stre.getParen(1); + while(stm.find() && !matchFail) { + String sdfPattern = stm.group(0); if (sdfPattern == null) { - matchFail = true; + matchFail = true; } else { try { fmt = new SimpleDateFormat(sdfPattern); - translationMap.put(RE.simplePatternToFullRegularExpression("{startTime:"+sdfPattern+"}"), fmt.format(new Date(startTime)).replace(":", "\\:")); + translationMap.put("{startTime:"+sdfPattern+"}", fmt.format(new Date(startTime)).replace(":", "\\:")); } catch (IllegalArgumentException e) { LOG.error("Cannot parse date format '{}' for graph {}.", sdfPattern, reportName); } - pos = pos + sdfPattern.length() + 1; } } // Handle an end time with a format - RE etre = new RE("\\{endTime:(.+?)\\}"); - pos = 0; + Matcher etm = Pattern.compile("\\{endTime:(.+?)\\}").matcher(command); matchFail = false; - while (etre.match(command, pos) && !matchFail) { - String sdfPattern = etre.getParen(1); + while (etm.find() && !matchFail) { + String sdfPattern = etm.group(0); if (sdfPattern == null) { matchFail = true; } else { try { fmt = new SimpleDateFormat(sdfPattern); - translationMap.put(RE.simplePatternToFullRegularExpression("{endTime:"+sdfPattern+"}"), fmt.format(new Date(endTime)).replace(":", "\\:")); + translationMap.put("{endTime:"+sdfPattern+"}", fmt.format(new Date(endTime)).replace(":", "\\:")); } catch (IllegalArgumentException e) { LOG.error("Cannot parse date format '{}' for graph {}.", sdfPattern, reportName); } - pos = pos + sdfPattern.length() + 1; } } @@ -393,24 +384,22 @@ public class DefaultRrdGraphService implements RrdGraphService, InitializingBean LOG.error("Invalid attributes were found on resource '{}'", graph.getResource().getId()); throw e; } - - + + try { for (Map.Entry translation : translationMap.entrySet()) { // replace s1 with s2 - RE re = new RE(translation.getKey()); - command = re.subst(command, translation.getValue()); + final Matcher matcher = Pattern.compile(translation.getKey(), Pattern.LITERAL).matcher(command); + matcher.replaceAll(translation.getValue()); } - } catch (RESyntaxException e) { - throw new IllegalArgumentException("Invalid regular expression " - + "syntax, check " - + "rrd-properties file", e); + } catch (PatternSyntaxException e) { + throw new IllegalArgumentException("Invalid regular expression syntax, check rrd-properties file", e); } - - + + if (width != null) { final Pattern re = Pattern.compile("(--width|-w)(\\w+|=)(\\d+)"); - + final Matcher matcher = re.matcher(command); if (matcher.matches()) { matcher.replaceFirst("--width " + width); @@ -418,10 +407,10 @@ public class DefaultRrdGraphService implements RrdGraphService, InitializingBean command = command + " --width " + width; } } - + if (height != null) { final Pattern re = Pattern.compile("(--height|-h)(\\w+|=)(\\d+)"); - + final Matcher matcher = re.matcher(command); if (matcher.matches()) { matcher.replaceFirst("--height " + height); @@ -429,7 +418,7 @@ public class DefaultRrdGraphService implements RrdGraphService, InitializingBean command = command + " --height " + height; } } - + return command; } diff --git a/opennms-webapp/src/main/webapp/admin/notification/noticeWizard/buildRule.jsp b/opennms-webapp/src/main/webapp/admin/notification/noticeWizard/buildRule.jsp index 232c5ed..fe2355f 100644 --- a/opennms-webapp/src/main/webapp/admin/notification/noticeWizard/buildRule.jsp +++ b/opennms-webapp/src/main/webapp/admin/notification/noticeWizard/buildRule.jsp @@ -32,7 +32,7 @@ <%@page language="java" contentType="text/html" session="true" - import="java.util.*, + import="java.util.*, java.util.regex.*, java.sql.*, org.opennms.web.admin.notification.noticeWizard.*, org.opennms.netmgt.config.*, @@ -64,7 +64,7 @@ document.rule.nextPage.value="<%=NotificationWizardServlet.SOURCE_PAGE_VALIDATE%>"; document.rule.submit(); } - + function skipVerification() { document.rule.nextPage.value="<%=NotificationWizardServlet.SOURCE_PAGE_PATH%>"; @@ -86,7 +86,7 @@ action="admin/notification/noticeWizard/notificationWizard" > - +

Filtering on TCP/IP address uses a very flexible format, allowing you @@ -98,7 +98,7 @@

The following examples are all valid and yield the set of addresses from 192.168.0.0 through 192.168.3.255.

- +
  • 192.168.0-3.*
  • 192.168.0-3.0-255 @@ -159,7 +159,7 @@ { List services = NotificationFactory.getInstance().getServiceNames(); StringBuffer buffer = new StringBuffer(); - + for (String service : services) { int serviceIndex = rule.indexOf(service); @@ -173,7 +173,7 @@ buffer.append(""); } } - + return buffer.toString(); } @@ -182,7 +182,7 @@ { List services = NotificationFactory.getInstance().getServiceNames(); StringBuffer buffer = new StringBuffer(); - + for (int i = 0; i < services.size(); i++) { //find services in the rule, but start looking after the first "!" (not), to avoid @@ -198,26 +198,21 @@ buffer.append(""); } } - + return buffer.toString(); } - public String getIpaddr(String rule) - throws org.apache.regexp.RESyntaxException - { - org.apache.regexp.RE dirRegEx = null; - dirRegEx = new org.apache.regexp.RE( ".+\\..+\\..+\\..+"); - + public String getIpaddr(String rule) { + Pattern dirRegEx = Pattern.compile(".+\\..+\\..+\\..+"); + StringTokenizer tokens = new StringTokenizer(rule, " "); - while(tokens.hasMoreTokens()) - { + while(tokens.hasMoreTokens()) { String nextToken = tokens.nextToken(); - if (dirRegEx.match( nextToken )) - { + if (dirRegEx.matcher( nextToken ).matches()) { return nextToken; } } - + return "*.*.*.*"; } %> diff --git a/pom.xml b/pom.xml index 33e24ef..d9044f9 100644 --- a/pom.xml +++ b/pom.xml @@ -767,7 +767,6 @@ http://jakarta.apache.org/commons/pool/apidocs/ http://junit.sourceforge.net/javadoc/ http://logging.apache.org/log4j/docs/api/ - http://jakarta.apache.org/regexp/apidocs/ http://jakarta.apache.org/velocity/api/ @@ -2690,11 +2689,6 @@ ${jacksonVersion} - jakarta-regexp - jakarta-regexp - 1.4 - - javax.annotation jsr250-api 1.0 diff --git a/protocols/xmp/src/main/java/org/opennms/netmgt/protocols/xmp/XmpUtil.java b/protocols/xmp/src/main/java/org/opennms/netmgt/protocols/xmp/XmpUtil.java index 2217d3d..1d2836e 100644 --- a/protocols/xmp/src/main/java/org/opennms/netmgt/protocols/xmp/XmpUtil.java +++ b/protocols/xmp/src/main/java/org/opennms/netmgt/protocols/xmp/XmpUtil.java @@ -36,9 +36,9 @@ package org.opennms.netmgt.protocols.xmp; import java.math.BigInteger; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; -import org.apache.regexp.RE; -import org.apache.regexp.RESyntaxException; import org.krupczak.xmp.Xmp; import org.krupczak.xmp.XmpMessage; import org.krupczak.xmp.XmpSession; @@ -47,7 +47,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class XmpUtil { - + private static final Logger LOG = LoggerFactory.getLogger(XmpUtil.class); /** Constant LESS_THAN="<" */ @@ -64,22 +64,23 @@ public class XmpUtil { public static final String NOT_EQUAL = "!="; /** Constant MATCHES="~" */ public static final String MATCHES = "~"; - + private static boolean valueMeetsCriteria(XmpVar replyVar, String valueOperator, String valueOperand, boolean caseSensitive) throws XmpUtilException { - RE valueRegex = null; + Pattern valueRegex = null; if (MATCHES.equals(valueOperator)) { try { - valueRegex = new RE(valueOperand); - if (!caseSensitive) { - valueRegex.setMatchFlags(RE.MATCH_CASEINDEPENDENT); - } - } catch (final RESyntaxException e) { + int flags = 0; + if (!caseSensitive) { + flags |= Pattern.CASE_INSENSITIVE; + } + valueRegex = Pattern.compile(valueOperand, flags); + } catch (final PatternSyntaxException e) { LOG.debug("Unable to initialize regular expression.", e); } } - - if ((valueRegex != null) && valueRegex.match(replyVar.getValue())) { + + if ((valueRegex != null) && valueRegex.matcher(replyVar.getValue()).matches()) { LOG.debug("handleScalarQuery: Response value |{}| matches, returning true", replyVar.getValue()); return true; } else if ((MATCHES.equals(valueOperator)) && ((valueRegex == null) || ("".equals(valueRegex)))) { @@ -112,7 +113,7 @@ public class XmpUtil { return (intValue.compareTo(intOperand) > 0); } else if (LESS_THAN_EQUALS.equals(valueOperator)) { return (intValue.compareTo(intOperand) <= 0); - } else if (GREATER_THAN_EQUALS.equals(valueOperator)) { + } else if (GREATER_THAN_EQUALS.equals(valueOperator)) { return (intValue.compareTo(intOperand) >= 0); } else if (EQUALS.equals(valueOperator)) { return (intValue.compareTo(intOperand) == 0); @@ -156,7 +157,7 @@ public class XmpUtil { throw new XmpUtilException("Value operator '" + valueOperator + "' does not apply for non-numeric value operand '" + valueOperand + "'"); } if (caseSensitive) { - return valueOperand.equals(replyVar.getValue()); + return valueOperand.equals(replyVar.getValue()); } else { return valueOperand.equalsIgnoreCase(replyVar.getValue()); } @@ -168,7 +169,7 @@ public class XmpUtil { throw new XmpUtilException("Response value '" + replyVar.getValue() + "' does not match for value operator '" + valueOperator +"' and value operand '" + valueOperand +"'"); } } - + return false; } @@ -189,9 +190,9 @@ public class XmpUtil { XmpMessage reply; XmpVar[] queryVars = new XmpVar[1]; XmpVar[] replyVars; - + queryVars[0] = new XmpVar(mib, object, Xmp.SYNTAX_NULLSYNTAX); - + reply = session.queryVars(queryVars); if (reply == null) { LOG.warn("handleScalarQuery: query for object {} from MIB {} failed, {}", object, mib, Xmp.errorStatusToString(session.getErrorStatus())); @@ -199,7 +200,7 @@ public class XmpUtil { } else { LOG.debug("handleScalarQuery: query for object {} from MIB {} succeeded.", object, mib); } - + replyVars = reply.getMIBVars(); if (replyVars[0].getMibName().equals(mib) && replyVars[0].getObjName().equals(object)) { return valueMeetsCriteria(replyVars[0], valueOperator, valueOperand, caseSensitive); @@ -217,7 +218,7 @@ public class XmpUtil { * @param table a {@link java.lang.String} object. * @param object a {@link java.lang.String} object. * @param instance a {@link java.lang.String} object. - * @param instanceRegex a {@link org.apache.regexp.RE} object. + * @param instanceRegex a {@link java.util.regex.Pattern} object. * @param valueOperator a {@link java.lang.String} object. * @param valueOperand a {@link java.lang.String} object. * @param minMatches a int. @@ -228,7 +229,7 @@ public class XmpUtil { * @throws org.opennms.netmgt.protocols.xmp.XmpUtilException if any. */ public static boolean handleTableQuery(XmpSession session, String mib, - String table, String object, String instance, RE instanceRegex, + String table, String object, String instance, Pattern instanceRegex, String valueOperator, String valueOperand, int minMatches, int maxMatches, boolean maxMatchesUnbounded, boolean caseSensitive) throws XmpUtilException { @@ -237,23 +238,23 @@ public class XmpUtil { XmpVar[] queryVars = new XmpVar[1]; XmpVar[] replyVars; int numMatches = 0; - + queryVars[0] = new XmpVar(mib, object, Xmp.SYNTAX_NULLSYNTAX); - + tableInfo[0] = mib; tableInfo[1] = object; tableInfo[2] = instance; reply = session.queryTableVars(tableInfo, 0, queryVars); - + if (reply == null) { LOG.warn("handleTableQuery: query for object {} from MIB {} failed, {}", object, mib, Xmp.errorStatusToString(session.getErrorStatus())); throw new XmpUtilException("XMP query failed (MIB " + mib + ", object " + object + "): " + Xmp.errorStatusToString(session.getErrorStatus())); } - + replyVars = reply.getMIBVars(); LOG.debug("handleTableQuery: Got reply with {} variables", replyVars.length); - - + + /* Since we're constrained to a single object, we know that there's * exactly one column in the result set and so can use a Java 5 * for() loop. If there were multiple columns, we'd have to break the @@ -262,10 +263,9 @@ public class XmpUtil { */ for (XmpVar thisVar : replyVars) { String rowInstance = thisVar.getKey(); - if ((instanceRegex != null) && (!instanceRegex.match(rowInstance))) { - + if ((instanceRegex != null) && (!instanceRegex.matcher(rowInstance).matches())) { LOG.debug("handleTableQuery: instance {} does not match, skipping this row.", rowInstance); - + continue; // to next var } else if (instanceRegex == null) { LOG.debug("handleTableQuery: instance match not specified, evaluating value of instance {}", rowInstance); @@ -276,7 +276,7 @@ public class XmpUtil { numMatches++; } } - + if (numMatches >= minMatches) { LOG.debug("handleTableQuery: Found {} matches, meets specified minimum of {}", numMatches, minMatches); if (maxMatchesUnbounded) { diff --git a/protocols/xmp/src/main/java/org/opennms/netmgt/protocols/xmp/capsd/XmpPlugin.java b/protocols/xmp/src/main/java/org/opennms/netmgt/protocols/xmp/capsd/XmpPlugin.java index 5f76508..544516f 100644 --- a/protocols/xmp/src/main/java/org/opennms/netmgt/protocols/xmp/capsd/XmpPlugin.java +++ b/protocols/xmp/src/main/java/org/opennms/netmgt/protocols/xmp/capsd/XmpPlugin.java @@ -37,14 +37,13 @@ package org.opennms.netmgt.protocols.xmp.capsd; import java.net.InetAddress; import java.util.Map; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; -import org.apache.regexp.RE; -import org.apache.regexp.RESyntaxException; import org.krupczak.xmp.SocketOpts; import org.krupczak.xmp.Xmp; import org.krupczak.xmp.XmpSession; import org.opennms.core.utils.ParameterMap; - import org.opennms.netmgt.capsd.AbstractPlugin; import org.opennms.netmgt.config.xmpConfig.XmpConfig; import org.opennms.netmgt.protocols.xmp.XmpUtil; @@ -69,20 +68,19 @@ import org.slf4j.LoggerFactory; * @version $Id: $ */ public final class XmpPlugin extends AbstractPlugin { - private static final Logger LOG = LoggerFactory.getLogger(XmpPlugin.class); - + private static final Logger LOG = LoggerFactory.getLogger(XmpPlugin.class); /** * The protocol supported by the plugin */ private final static String PROTOCOL_NAME = "XMP"; - + /** * The default port to use for XMP */ private final static int DEFAULT_PORT = Xmp.XMP_PORT; - - + + /** * Default number of retries for TCP requests */ @@ -92,7 +90,7 @@ public final class XmpPlugin extends AbstractPlugin { * Default timeout (in milliseconds) for XMP requests */ private final static int DEFAULT_TIMEOUT = 5000; // in milliseconds - + /** * Default XMP user for performing requests */ @@ -102,49 +100,49 @@ public final class XmpPlugin extends AbstractPlugin { * Default type of request to perform */ private final static String DEFAULT_REQUEST_TYPE = "GetRequest"; - + /** * Default MIB from which to make request */ private final static String DEFAULT_REQUEST_MIB = "core"; - + /** * Default table from which to make request */ private final static String DEFAULT_REQUEST_TABLE = ""; - + /** * Default object name to request */ private final static String DEFAULT_REQUEST_OBJECT = "sysObjectID"; - + /** * Default instance to request (for SelectTableRequest only) */ private final static String DEFAULT_REQUEST_INSTANCE = "*"; - + /** * Default string against which to match the returned value(s) */ private final static String DEFAULT_VALUE_MATCH = null; - + /** * Default string against which to match the returned instance(s) */ private final static String DEFAULT_INSTANCE_MATCH = null; - + /** * Default integer denoting minimum number of * matches allowed */ private final static int DEFAULT_MIN_MATCHES = 1; - + /** * Default integer denoting maximum number of * matches allowed. */ private final static int DEFAULT_MAX_MATCHES = 1; - + /** * Default boolean indicating whether maximum number * of matches is actually unbounded @@ -189,7 +187,7 @@ public final class XmpPlugin extends AbstractPlugin { */ @Override public boolean isProtocolSupported(InetAddress address, Map qualifiers) { - + XmpConfig protoConfig = XmpConfigFactory.getInstance().getXmpConfig(); XmpSession session; SocketOpts sockopts = new SocketOpts(); @@ -230,10 +228,10 @@ public final class XmpPlugin extends AbstractPlugin { String maxMatchesUnboundedStr = ParameterMap.getKeyedString(qualifiers, "max-matches", "unbounded"); maxMatchesUnbounded = (maxMatchesUnboundedStr.equalsIgnoreCase("unbounded")); } - + // Set the SO_TIMEOUT so that this thing has a prayer of working over a WAN sockopts.setConnectTimeout(timeout); - + // If this is a SelectTableRequest, then you can't use the defaults // for Table and Object. if (requestType.equalsIgnoreCase("SelectTableRequest")) { @@ -244,7 +242,7 @@ public final class XmpPlugin extends AbstractPlugin { throw new IllegalArgumentException("When performing a SelectTableRequest, object must be specified and must be tabular"); } } - + // If this is a GetRequest, then you can't specify a table or // an instance else if (requestType.equalsIgnoreCase("GetRequest")) { @@ -257,15 +255,13 @@ public final class XmpPlugin extends AbstractPlugin { } else { throw new IllegalArgumentException("Unknown request type " + requestType + ", only GetRequest and SelectTableRequest are supported"); } - - RE instanceRegex = null; + + Pattern instanceRegex = null; try { - if (instanceMatch == null) { - instanceRegex = null; - } else if (instanceMatch != null) { - instanceRegex = new RE(instanceMatch); + if (instanceMatch != null) { + instanceRegex = Pattern.compile(instanceMatch); } - } catch (RESyntaxException e) { + } catch (PatternSyntaxException e) { throw new java.lang.reflect.UndeclaredThrowableException(e); } @@ -289,7 +285,7 @@ public final class XmpPlugin extends AbstractPlugin { } catch (XmpUtilException e) { result = false; } - } + } return result; } } diff --git a/protocols/xmp/src/main/java/org/opennms/netmgt/protocols/xmp/monitor/XmpMonitor.java b/protocols/xmp/src/main/java/org/opennms/netmgt/protocols/xmp/monitor/XmpMonitor.java index e10bd02..3eb4e1b 100644 --- a/protocols/xmp/src/main/java/org/opennms/netmgt/protocols/xmp/monitor/XmpMonitor.java +++ b/protocols/xmp/src/main/java/org/opennms/netmgt/protocols/xmp/monitor/XmpMonitor.java @@ -37,16 +37,14 @@ package org.opennms.netmgt.protocols.xmp.monitor; import java.net.InetAddress; import java.util.Map; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; -import org.apache.regexp.RE; -import org.apache.regexp.RESyntaxException; import org.krupczak.xmp.SocketOpts; import org.krupczak.xmp.Xmp; import org.krupczak.xmp.XmpSession; import org.opennms.core.utils.ParameterMap; - import org.opennms.netmgt.config.xmpConfig.XmpConfig; - import org.opennms.netmgt.model.PollStatus; import org.opennms.netmgt.poller.MonitoredService; import org.opennms.netmgt.poller.NetworkInterface; @@ -62,14 +60,14 @@ import org.opennms.netmgt.protocols.xmp.config.XmpConfigFactory; * @version $Id: $ */ public class XmpMonitor extends AbstractServiceMonitor { - - + + /** * The default port to use for XMP */ private final static int DEFAULT_PORT = Xmp.XMP_PORT; - + /** * Default number of retries for TCP requests */ @@ -79,7 +77,7 @@ public class XmpMonitor extends AbstractServiceMonitor { * Default timeout (in milliseconds) for XMP requests */ private final static int DEFAULT_TIMEOUT = 5000; // in milliseconds - + /** * Default XMP user for performing requests */ @@ -89,49 +87,49 @@ public class XmpMonitor extends AbstractServiceMonitor { * Default type of request to perform */ private final static String DEFAULT_REQUEST_TYPE = "GetRequest"; - + /** * Default MIB from which to make request */ private final static String DEFAULT_REQUEST_MIB = "core"; - + /** * Default table from which to make request */ private final static String DEFAULT_REQUEST_TABLE = ""; - + /** * Default object name to request */ private final static String DEFAULT_REQUEST_OBJECT = "sysObjectID"; - + /** * Default instance to request (for SelectTableRequest only) */ private final static String DEFAULT_REQUEST_INSTANCE = "*"; - + /** * Default string against which to match the returned value(s) */ private final static String DEFAULT_VALUE_MATCH = null; - + /** * Default string against which to match the returned instance(s) */ private final static String DEFAULT_INSTANCE_MATCH = null; - + /** * Default integer denoting minimum number of * matches allowed */ private final static int DEFAULT_MIN_MATCHES = 1; - + /** * Default integer denoting maximum number of * matches allowed. */ private final static int DEFAULT_MAX_MATCHES = 1; - + /** * Default boolean indicating whether maximum number * of matches is actually unbounded @@ -145,18 +143,18 @@ public class XmpMonitor extends AbstractServiceMonitor { @Override public PollStatus poll(MonitoredService svc, Map parameters) { NetworkInterface iface = svc.getNetInterface(); - + PollStatus status = PollStatus.unavailable(); InetAddress ipaddr = (InetAddress) iface.getAddress(); - + XmpConfig protoConfig = XmpConfigFactory.getInstance().getXmpConfig(); XmpSession session; SocketOpts sockopts = new SocketOpts(); // TODO how to apply timeout and retry to XMP operations? int retry = protoConfig.hasRetry() ? protoConfig.getRetry() : DEFAULT_RETRY; int timeout = protoConfig.hasTimeout() ? protoConfig.getTimeout() : DEFAULT_TIMEOUT; - int port = DEFAULT_PORT; + int port = DEFAULT_PORT; String authenUser = DEFAULT_AUTHEN_USER; String requestType = DEFAULT_REQUEST_TYPE; String mib = DEFAULT_REQUEST_MIB; @@ -201,7 +199,7 @@ public class XmpMonitor extends AbstractServiceMonitor { throw new IllegalArgumentException("When performing a SelectTableRequest, object must be specified and must be tabular"); } } - + // If this is a GetRequest, then you can't specify a table or // an instance else if (requestType.equalsIgnoreCase("GetRequest")) { @@ -214,23 +212,21 @@ public class XmpMonitor extends AbstractServiceMonitor { } else { throw new IllegalArgumentException("Unknown request type " + requestType + ", only GetRequest and SelectTableRequest are supported"); } - - RE instanceRegex = null; + + Pattern instanceRegex = null; try { - if (instanceMatch == null) { - instanceRegex = null; - } else if (instanceMatch != null) { - instanceRegex = new RE(instanceMatch); + if (instanceMatch != null) { + instanceRegex = Pattern.compile(instanceMatch); } - } catch (RESyntaxException e) { + } catch (final PatternSyntaxException e) { throw new java.lang.reflect.UndeclaredThrowableException(e); } - + long startTime = System.currentTimeMillis(); - + // Set the SO_TIMEOUT. What a concept! sockopts.setConnectTimeout(timeout); - + session = new XmpSession(sockopts, ipaddr, port, authenUser); boolean result = false; -- 1.8.4.2