gpt4 book ai didi

java - 模式匹配器 IllegalStateException

转载 作者:行者123 更新时间:2023-12-01 14:43:08 36 4
gpt4 key购买 nike

我正在使用 Adventnet SNMPAPI 开发 UDP 监听程序。现在我需要将监听数据保存到数据库中。当我这样做时,我遇到了错误。任何人都可以帮忙解决这个问题吗...

这是我的代码。

import com.adventnet.snmp.beans.*; 
import com.adventnet.snmp.snmp2.*;
import com.adventnet.snmp.snmp2.usm.*;
import java.io.*;
import java.net.*;
import java.sql.*;
import java.util.regex.*;

public class trapreceiver {

private static int MIBS = 0;
private static int COMMUNITY = 1;
private static int PORT = 2;

private static int USER_NAME = 3;
private static int ENGID = 4;
private static int AUTH_PROTOCOL = 5;
private static int AUTH_PASSWORD = 6;
private static int PRIV_PASSWORD = 7;
private static int DEBUG = 8;
private static int CONTEXT_NAME = 9;
private static int CONTEXT_ID = 10;
private static int PRIV_PROTOCOL = 11;
private static String Data;
public static void main(String args[]) {

// Take care of getting options

String usage = "trapreceiver [-m MIB_files] [-c community] [-p port] [-u user] [-e engineID(1234.../0x1234...)] [-a authProtocol(MD5/SHA)] [-w auth_password] [-s priv_password] [-d] [-n contextName] [-i contextId] [ -pp priv_protocol(DES/AES-128/AES-192/AES-256/3DES) ]";
String options[] = { "-m" , "-c", "-p", "-u", "-e", "-a", "-w", "-s", "-d", "-n", "-i", "-pp" };
String values[] = { null, null, null, null, null, null, null, null, "None", null, null, null};
String DataReceived = null;
String userName = null;
int authProtocol = USMUserEntry.NO_AUTH;
String authPassword = new String ("");
String privPassword = new String ("");
String engineID = null;

int privProtocol = USMUserEntry.NO_PRIV;
byte secLevel = 0;

ParseOptions opt = new ParseOptions(args,options,values, usage);
if (opt.remArgs.length!=0) opt.usage_error();

// instantiate a receiver object
SnmpTrapReceiver receiver = new SnmpTrapReceiver();

//To load MIBs from compiled file
receiver.getMibOperations().setLoadFromCompiledMibs(true);

if (values[COMMUNITY] != null) receiver.setCommunity( values[COMMUNITY] );
try { // set trap port to listen on if specified - else port 162

if (values[PORT] != null) {
receiver.setPortWithExceptionMsg( Integer.parseInt(values[PORT]) );
} else {
System.out.println("Trying to set port 162 as the receiver port...");
receiver.setPortWithExceptionMsg( 162 );
}


if (values[USER_NAME] != null) {
userName = values[USER_NAME];
receiver.setPrincipal(userName);
}

if (values[ENGID] != null) {
engineID = values[ENGID];
if(engineID.startsWith("0x") || engineID.startsWith("0X"))
engineID = new String(gethexValue(values[ENGID]));
}

if (values[AUTH_PROTOCOL] != null) {
if(engineID == null) {
System.out.println("EngineID is missing");
opt.usage_error();
}
if ( values[AUTH_PROTOCOL].equals("SHA"))
authProtocol = USMUserEntry.SHA_AUTH;
else if ( values[AUTH_PROTOCOL].equals("MD5"))
authProtocol = USMUserEntry.MD5_AUTH;
else
authProtocol = USMUserEntry.NO_AUTH;
receiver.setAuthProtocol(authProtocol);
receiver.setTrapAuthEnable(true);
secLevel |= 0x01;
}

if (values[AUTH_PASSWORD] != null) {
if(engineID == null) {
System.out.println("EngineID is missing");
opt.usage_error();
}
if (secLevel == 0x01) {
authPassword = values[AUTH_PASSWORD];
receiver.setAuthPassword(authPassword);
}
else
opt.usage_error();
}

if(values[PRIV_PASSWORD] != null) {
if(engineID == null) {
System.out.println("EngineID is missing");
opt.usage_error();
}
if (secLevel == 0x01)
{
privPassword = values[PRIV_PASSWORD];
if(values[PRIV_PROTOCOL] != null)
{
if(values[PRIV_PROTOCOL].equals("AES-128"))
{
privProtocol = USMUserEntry.CFB_AES_128;
}
else if(values[PRIV_PROTOCOL].equals("AES-192"))
{
privProtocol = USMUserEntry.CFB_AES_192;
}
else if(values[PRIV_PROTOCOL].equals("AES-256"))
{
privProtocol = USMUserEntry.CFB_AES_256;
}
else if(values[PRIV_PROTOCOL].equals("3DES"))
{
privProtocol = USMUserEntry.CBC_3DES;
}
else if(values[PRIV_PROTOCOL].equals("DES"))
{
privProtocol = USMUserEntry.CBC_DES;
}
else
{
System.out.println(" Invalid PrivProtocol "+values[PRIV_PROTOCOL]);
opt.usage_error();
}
}

receiver.setPrivPassword(privPassword);
receiver.setPrivProtocol(privProtocol);

if(values[CONTEXT_NAME]!= null)
receiver.setContextName(values[CONTEXT_NAME]);
if(values[CONTEXT_ID]!= null)
receiver.setContextID((values[CONTEXT_ID]).getBytes());

secLevel |= 0x02;
}
else
opt.usage_error();
}

} catch (NumberFormatException ex) {
System.err.println("Invalid Integer Arg");
} catch (SnmpException se) {
System.err.println(se);
System.exit(1);
}

if(values[DEBUG].equals("Set"))
receiver.setDebug(true);

if(userName != null)
receiver.createUserEntry(engineID.getBytes(),secLevel);

if (values[MIBS] != null) try { // load MIB files
System.err.println("Loading MIBs: "+values[MIBS]);
receiver.loadMibs(values[MIBS]);
System.err.println("Done.");
} catch (Exception ex) {
System.err.println("Error loading MIBs: "+ex);
}

// we need to instantiate a trap listener to listen for trap events
TrapListener listener = new TrapListener() {

// This method is called when trap is received by SnmpTrapReceiver
public void receivedTrap(TrapEvent trap) {
System.out.println("Got a trap from: "+trap.getRemoteHost());
// print PDU details
String DataReceived = ((SnmpTrapReceiver)trap.getSource()).getMibOperations().toString(trap.getTrapPDU());
System.out.println(((SnmpTrapReceiver)trap.getSource())
.getMibOperations().toString(trap.getTrapPDU()) );
System.out.println("DataReceived :::: " + DataReceived);
Pattern p = Pattern.compile("\\STRING.*?)\\.");
Matcher m = p.matcher(DataReceived);
m.find();
Data = m.group(1);
System.out.println(Data);

/*Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "snmp";
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver);
con = DriverManager.getConnection(url + db,"root","root");
Statement st = con.createStatement();
String sql = "INSERT INTO DataReceived(data) " +
"VALUES ('"+m.group(1)+"')";
try
{
int val = st.executeUpdate(sql);
System.out.println("1 row affected");
catch (SQLException s)
{
System.out.println("SQL statement is not executed!");
}
}*/
if( trap.getTrapPDU().getCommand() == SnmpAPI.TRP_REQ_MSG)
{
com.adventnet.snmp.mibs.MibTrap trapDefn = // get trap defn
trap.getTrapDefinition();

if (trapDefn != null) // print name and description
System.out.println("Trap Name: "+trapDefn.getName()+
"\nDescr: "+trapDefn.getDescription());
}
else if( trap.getTrapPDU().getCommand() == SnmpAPI.TRP2_REQ_MSG)
{

com.adventnet.snmp.mibs.MibNode notification = trap.getNotificationDefinition();
if(notification != null)
System.out.println("Notification Name: "+notification.getLabel()+
"\nObjects: "+ notification.getObjects()+
"\nStatus: "+ notification.getStatus()+
"\nDescr: "+notification.getDescription()+
"\nParent: "+ notification.getParent());

}
}
/*
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "snmp";
String driver = "com.mysql.jdbc.Driver";

Class.forName(driver);
con = DriverManager.getConnection(url + db,"root","root");
Statement st = con.createStatement();
String sql = "INSERT INTO DataReceived(data) " +
"VALUES ('"+Data+"')";

int val = st.executeUpdate(sql);
//System.out.println("1 row affected");*/
};

receiver.addTrapListener(listener);

System.out.println("Trap Receiver started at port "+receiver.getPort());
}


private static byte[] gethexValue(String value)
{
byte temp;
byte[] Key=new byte[value.length()/2 - 1];
String ss,str;

ss = value.substring(2);
for(int i = 0; i < ss.length(); i+=2)
{
str = ss.substring(i,i+2);
temp = (byte)Integer.parseInt(str,16);
Key[i/2] = temp;
}
return Key;
}

}

感谢Adv..

谨致问候,希马钱德拉·C.

最佳答案

从异常中:

Exception in thread "Thread-1" java.lang.IllegalStateException: Nomatch found
at java.util.regex.Matcher.group(Matcher.java:468)
atsnmpv3trapd.callback(snmpv3trapd.java:305)

代码:

String DataReceived = ...
...
Pattern p = Pattern.compile("\\STRING.*?)\\.");
Matcher m = p.matcher(DataReceived);
m.find();
Data = m.group(1);

异常在 m.group(1) 行引发。 错误No match found at java.util.regex.Matcher.group(...)只是说明接收到的字符串(变量DataReceived)确实存在与任何地方的正则表达式都不匹配。

现在我相信您的代码还有其他内容。看一下 "\\STRING.*?)\\." 字符串,它是以下正则表达式:

\STRING.*?)\.

由于出现不匹配的结束 ),这应该会产生错误。现在,即使您纠正了这一点,这个正则表达式也可能与您的想法不匹配。

第一个字符 \S 与字母 S 不匹配,而是字符类 \s 的否定版本(与空格)。这样,以 xTRING#TRING(依此类推)开头的字符串将与您的正则表达式匹配。

总结一下:

我相信您想要匹配序列 STRING 之后和字符 . 之前的字符串。为此,请使用正则表达式:

STRING(.*?)\.

因此模式为:

Pattern p = Pattern.compile("STRING(.*?)\\.");

现在,m.group(1); 将在匹配时起作用。

如果您想避免没有匹配项时出现异常,应检查 m.find() 的结果:

Pattern p = Pattern.compile("STRING(.*?)\\.");
Matcher m = p.matcher(DataReceived);
Data = null;
if (m.find()) {
Data = m.group(1);
}

注意:如果可以的话,请停止以大写开头变量名称。这不是 Java 约定。

关于java - 模式匹配器 IllegalStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15738275/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com