我不断出错:
2019-05-06 14:37:40,128 [EPI-TaskExecutor-1]错误 ScriptExecutionExceptionHandler.handleScriptError(31)-具有ID的脚本 [3e2fd082-62f3-46a2-8fca-71b1f9cef028]和标签[中断定义 脚本]报告错误::没有此类属性:类的getToHour: OutagePolicyScript。
Outages.xml文件可以,并且与outage.dtd文件一起放置在正确的位置。
import java.util.List;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import com.hp.opr.api.scripting.Event;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.lang3.ArrayUtils;
class OutagePolicyScript
{
Object syncObject = new Object();
final static String fileName = "/opt/HP/BSM/Temp/outages.xml"; // for Windows it will be: "d:/HPBSM/Temp/outages.xml";
final static Log s_log = LogFactory.getLog("com.hp.opr.epi.OutagePolicyScript");
List<OutageDefinition> outageDefinitions = new ArrayList<OutageDefinition>();
Thread loadXMLThread;
final boolean isSuppressEventsOrClose = true;
def init()
{
LoadOutagesFromXML r1 = new LoadOutagesFromXML();
loadXMLThread = new Thread(r1);
loadXMLThread.start();
s_log.debug("init finished");
}
def destroy()
{
s_log.debug("going to stop thread....");
loadXMLThread.interrupt();
}
def process(List<Event> events)
{
synchronized(syncObject) {
try
{
events.each {Event event ->
handleEventSuppressionIfNeeded(event, "EST");
//event.setTitle("Modified by CA/EPI: " + event.getTitle());
// always include following check for each event
if(Thread.interrupted())
throw new InterruptedException()
}
}
catch(InterruptedException e)
{
s_log.error("process of events interrupted", e);
}
}
}
private void handleEventSuppressionIfNeeded(Event event, String timezoneId)
{
// Calculate if event was received during the accepted time window.
Date timeRecieved = event.getTimeReceived();
Calendar cal = Calendar.getInstance();
TimeZone tz = TimeZone.getTimeZone(timezoneId);
if (tz != null)
cal = Calendar.getInstance(tz);
cal.setTime(timeRecieved);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int dow = cal.get(Calendar.DAY_OF_WEEK);
//event.addCustomAttribute("hour", Integer.toString(hour));
//event.addCustomAttribute("minute", Integer.toString(minute));
//event.addCustomAttribute("day of week", Integer.toString(dow));
// go over all the outage definitions, and compare event attributes to the rule
outageDefinitions.each {OutageDefinition outage ->
if (outage.getIsActive()) {
s_log.debug("Checking active rule: " + outage.getDescription());
// check if the event's day of week is one of the outage definition days. in case the rule cross day, reduce 1 for day of week
if (ArrayUtils.contains(outage.getDays(), dow) || (outage.getCrossDay() && ArrayUtils.contains(outage.getDays(), (dow == 1) ? 7 : dow-1 ))) {
// check if event hour and minute are inside rule's from/to
// convert all configurations to minutes
// if the rule cross a day, then add to "to" 24 hours in order to compare from <= event_time < to
// if the rule cross a day AND event hour < "from" then it means the event is in the next day and need to add 24 hours too
int eventTimeInMin = ((hour < outage.getFromHour() && outage.getCrossDay()) ? hour + 24 : hour) * 60 + minute;
int fromInMin = outage.getFromHour() * 60 + outage.getFromMinute();
int toInMin = (outage.getCrossDay() ? outage.getToHour() + 24 : outage.getToHour) * 60 + outage.getToMinute();
if (eventTimeInMin >= fromInMin && eventTimeInMin < toInMin) {
s_log.debug("event time is within this outage rule, proceed to compare event's attributes");
boolean foundMatch = true;
Set<String> attributeNames = outage.getAttributesList().keySet();
attributeNames.each {String name ->
boolean attMatchResult;
// at the moment, all comparisons are using "EQ"
switch (name) {
case "title" : attMatchResult = compareEventAttributeToOutageRuleForcontains("title", event.getTitle(), outage.getAttributesList().get(name)); break;
case "application" : attMatchResult = compareEventAttributeToOutageRule("application", event.getApplication(), outage.getAttributesList().get(name)); break;
case "object" : attMatchResult = compareEventAttributeToOutageRule("object", event.getObject(), outage.getAttributesList().get(name)); break;
case "category" : attMatchResult = compareEventAttributeToOutageRule("category", event.getCategory(), outage.getAttributesList().get(name)); break;
case "subcategory" : attMatchResult = compareEventAttributeToOutageRule("subcategory", event.getSubCategory(), outage.getAttributesList().get(name)); break;
case "nodeHint" : attMatchResult = compareEventAttributeToOutageRuleForcontains("nodeHint", event.getNodeHints().getHint(), outage.getAttributesList().get(name)); break;
default : s_log.error("attribute name [" + name + "] from outages.xml is not supported");
}
s_log.debug("result for attribute [" + name + "] is: " + attMatchResult);
foundMatch &= attMatchResult;
}
s_log.debug("result after processing all attributes in the rule is: " + foundMatch);
if (foundMatch) {
if (isSuppressEventsOrClose)
event.addCustomAttribute("SuppressDueToOutageRule", outage.getDescription());
else
event.setState(LifecycleState.CLOSED);
}
}
else {
s_log.debug("Current rule doesnt match for the event's time, this rule will be skipped");
}
}
else {
s_log.debug("Current rule doesnt match for the event's day, this rule will be skipped");
}
}
}
}
private boolean compareEventAttributeToOutageRule(String eventAttName, String eventAttValue, Set<String> ruleValues)
{
if (ruleValues.contains(eventAttValue)) {
s_log.debug("found match on attribute [" + eventAttName + "], attribute value=" + eventAttValue);
return true;
}
// else, no match
s_log.debug("no match for attribute " + eventAttName);
return false;
}
private boolean compareEventAttributeToOutageRuleForcontains(String eventAttName, String eventAttValue, Set<String> ruleValues)
{
Iterator<String> itr = ruleValues.iterator();
while (itr.hasNext()) {
if (eventAttValue.indexOf(itr.next()) != -1) { // check if the event attribute contains the rule's value
s_log.debug("found match on attribute [" + eventAttName + "], attribute value=" + eventAttValue);
return true;
}
}
// else, no match
s_log.debug("no match for attribute " + eventAttName);
return false;
}
class LoadOutagesFromXML implements Runnable
{
long lastModifiedTime = -1;
public void run()
{
while (!Thread.interrupted()) {
s_log.debug("in running.... current time: " + new Date());
// lock the sync object
synchronized(syncObject) {
long before = System.currentTimeMillis();
readOutageFile();
long after = System.currentTimeMillis();
s_log.debug("Loading outages definitions from XML took [" + (after - before) + "] ms.");
}
Thread.sleep(60000); // 60 seconds
}
s_log.debug("thread interrupted....");
}
private void readOutageFile()
{
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File f = new File(fileName);
if (f.lastModified() == lastModifiedTime) {
// the file wasnt changed, no need to reload file
s_log.debug("file LastModifiedTime didn't change, no need to reload configuration");
return;
}
// otherwise, clear previous results and reload XML file
outageDefinitions.clear();
s_log.debug("going to load outage.xml");
Document doc = db.parse(f);
NodeList outages = doc.getElementsByTagName("outage");
for (int i=0 ; i<outages.getLength() ; ++i) {
s_log.debug("handle outage: " + Integer.toString(i));
// going to handle specific outage definition
Element aOutage = (Element)outages.item(i);
Element aTimeWindow = (Element)(aOutage.getElementsByTagName("timeWindow").item(0));
outageDefinitions.add(new OutageDefinition(aOutage.getAttribute("description"),
aOutage.getAttribute("isEnabled"),
aTimeWindow.getElementsByTagName("days").item(0).getTextContent(),
parseIntFromStr(aTimeWindow.getElementsByTagName("from").item(0).getTextContent(), true),
parseIntFromStr(aTimeWindow.getElementsByTagName("from").item(0).getTextContent(), false),
parseIntFromStr(aTimeWindow.getElementsByTagName("to").item(0).getTextContent(), true),
parseIntFromStr(aTimeWindow.getElementsByTagName("to").item(0).getTextContent(), false),
parseAttributesFromXML((Element)aOutage.getElementsByTagName("eventsFilter").item(0))));
}
lastModifiedTime = f.lastModified();
s_log.debug("Going to keep lastModifiedTime as " + lastModifiedTime);
}
catch (Exception e) {
s_log.error("caught exception during parsing of outage.xml", e);
lastModifiedTime = -1;
}
}
private int parseIntFromStr(String str, boolean isHour)
{
String[] array = str.trim().split(":");
if (array.length != 2) {
s_log.debug("Bad time format, expect HH:MM format but recieved: " + str);
return -1;
}
if (isHour)
return Integer.parseInt(array[0]);
else
return Integer.parseInt(array[1]);
}
private Map<String, Set<String>> parseAttributesFromXML(Element eventsFilter)
{
Map<String, Set<String>> result = new HashMap<String, Set<String>>();
NodeList eventAttributes = eventsFilter.getElementsByTagName("eventAttribute");
for (int i=0 ; i<eventAttributes.getLength() ; ++i) {
NodeList attributeValues = eventAttributes.item(i).getElementsByTagName("value");
Set<String> values = new HashSet<String>(attributeValues.getLength());
for (int j=0 ; j<attributeValues.getLength() ; j++) {
values.add(attributeValues.item(j).getTextContent());
}
result.put(eventAttributes.item(i).getAttribute("name"), values);
}
return result;
}
}
class OutageDefinition
{
String description;
boolean isActive;
int[] days;
int fromHour;
int fromMinute;
int toHour;
int toMinute;
boolean crossDay;
Map<String, Set<String>> attributesList;
public OutageDefinition(String desc, String active, String outageDays, int oFromHour, int oFromMinute, int oToHour, int oToMinute, Map<String, Set<String>> oAttributes) {
this.description = desc;
this.isActive = Boolean.parseBoolean(active);
this.fromHour = oFromHour;
this.fromMinute = oFromMinute;
this.toHour = oToHour;
this.toMinute = oToMinute;
this.attributesList = oAttributes;
this.crossDay = false;
// check if time cross a day
if (this.fromHour > this.toHour) {
s_log.debug("in rule [" + this.description + "] found time condition that crosses midnight, adjust toHour accordingly");
this.crossDay = true;
}
this.days = getDaysFromString(outageDays);
}
private int[] getDaysFromString(String str)
{
String[] days = str.trim().split(",");
int[] result = new int[days.length];
for (int i=0 ; i<days.length ; ++i) {
switch (days[i]) {
case "Sunday" : result[i] = 1; break;
case "Monday" : result[i] = 2; break;
case "Tuesday" : result[i] = 3; break;
case "Wednesday" : result[i] = 4; break;
case "Thursday" : result[i] = 5; break;
case "Friday" : result[i] = 6; break;
case "Saturday" : result[i] = 7; break;
default : result[i] = -1; break;
}
}
return result;
}
public String getDescription() {
return description;
}
public boolean getIsActive() {
return isActive;
}
public int[] getDays() {
return days;
}
public int getFromHour() {
return fromHour;
}
public int getFromMinute() {
return fromMinute;
}
public int getToHour() {
return toHour;
}
public int getToMinute() {
return toMinute;
}
public Map<String, Set<String>> getAttributesList() {
return attributesList;
}
public boolean getCrossDay() {
return crossDay;
}
}
}
答案 0 :(得分:0)
仔细观察这一行。您必须调用一个方法(outage.getToHour()
)或访问一个属性(outage.getToHour
),但是在这里您必须做这两种事情。选择正确的东西
int toInMin = (outage.getCrossDay() ? outage.getToHour() + 24 : outage.getToHour) * 60 + outage.getToMinute();