Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Hi,
- I have a piece of code in C#. It reads some services in windows and logs it into a file. Can we do the same thing in Java. Please Help! Its urgent.
- I am pasting the code.
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Net.Mail;
- using System.ServiceProcess;
- using System.Text;
- using Microsoft.Win32;
- namespace MineStarAvailabilityMonitor
- {
- public class Monitor
- {
- private int year;
- private int month;
- private string filename;
- private int mineTrackingDownCount = 0;
- private int iAssignmentServerDownCount = 0;
- private int cycleGeneratorDownCount = 0;
- private static int MAX_DOWN_COUNT = 4;
- private Properties props, custProps;
- private string fileRoot;
- private string systemName;
- private bool writeHeader;
- private string overridesFilename;
- private string mamFilename;
- private DayOfWeek dayOfWeek;
- private int day;
- public Monitor(string systemName, string file)
- {
- year = DateTime.Now.Year;
- month = DateTime.Now.Month;
- dayOfWeek = DateTime.Now.DayOfWeek;
- day = DateTime.Now.Day;
- if (systemName == null)
- {
- this.systemName = "main";
- }
- else
- this.systemName = systemName;
- LoadConfig(file);
- filename = GetFilename(this.systemName);
- }
- public void CheckJVM(object stateObject)
- {
- ServiceController svcCtrl;
- ServiceControllerStatus srvStatus;
- // Always update month and year to make sure we get the monthly roll over of MAM log file
- var newyear = DateTime.Now.Year;
- var newmonth = DateTime.Now.Month;
- var newDay = DateTime.Now.Day;
- var newDayOfWeek = DateTime.Now.DayOfWeek;
- if (newmonth != month)
- {
- // Log is about to change so send it before creating new one
- generateEmail("MAM - " + custProps.get("/MineStar.properties._CUSTCODE", "DEFAULT"), "Attached is the current MAM log", true);
- year = newyear;
- month = newmonth;
- day = newDay;
- dayOfWeek = newDayOfWeek;
- GetFilename(systemName);
- }
- // Start by checking to see if it's a new day or week
- if (day != newDay)
- {
- // First update day
- day = newDay;
- // Send alive message
- generateEmail("MAM - " + custProps.get("/MineStar.properties._CUSTCODE", "DEFAULT"),
- "MAM is alive at " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString(),
- false);
- }
- if (newDayOfWeek != dayOfWeek && newDayOfWeek == DayOfWeek.Sunday)
- {
- dayOfWeek = newDayOfWeek;
- // Send log
- generateEmail("MAM - " + custProps.get("/MineStar.properties._CUSTCODE", "DEFAULT"), "Attached is the current MAM log", true);
- }
- if (!System.IO.File.Exists(mamFilename))
- writeHeader = true;
- else
- writeHeader = false;
- StreamWriter sw = new StreamWriter(mamFilename, true);
- if (writeHeader)
- WriteFileHeader(sw);
- // This is where we will look for the state of the required services
- // M*MineTracking, M*IAssignmentServer, M*CycleGenerator
- StringBuilder sb = new StringBuilder();
- //ServiceController[] scServices;
- //scServices = ServiceController.GetServices();
- Process proc = Process.GetCurrentProcess();
- //writeSpeedo(sw, proc);
- proc.Dispose();
- if (!IsInstalled("M*MineTracking"))
- {
- sw.WriteLine("Unable to locate the service M*MineTracking. Possible causes:");
- sw.WriteLine("MineStar is not installed");
- sw.WriteLine("MineStar is not configured to run as a service");
- sw.WriteLine("This is a non standard install");
- sw.Flush();
- sw.Close();
- return;
- }
- svcCtrl = new ServiceController("M*MineTracking");
- srvStatus = svcCtrl.Status;
- if (srvStatus != ServiceControllerStatus.Running)
- {
- mineTrackingDownCount++;
- }
- else
- {
- mineTrackingDownCount = 0;
- }
- svcCtrl.Dispose();
- sb.Append(DateTime.Now.ToLongDateString());
- sb.Append(" ");
- sb.Append(DateTime.Now.ToLongTimeString());
- sb.Append(" M*MineTracking");
- sb.Append("=");
- sb.Append(srvStatus);
- sb.Append(",");
- if (IsInstalled("M*IAssignmentServer"))
- {
- svcCtrl = new ServiceController("M*IAssignmentServer");
- srvStatus = svcCtrl.Status;
- if (srvStatus != ServiceControllerStatus.Running)
- {
- iAssignmentServerDownCount++;
- }
- else
- {
- iAssignmentServerDownCount = 0;
- }
- sb.Append("M*IAssignmentServer");
- sb.Append("=");
- sb.Append(srvStatus);
- sb.Append(",");
- svcCtrl.Dispose();
- }
- if (IsInstalled("M*CycleGenerator"))
- {
- svcCtrl = new ServiceController("M*CycleGenerator");
- srvStatus = svcCtrl.Status;
- if (srvStatus != ServiceControllerStatus.Running)
- {
- cycleGeneratorDownCount++;
- }
- else
- {
- cycleGeneratorDownCount = 0;
- }
- sb.Append("M*CycleGenerator");
- sb.Append("=");
- sb.Append(srvStatus);
- sw.WriteLine(sb.ToString());
- svcCtrl.Dispose();
- }
- sw.Flush();
- sw.Close();
- if (iAssignmentServerDownCount >= MAX_DOWN_COUNT || cycleGeneratorDownCount >= MAX_DOWN_COUNT || mineTrackingDownCount >= MAX_DOWN_COUNT)
- {
- // Send email
- string body = "MAM has detected a potential failure on " +
- System.Windows.Forms.SystemInformation.ComputerName +
- "\n This is a system generated email\n Please contact the MineStar System Administrator";
- generateEmail("MineStar Availability Monitor - ALERT", body, true);
- mineTrackingDownCount = 0;
- iAssignmentServerDownCount = 0;
- cycleGeneratorDownCount = 0;
- sw = new StreamWriter(mamFilename, true);
- sw.WriteLine(DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + " Alert email sent");
- sw.Flush();
- sw.Close();
- }
- }
- private void writeSpeedo(StreamWriter sw, Process proc)
- {
- sw.Write(" **************** ");
- sw.Write("Peak Working Set = " + proc.PeakWorkingSet64);
- sw.Write(" Working Set = " + proc.WorkingSet64);
- sw.Write(" Handle Count = " + proc.HandleCount);
- sw.Write(" Private Memory Size = " + proc.PrivateMemorySize64);
- sw.WriteLine(" ****************");
- }
- private static bool IsInstalled(string serviceName)
- {
- using (ServiceController controller =
- new ServiceController(serviceName))
- {
- try
- {
- ServiceControllerStatus status = controller.Status;
- }
- catch
- {
- controller.Dispose();
- return false;
- }
- controller.Dispose();
- return true;
- }
- }
- private void WriteFileHeader(StreamWriter sw)
- {
- string line1, line2, line3;
- line1 = custProps.get("/MineStar.properties._CUSTCODE", "DEFAULT");
- line2 = custProps.get("/MineStar.properties._CUSTSITE", "DEFAULT");
- line3 = custProps.get("/Versions.properties.CURRENT_BUILD", "UNKNOWN");
- sw.Write("******* ");
- sw.Write(line1);
- sw.WriteLine(" ********");
- sw.Write("******* ");
- sw.Write(line2);
- sw.WriteLine(" ********");
- sw.Write("******* ");
- sw.Write(line3);
- sw.WriteLine(" ********");
- }
- public string GetFilename(String system)
- {
- fileRoot = props.get("MSTAR_SYSTEMS");
- mamFilename = fileRoot + "\\" + system + "\\logs\\monitoring\\MAM" + year + month + ".txt";
- overridesFilename = fileRoot + "\\" + system + "\\config\\MineStar.overrides";
- custProps = new Properties(overridesFilename);
- return fileRoot;
- }
- public string GetOverridesFilename()
- {
- return overridesFilename;
- }
- private void generateEmail(string subject, string body, bool attachLog)
- {
- // Check if email enabled
- EventLog.WriteEntry("MAM", "Check if email enabled");
- string strEmailEnabled = custProps.get("/MineStar.properties._EMAIL_ENABLED_EXT", "true");
- bool emailEnabled = Convert.ToBoolean(strEmailEnabled);
- if (!emailEnabled)
- {
- EventLog.WriteEntry("MAM", "Email is NOT enabled");
- StreamWriter sw = new StreamWriter(mamFilename, true);
- sw.WriteLine("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
- sw.WriteLine("Email not enabled so the following message could not be sent");
- sw.WriteLine(subject);
- sw.WriteLine(body);
- sw.WriteLine("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
- sw.Flush();
- sw.Close();
- return;
- }
- EventLog.WriteEntry("MAM", "Email enabled");
- // Get properties from MineStar.Overrides
- var smtpServ = custProps.get("/MineStar.properties._EMAILSERVER", "smtp.gmail.com");
- var smtpPort = custProps.get("/MineStar.properties._EMAILPORT", "587");
- EventLog.WriteEntry("MAM", "Email enabled - authenticated SMTP");
- // Lets do authenticated SMTP
- MailMessage mail = new MailMessage();
- SmtpClient smtpServer = new SmtpClient(smtpServ, Convert.ToInt16(smtpPort));
- EventLog.WriteEntry("MAM", "Email enabled - get credentials");
- var emailUser = custProps.get("/MineStar.properties._EMAILUSER", "empty");
- var emailPass = custProps.get("/MineStar.properties._EMAILPASSWORD", "empty");
- EventLog.WriteEntry("MAM", "Email enabled - set credentials");
- try
- {
- smtpServer.Credentials = new System.Net.NetworkCredential(emailUser, emailPass);
- }
- catch (SystemException excep)
- {
- EventLog.WriteEntry("MAM", excep.Message);
- }
- smtpServer.EnableSsl = true;
- EventLog.WriteEntry("MAM", "Email enabled - set sender");
- mail.From = new MailAddress(custProps.get("/MineStar.properties._EMAILUSER", ""));
- EventLog.WriteEntry("MAM", "Email enabled - set reciever");
- mail.To.Add(custProps.get("/MineStar.properties._EMAILRECIPIENT", ""));
- //mail.Subject = "MineStar Availability Monitor - ALERT";
- mail.Subject = subject;
- //mail.Body = "MAM has detected a potential failure on " + System.Windows.Forms.SystemInformation.ComputerName + "\nThis is a system generated email\nPlease contact the MineStar System Administrator";
- mail.Body = body;
- if (attachLog)
- {
- EventLog.WriteEntry("MAM", "Email enabled - attach log");
- System.Net.Mail.Attachment attachment;
- attachment = new Attachment(mamFilename);
- mail.Attachments.Add(attachment);
- }
- try
- {
- EventLog.WriteEntry("MAM", "Email enabled - send mail");
- smtpServer.Send(mail);
- }
- catch (System.Net.Mail.SmtpException)
- {
- StreamWriter sw = new StreamWriter(mamFilename, true);
- sw.WriteLine("Failed to send email ALERT");
- sw.Flush();
- sw.Close();
- }
- mail.Dispose();
- //smtpServer.Dispose();
- //smtpServer = null;
- }
- internal void LoadConfig(string file)
- {
- props = new Properties(file);
- }
- }
- }
- @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Configuration.Install;
- using System.Linq;
- using System.ServiceProcess;
- using System.Text;
- namespace MineStarAvailabilityMonitor
- {
- static class Program
- {
- /// <summary>
- /// The main entry point for the application.
- /// </summary>
- static void Main(string[] args)
- {
- if (args.Length != 0)
- {
- switch (args[0])
- {
- case "-install":
- Console.WriteLine("Attempting to install MineStar Application Monitor on this machine.\n Administrator privilage required");
- InstallService();
- return;
- case "-uninstall":
- UninstallService();
- return;
- default:
- // Must be normal args
- break;
- }
- }
- ServiceBase[] ServicesToRun;
- ServicesToRun = new ServiceBase[]
- {
- new Service1()
- };
- ServiceBase.Run(ServicesToRun);
- }
- private static void InstallService()
- {
- if (IsInstalled()) return;
- try
- {
- using (AssemblyInstaller installer = GetInstaller())
- {
- IDictionary state = new Hashtable();
- try
- {
- installer.Install(state);
- installer.Commit(state);
- }
- catch
- {
- try
- {
- installer.Rollback(state);
- }
- catch { }
- throw;
- }
- }
- }
- catch
- {
- throw;
- }
- }
- private static void UninstallService()
- {
- if (!IsInstalled()) return;
- try
- {
- using (AssemblyInstaller installer = GetInstaller())
- {
- IDictionary state = new Hashtable();
- try
- {
- installer.Uninstall(state);
- }
- catch
- {
- throw;
- }
- }
- }
- catch
- {
- throw;
- }
- }
- private static bool IsInstalled()
- {
- using (ServiceController controller =
- new ServiceController("MAM"))
- {
- try
- {
- ServiceControllerStatus status = controller.Status;
- }
- catch
- {
- return false;
- }
- return true;
- }
- }
- private static AssemblyInstaller GetInstaller()
- {
- AssemblyInstaller installer = new AssemblyInstaller(typeof(Service1).Assembly, null);
- installer.UseNewContext = true;
- return installer;
- }
- }
- }
- @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Configuration.Install;
- using System.Linq;
- namespace MineStarAvailabilityMonitor
- {
- [RunInstaller(true)]
- public partial class ProjectInstaller : System.Configuration.Install.Installer
- {
- public ProjectInstaller()
- {
- InitializeComponent();
- }
- private void serviceProcessInstaller1_AfterInstall(object sender, InstallEventArgs e)
- {
- }
- }
- }
- @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
- namespace MineStarAvailabilityMonitor
- {
- partial class ProjectInstaller
- {
- /// <summary>
- /// Required designer variable.
- /// </summary>
- private System.ComponentModel.IContainer components = null;
- /// <summary>
- /// Clean up any resources being used.
- /// </summary>
- /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
- protected override void Dispose(bool disposing)
- {
- if (disposing && (components != null))
- {
- components.Dispose();
- }
- base.Dispose(disposing);
- }
- #region Component Designer generated code
- /// <summary>
- /// Required method for Designer support - do not modify
- /// the contents of this method with the code editor.
- /// </summary>
- private void InitializeComponent()
- {
- this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
- this.MAMServiceInstaller = new System.ServiceProcess.ServiceInstaller();
- //
- // serviceProcessInstaller1
- //
- this.serviceProcessInstaller1.Password = null;
- this.serviceProcessInstaller1.Username = null;
- this.serviceProcessInstaller1.AfterInstall += new System.Configuration.Install.InstallEventHandler(this.serviceProcessInstaller1_AfterInstall);
- //
- // MAMServiceInstaller
- //
- this.MAMServiceInstaller.Description = "MineStar Availability Monitoring Service";
- this.MAMServiceInstaller.DisplayName = "MineStar Availability Monitor";
- this.MAMServiceInstaller.ServiceName = "MAM";
- this.MAMServiceInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
- //
- // ProjectInstaller
- //
- this.Installers.AddRange(new System.Configuration.Install.Installer[] {
- this.serviceProcessInstaller1,
- this.MAMServiceInstaller});
- }
- #endregion
- private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
- private System.ServiceProcess.ServiceInstaller MAMServiceInstaller;
- }
- }
- @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace MineStarAvailabilityMonitor
- {
- public class Properties
- {
- private Dictionary<String, String> list;
- private String filename;
- public Properties(String file)
- {
- reload(file);
- }
- public String get(String field, String defValue)
- {
- return (get(field) == null) ? (defValue) : (get(field));
- }
- public String get(String field)
- {
- return (list.ContainsKey(field)) ? (list[field]) : (null);
- }
- public void set(String field, Object value)
- {
- if (!list.ContainsKey(field))
- list.Add(field, value.ToString());
- else
- list[field] = value.ToString();
- }
- public void Save()
- {
- Save(this.filename);
- }
- public void Save(String filename)
- {
- this.filename = filename;
- if (!System.IO.File.Exists(filename))
- System.IO.File.Create(filename);
- System.IO.StreamWriter file = new System.IO.StreamWriter(filename);
- foreach (String prop in list.Keys.ToArray())
- if (!String.IsNullOrEmpty(list[prop]))
- file.WriteLine(prop + "=" + list[prop]);
- file.Close();
- }
- public void reload()
- {
- reload(this.filename);
- }
- public void reload(String filename)
- {
- this.filename = filename;
- list = new Dictionary<String, String>();
- if (System.IO.File.Exists(filename))
- loadFromFile(filename);
- else
- System.IO.File.Create(filename);
- }
- private void loadFromFile(String file)
- {
- foreach (String line in System.IO.File.ReadAllLines(file))
- {
- if ((!String.IsNullOrEmpty(line)) &&
- (!line.StartsWith(";")) &&
- (!line.StartsWith("#")) &&
- (!line.StartsWith("'")) &&
- (line.Contains('=')))
- {
- int index = line.IndexOf('=');
- String key = line.Substring(0, index).Trim();
- String value = line.Substring(index + 1).Trim();
- if ((value.StartsWith("\"") && value.EndsWith("\"")) ||
- (value.StartsWith("'") && value.EndsWith("'")))
- {
- value = value.Substring(1, value.Length - 2);
- }
- try
- {
- //ignore dublicates
- list.Add(key, value);
- }
- catch { }
- }
- }
- }
- }
- }
- @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Diagnostics;
- using System.Linq;
- using System.Runtime.InteropServices;
- using System.ServiceProcess;
- using System.Text;
- using System.Threading;
- namespace MineStarAvailabilityMonitor
- {
- [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
- public struct SERVICE_STATUS
- {
- public int serviceType;
- public int currentState;
- public int controlsAccepted;
- public int win32ExitCode;
- public int serviceSpecificExitCode;
- public int checkPoint;
- public int waitHint;
- }
- public enum State
- {
- SERVICE_STOPPED = 0x00000001,
- SERVICE_START_PENDING = 0x00000002,
- SERVICE_STOP_PENDING = 0x00000003,
- SERVICE_RUNNING = 0x00000004,
- SERVICE_CONTINUE_PENDING = 0x00000005,
- SERVICE_PAUSE_PENDING = 0x00000006,
- SERVICE_PAUSED = 0x00000007,
- }
- public partial class Service1 : ServiceBase
- {
- [DllImport("ADVAPI32.DLL", EntryPoint = "SetServiceStatus")]
- public static extern bool SetServiceStatus(
- IntPtr hServiceStatus,
- SERVICE_STATUS lpServiceStatus
- );
- private SERVICE_STATUS myServiceStatus;
- private Monitor monitor;
- private Timer monTimer;
- private TimerCallback timerDelegate;
- private string systemName = "main";
- private long startDelay = 1000;
- private long period = 300000;
- public Service1()
- {
- InitializeComponent();
- }
- protected override void OnStart(string[] args)
- {
- // If we have some args use them before checking the image path args
- if (args.Length != 0)
- {
- // 0 = system 1 = start delay 2 = period
- if (args[0] != String.Empty)
- {
- systemName = args[0];
- if (args[1] != String.Empty)
- {
- startDelay = Convert.ToInt64(args[1]);
- if (args[2] != String.Empty)
- {
- period = Convert.ToInt64(args[2]);
- }
- }
- }
- }
- else
- {
- string[] imagePathArgs = Environment.GetCommandLineArgs();
- if (imagePathArgs.Length == 1)
- {
- // Use defaults
- }
- else
- {
- // The first arg needs to be the system name
- if (imagePathArgs[1] != String.Empty)
- {
- systemName = imagePathArgs[1];
- if (imagePathArgs[2] != String.Empty)
- {
- startDelay = Convert.ToInt64(imagePathArgs[2]);
- if (imagePathArgs[3] != String.Empty)
- {
- period = Convert.ToInt64(imagePathArgs[3]);
- }
- }
- }
- }
- }
- IntPtr handle = this.ServiceHandle;
- myServiceStatus.currentState = (int)State.SERVICE_START_PENDING;
- SetServiceStatus(handle, myServiceStatus);
- // Check for properties file
- string file = FindConfigFile();
- if (file.Equals("NOFILE"))
- {
- myServiceStatus.currentState = (int)State.SERVICE_STOP_PENDING;
- SetServiceStatus(handle, myServiceStatus);
- return;
- }
- monitor = new Monitor(systemName, file);
- timerDelegate = new TimerCallback(monitor.CheckJVM);
- monTimer = new Timer(timerDelegate, null, startDelay, period);
- myServiceStatus.currentState = (int)State.SERVICE_RUNNING;
- SetServiceStatus(handle, myServiceStatus);
- }
- protected override void OnStop()
- {
- //monTimer.Dispose();
- }
- /*******************************
- * Search for a file in known location on various drives
- * C,D,E,F
- * mstarFiles/systems/main
- *
- *******************************/
- protected String FindConfigFile()
- {
- char drive = 'C';
- string dir = ":\\mstar\\";
- string filename = "LICENSE.key";
- bool found = false;
- while (!found && drive <= 'Z')
- {
- if (System.IO.File.Exists(drive + dir + filename))
- {
- found = true;
- return drive + dir + filename;
- }
- else
- drive++;
- }
- return "NOFILE";
- }
- }
- }
- @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
- namespace MineStarAvailabilityMonitor
- {
- partial class Service1
- {
- /// <summary>
- /// Required designer variable.
- /// </summary>
- private System.ComponentModel.IContainer components = null;
- /// <summary>
- /// Clean up any resources being used.
- /// </summary>
- /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
- protected override void Dispose(bool disposing)
- {
- if (disposing && (components != null))
- {
- components.Dispose();
- }
- base.Dispose(disposing);
- }
- #region Component Designer generated code
- /// <summary>
- /// Required method for Designer support - do not modify
- /// the contents of this method with the code editor.
- /// </summary>
- private void InitializeComponent()
- {
- components = new System.ComponentModel.Container();
- this.ServiceName = "Service1";
- }
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement