当前位置:我的异常网» Linux/Unix » jsp页面调用哪个Linux的shell 脚本步骤
jsp页面调用哪个Linux的shell 脚本步骤
www.myexceptions.net 网友分享于:2015-08-26 浏览:191次
jsp页面调用哪个Linux的shell 脚本方法
import java.io.*;
import java.util.*;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.×;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hyperic.dao.DAOFactory;
import org.hyperic.hq.appdef.shared.AppdefEntityID;
import org.hyperic.hq.application.HQApp;
import org.hyperic.hq.authz.server.session.AuthzSubject;
import org.hyperic.hq.authz.server.session.AuthzSubjectManagerEJBImpl;
import org.hyperic.hq.authz.server.session.Resource;
import org.hyperic.hq.authz.server.session.ResourceDAO;
import org.hyperic.hq.authz.shared.AuthzSubjectManagerLocal;
import org.hyperic.hq.bizapp.shared.action.EmailActionConfig;
import org.hyperic.hq.escalation.server.session.Escalatable;
import org.hyperic.hq.escalation.server.session.EscalationStateChange;
import org.hyperic.hq.escalation.server.session.PerformsEscalations;
import org.hyperic.hq.events.ActionExecuteException;
import org.hyperic.hq.events.ActionExecutionInfo;
import org.hyperic.hq.events.ActionInterface;
import org.hyperic.hq.events.AlertDefinitionInterface;
import org.hyperic.hq.events.AlertInterface;
import org.hyperic.hq.events.InvalidActionDataException;
import org.hyperic.hq.events.Notify;
import org.hyperic.hq.hqu.rendit.RenditServer;
import org.hyperic.hq.measurement.MeasurementNotFoundException;
import org.hyperic.util.config.ConfigResponse;
public class EmailAction extends EmailActionConfig
implements ActionInterface, Notify
{
public static final String RES_NAME_HOLDER = "RES_NAME_REPL";
public static final String RES_DESC_HOLDER = "RES_DESC_REPL";
protected static String baseUrl = null;
public static boolean smsPro = false;
protected String phone = "";
protected String mes = "";
protected String rsna = "";
protected String alna = "";
protected String date = "";
private Log _log = LogFactory.getLog(EmailAction.class);
private AuthzSubjectManagerLocal subjMan;
public EmailAction() {
}
protected AuthzSubjectManagerLocal getSubjMan() {
if (subjMan == null) {
subjMan = AuthzSubjectManagerEJBImpl.getOne();
}
return subjMan;
}
private String renderTemplate(String filename, Map params) {
File templateDir = new File(HQApp.getInstance().getResourceDir(),
"alertTemplates");
File templateFile = new File(templateDir, filename);
StringWriter output = new StringWriter();
try {
RenditServer.getInstance().renderTemplate(templateFile, params,
output);
if (_log.isDebugEnabled())
_log.debug("Template rendered\n" + output.toString());
} catch(Exception e) {
_log.warn("Unable to render template", e);
}
return output.toString();
}
private String createSubject(AlertDefinitionInterface alertdef,
AlertInterface alert, Resource resource,
String status) {
Map params = new HashMap();
params.put("resource", resource);
params.put("alertDef", alertdef);
params.put("alert", alert);
params.put("status", status);
params.put("isSms", new Boolean(isSms()));
return renderTemplate("subject.gsp", params);
}
private String createText(AlertDefinitionInterface alertdef,
ActionExecutionInfo info, Resource resource,
AlertInterface alert, String templateName,
AuthzSubject user)
throws MeasurementNotFoundException
{
Map params = new HashMap();
params.put("alertDef", alertdef);
params.put("alert", alert);
params.put("action", info);
params.put("resource", resource);
params.put("user", user);
return renderTemplate(templateName, params);
}
private AppdefEntityID getResource(AlertDefinitionInterface def) {
return new AppdefEntityID(def.getAppdefType(), def.getAppdefId());
}
public void smsText(){
String tmp = "";
int i = 0x0a;
String sp = ""+(char)i;
tmp = mes.substring(mes.indexOf("Resource Name:")+14);
rsna = tmp.substring(0,tmp.indexOf(sp)).trim();
//rsna = mes.substring(mes.indexOf("Resource Name:")+14,mes.indexOf("- Alert Name")).trim();
tmp = mes.substring(mes.indexOf("Alert Name:")+11);
alna = tmp.substring(0,tmp.indexOf(sp)).trim();
//alna = mes.substring(mes.indexOf("Alert Name:")+11,mes.indexOf("- Alert Description")).trim();
tmp = mes.substring(mes.indexOf("Alert Date / Time:")+18);
date = tmp.substring(0,tmp.indexOf(sp)).trim();
//date = mes.substring(mes.indexOf("Alert Date / Time:")+18,mes.indexOf("- Triggering")).trim();
//return rsna+""+alna+""+date;
}
public void alertFile(String t){
FileOutputStream out = null;
PrintStream p = null;
try {
java.util.Date d=new java.util.Date();
java.text.SimpleDateFormat s= new java.text.SimpleDateFormat("yyyy-MM-dd HH;mm;ss");
String dateStr = s.format(d);
String fn = "c:\\sms\\alerts\\sms_Alert_"+dateStr+".log";
File f = new File(fn);
int i =0 ;
while(f.exists()){
i++;
fn = "c:\\sms\\alerts\\sms_Alert_"+dateStr+"_"+i+".log";
f = new File(fn);
}
out = new FileOutputStream(fn);
p = new PrintStream(out);
}catch (Exception e) {
}
p.println(t);
try{
p.close();
out.close();
}catch (Exception e) {
}
}
public void outPutAlertSms(){
//FileInputStream in;
//PrintStream p;
try {
FileReader fr = new FileReader("c:\\sms\\smsConfig.txt");
BufferedReader br = new BufferedReader(fr);
String JAVA_path = br.readLine();
JAVA_path = JAVA_path.substring(JAVA_path.indexOf("=")+1);
//in = new FileInputStream("c:\\sms\\smsConfig.txt");
// Connect print stream to the output stream
//p = new PrintStream( out );
smsText();
/*----old sms code
//set the alert content
String alert = phone+"
"+rsna+"
"+alna+"
"+date;
alert = alert.replace(" ","");
//p.println ("the following sms had sent ");
//p.println("the Alert Resource Name:"+rsna);
//p.println("the Alert Name:"+alna);
//p.println("the Alert date:"+date);
//p.println("the Alert:"+mes);
*/
//----new sms code
String alert = "Phone Numbers="+phone+"&"+"Resource Name="+rsna+"&"+"Alert Name="+alna+"&"+"Alert Date / Time="+date;
alertFile(alert);
//get the cmd dir envirment
//生成一个临时文件来确定当前的工作路径,因为tomcat当时在做项目的时候混乱的找不到服务器的路径是什么,用这种方式解决 mark
File f = new File("path.txt");
String path = f.getAbsolutePath();
path = path.substring(0,path.indexOf("path.txt"));
File dir = new File(path);
//set cmd
//String cmd = JAVA_path+"\\java -classpath c:\\sms SmsCenter "+alert;
//new sms code
String cmd = JAVA_path+"\\java -classpath c:\\sms SmsCenter good";
//path += "sms";
//p.println(cmd);
//call the sms center, set the alert
//Process prs = Runtime.getRuntime().exec(cmd,null,dir);
//new sms code
//Process prs = Runtime.getRuntime().exec(cmd,null,dir);
br.close();
fr.close();
//p.println(cmd);//print the cmd content
//p.close();
//out.close();
} catch (Exception e) {
_log.warn("output sms.log error"+mes, e);
}
}
public String execute(AlertInterface alert, ActionExecutionInfo info)
throws ActionExecuteException
{
try {
Map addrs = lookupEmailAddr();
if (addrs.isEmpty()) {
return "No valid users or emails found to send alert";
}
EmailFilter filter = new EmailFilter();
AlertDefinitionInterface alertDef =
alert.getAlertDefinitionInterface();
AppdefEntityID appEnt = getResource(alertDef);
ResourceDAO rDao = new ResourceDAO(DAOFactory.getDAOFactory());
Resource resource = rDao.findByInstanceId(appEnt.getAuthzTypeId(),
appEnt.getId());
String[] body = new String[addrs.size()];
String[] htmlBody = new String[addrs.size()];
EmailRecipient[] to = (EmailRecipient[])
addrs.keySet().toArray(new EmailRecipient[addrs.size()]);
for (int i = 0; i < to.length; i++) {
AuthzSubject user = (AuthzSubject) addrs.get(to[i]);
if (to[i].useHtml()) {
htmlBody[i] = createText(alertDef, info, resource, alert,
"html_email.gsp", user);
}
body[i] = createText(alertDef, info, resource, alert,
isSms() ? "sms_email.gsp" :
"text_email.gsp", user);
mes += ":"+body[i];
}
filter.sendAlert(appEnt, to,
createSubject(alertDef, alert, resource, ""),
body, htmlBody, alertDef.getPriority(),
alertDef.isNotifyFiltered());
outPutAlertSms();
StringBuffer result = getLog(to);
return result.toString();
} catch (Exception e) {
throw new ActionExecuteException(e);
}
}
protected StringBuffer getLog(EmailRecipient[] to) {
StringBuffer result = new StringBuffer(isSms() ? "SMS" : "Notified");
// XXX: Should get this strings into a resource file
switch (getType()) {
case TYPE_USERS :
result.append(" users: ");
break;
default :
case TYPE_EMAILS :
result.append(": ");
break;
}
for (int i = 0; i < to.length; i++) {
result.append(to[i].getAddress().getPersonal());
if (i < to.length - 1) {
result.append(", ");
}
}
return result;
}
protected Map lookupEmailAddr()
throws ActionExecuteException
{
// First, look up the addresses
int i = 0;
HashSet prevRecipients = new HashSet();
Map validRecipients = new HashMap();
for (Iterator it = getUsers().iterator(); it.hasNext(); i++) {
try {
InternetAddress addr;
boolean useHtml = false;
AuthzSubject who = null;
switch (getType()) {
case TYPE_USERS:
Integer uid = (Integer) it.next();
who = getSubjMan().getSubjectById(uid);
if (who == null) {
_log.warn("User not found: " + uid);
continue;
}
phone += who.getSMSAddress()+"|";
if (isSms()) {
addr = new InternetAddress(who.getSMSAddress());
} else {
addr = new InternetAddress(who.getEmailAddress());
}
addr.setPersonal(who.getName());
useHtml = isSms() ? false : who.isHtmlEmail();
break;
default:
case TYPE_EMAILS:
addr = new InternetAddress((String) it.next(), true);
addr.setPersonal(addr.getAddress());
break;
}
// Don't send duplicate notifications
if (prevRecipients.add(addr)) {
validRecipients.put(new EmailRecipient(addr, useHtml), who);
}
} catch (AddressException e) {
_log.warn("Mail address invalid", e);
continue;
} catch (UnsupportedEncodingException e) {
_log.warn("Username encoding error", e);
continue;
} catch (Exception e) {
_log.warn("Email lookup failed");
_log.debug("Email lookup failed", e);
continue;
}
}
return validRecipients;
}
public void setParentActionConfig(AppdefEntityID ent, ConfigResponse cfg)
throws InvalidActionDataException
{
init(cfg);
}
public void send(Escalatable alert, EscalationStateChange change,
String message, Set notified)
throws ActionExecuteException
{
PerformsEscalations def = alert.getDefinition();
Map addrs = lookupEmailAddr();
EmailFilter filter = new EmailFilter();
for (Iterator it = addrs.entrySet().iterator(); it.hasNext(); ) {
Map.Entry entry = (Map.Entry) it.next();
EmailRecipient rec = (EmailRecipient) entry.getKey();
// Don't notify again if already notified
if (notified.contains(rec.getAddress())) {
it.remove();
continue;
}
rec.setHtml(false);
notified.add(rec.getAddress());
}
AlertDefinitionInterface defInfo = def.getDefinitionInfo();
String[] messages = new String[addrs.size()];
Arrays.fill(messages, message);
EmailRecipient[] to = (EmailRecipient[])
addrs.keySet().toArray(new EmailRecipient[addrs.size()]);
AppdefEntityID appEnt = getResource(defInfo);
ResourceDAO rDao = new ResourceDAO(DAOFactory.getDAOFactory());
Resource resource = rDao.findByInstanceId(appEnt.getAuthzTypeId(),
appEnt.getId());
filter.sendAlert(getResource(defInfo), to,
createSubject(defInfo, alert.getAlertInfo(), resource,
change.getDescription()),
messages, messages, defInfo.getPriority(), false);
//outPutAlertFile();
}
}
文章评论