Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
8 respostas
N
noobsaibot
Olá amigos,
Estou encontrando dificuldades para executar o seguinte código:
packageorg.nsclient4j;publicclassCLStat{publicstaticvoidmain(Stringargs[]){try{NSClient4jclient=newNSClient4j("10.1.1.15");System.out.print("Result:"+client.getPerfMonCounter("\Processador(_Total)\% tempo de processador"));}catch(NSClient4JExceptione){System.err.println("Exception Geting Stat:"+e);}}}
javaorg.nsclient4j.CLStat10.1.1.15"\Processador(_Total)\% tempo de processador"
Mas como não sou entendido vou no assunto vou postar a classe como você solicitou.
N
noobsaibot
Conforme solicitado…
packagecom.marketwide.nagios;importjava.io.BufferedInputStream;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importjava.net.Socket;importjava.net.UnknownHostException;importjava.text.ParseException;importjava.text.SimpleDateFormat;importjava.util.Date;importjava.util.ArrayList;importjava.util.StringTokenizer;/** * <p>Title: NSClient4J</p> * <p>Description: Net Saint NT Client For Java</p> * <p>Copyright: Copyright (c) 2004</p> * <p>Company: Marketwide Software</p> * <p>This is a Java implementation of the nagios plugin <b>check_nt</b>. * <p>Some of the calls are not implemented since they are superfluous and can be achieved with the <i>getPerfMonCounter</i> call. * <p>These are:<ul> * <li>CHECK_USEDDISKSPACE * <li>CHECK_MEMUSE * </ul> * @author Whitehead ([email removido]) * @version 1.0 */publicclassNSClient4j{/** The string representation of the host name to connect to */protectedStringhostName=null;/** The port number NSClient is running on. Default is 1248 */protectedintportNumber=1248;/** The password for connecting to NSClient. Default is "None" */protectedStringpassword="None";/** The socket for communicating with Remote NSClient */protectedSocketsocket=null;protectedOutputStreamos=null;protectedInputStreamis=null;protectedBufferedInputStreambis=null;protectedByteArrayOutputStreambaos=null;protectedintsocketTimeout=5000;protectedbooleaninited=false;publicvoidsetPassword(Stringpassword){this.password=password;}publicvoidsetPortNumber(intportNumber){this.portNumber=portNumber;}publicvoidsetHostName(StringhostName){this.hostName=hostName;}/** * NSClient4j Constructor. * @param hostName String The name or IP address of the host that is running NSClient * @throws NSClient4JException */publicNSClient4j(StringhostName)throwsNSClient4JException{this.hostName=hostName;initSocket();}/** * NSClient4j Constructor. * @param hostName String The name or IP address of the host that is running NSClient * @param portNumber int The port number NSClient is listening on if not the default * @throws NSClient4JException */publicNSClient4j(StringhostName,intportNumber)throwsNSClient4JException{this.hostName=hostName;this.portNumber=portNumber;initSocket();}/** * NSClient4j Constructor. * @param hostName String The name or IP address of the host that is running NSClient * @param portNumber int The port number NSClient is listening on if not the default * @param password String * @throws NSClient4JException */publicNSClient4j(StringhostName,intportNumber,Stringpassword)throwsNSClient4JException{this.hostName=hostName;this.portNumber=portNumber;this.password=password;initSocket();}/** * NSClient4j Constructor. * @param hostName String The name or IP address of the host that is running NSClient * @param password String * @throws NSClient4JException */publicNSClient4j(StringhostName,Stringpassword)throwsNSClient4JException{this.hostName=hostName;this.password=password;initSocket();}/** * Parameterless constructor. * Unlike the other constructors, this one does not init the socket layer. * Once the configuration parameters have been set, the init() method must be called before the client can be used. */publicNSClient4j(){inited=false;}/** * Sets the time out on the NSRequests. If the request times out, it will throw an exception. * The default is 5000 ms * @param timeout int the request timeout in milliseconds */publicvoidsetSocketTimeOut(inttimeout){socketTimeout=timeout;}/** * Initializes the socket layer. * Intended for use in concert with the parameterless constructor * @throws NSClient4JException */publicvoidinit()throwsNSClient4JException{initSocket();}/** * Opens the socket as configured to the remote NSClient. * Initializes all the io streams. * @throws UnknownHostException * @throws IOException */protectedvoidinitSocket()throwsNSClient4JException{if(!inited){try{socket=newSocket(hostName,portNumber);is=socket.getInputStream();os=socket.getOutputStream();bis=newBufferedInputStream(is);baos=newByteArrayOutputStream();inited=true;}catch(UnknownHostExceptionex){inited=false;thrownewNSClient4JException("Unknown Host:"+hostName,ex);}catch(IOExceptionex){inited=false;thrownewNSClient4JException("Exception Connecting to "+hostName+":"+portNumber+" -> "+ex,ex);}}}/** * Closes the socket */publicvoidclose(){try{socket.close();}catch(Exceptionex){}}/** * Last ditch effort to close the socket */publicvoidfinalize(){try{socket.close();}catch(Exceptionex){}try{super.finalize();}catch(Throwablet){}}/** * Returns the version of the NSClient that is connected to. * @throws NSClient4JException * @return String */publicStringgetNSClientVersion()throwsNSClient4JException{Stringresult=submittRequest(password+"&1");returnresult;}/** * <p>Retrieves the value of a NT Performance Monitor counter value. * <p>Example counter string are: <ul> * <li>\\ProcessorPerformance(ACPI\\GenuineIntel_-_x86_Family_6_Model_9\\_0_0)\\Processor Frequency * <li>\\Processor(_Total)\\% Processor Time * </ul> * @param counterName String * @throws NSClient4JException * @return String */publicStringgetPerfMonCounter(StringcounterName)throwsNSClient4JException{if(counterName.equalsIgnoreCase("CPU")){returngetCPUUsage();}Stringresult=submittRequest(password+"&8&"+counterName);returnresult;}/** * This method is needed since calling the perfMon counter always show close to 100 % util. * @throws NSClient4JException * @return String */publicStringgetCPUUsage()throwsNSClient4JException{//CPU Load 1% (1 min average)Stringresult=submittRequest(password+"&2&1&1&1");returnresult;}/** * Retrieves the up time of the server in seconds * @throws NSClient4JException * @return int The up time in seconds */publicintgetUpTimeSeconds()throwsNSClient4JException{Stringresult=submittRequest(password+"&3");returnInteger.parseInt(result);}/** * Retrieves the up time of the server in minutes * @throws NSClient4JException * @return int The up time in minutes (rounded) */publicintgetUpTimeMinutes()throwsNSClient4JException{Stringresult=submittRequest(password+"&3");intsecs=Integer.parseInt(result);intminutes=secs/60;returnminutes;}/** * Retrieves the up time of the server in hours * @throws NSClient4JException * @return int The up time in hours (rounded) */publicintgetUpTimeHours()throwsNSClient4JException{Stringresult=submittRequest(password+"&3");intsecs=Integer.parseInt(result);inthours=secs/60/60;returnhours;}/** * Retrieves the up time of the server in Days * @throws NSClient4JException * @return int The up time in days */publicfloatgetUpTimeDays()throwsNSClient4JException{Stringresult=submittRequest(password+"&3");floatsecs=Float.parseFloat(result);floatdays=secs/60/60/24;returndays;}/** * Retrieves the up time of the server as the date the server started * @throws NSClient4JException * @return Date The date the server started. */publicDategetUpTimeDate()throwsNSClient4JException{Stringresult=submittRequest(password+"&3");longstartTime=System.currentTimeMillis()-Long.parseLong(result)*1000;returnnewDate(startTime);}/** * Tests a service by service name. If the service is up, returns true. * If it is stopped, or unknown, returns a false. * @param serviceName String * @throws NSClient4JException * @return boolean */publicbooleanisServiceUp(StringserviceName)throwsNSClient4JException{Stringresult=submittRequest(password+"&5&ShowAll&"+serviceName);String[]results=split(result,":");if(results[1].trim().equalsIgnoreCase("Started")){returntrue;}else{returnfalse;}}/** * Tests a process by process name. If process is running, returns true. * If process is not running, or unknown, returns false. * @param processName String * @throws NSClient4JException * @return boolean */publicbooleanisProcessUp(StringprocessName)throwsNSClient4JException{Stringresult=submittRequest(password+"&6&ShowAll&"+processName);String[]results=split(result,":");if(results[1].trim().equalsIgnoreCase("Running")){returntrue;}else{returnfalse;}}/** * Gets the file date of the passed file name * @param fileName String * @throws NSClient4JException * @return Date */publicDategetFileDate(StringfileName)throwsNSClient4JException{Stringresult=submittRequest(password+"&9&"+fileName);// 8500&Date: 08/28/2004 1:05:42 PMString[]results=split(result,":");SimpleDateFormatdateFormat=newSimpleDateFormat("MM/dd/yyyy h:mm:ss a");try{returndateFormat.parse(results[1].trim());}catch(ParseExceptionex){thrownewNSClient4JException("Bad Date Format:"+results[1],ex);}}/** * Returns the port number connected to * @return int */publicintgetPortNumber(){returnportNumber;}/** * Returns the host name connected to * @return String */publicStringgetHostName(){returnhostName;}/** * Generic request submission method used by all NSClient4j calls. * @param request String * @throws NSClient4JException * @return String */protectedsynchronizedStringsubmittRequest(Stringrequest)throwsNSClient4JException{byte[]buffer=newbyte[1024];baos.reset();Stringresult=null;if(!inited){initSocket();}try{socket.setSoTimeout(socketTimeout);os.write(request.getBytes());os.flush();while(true){intread=bis.read(buffer);if(read>0){baos.write(buffer,0,read);break;}else{break;}}result=baos.toString();returnresult;}catch(Exceptionex){inited=false;thrownewNSClient4JException(ex.getMessage(),ex);}}publicstaticStringgetCounter(StringhostName,intport,Stringpassword,StringcounterName){try{NSClient4jclient=newNSClient4j(hostName,port,password);returnclient.getPerfMonCounter(counterName);}catch(NSClient4JExceptionex){return"Exception:"+ex;}}publicstaticString[]split(Strings,Stringdelim){StringTokenizertokenizer=newStringTokenizer(s,delim);String[]result=newString[tokenizer.countTokens()];inti=0;while(tokenizer.hasMoreTokens()){result[i]=tokenizer.nextToken();i++;}returnresult;}}
F
fcfm
Ao invés de usar a String “Processador(_Total)% tempo de processador”
use “CPU”
Esse contador tem um bug, e o serviço NSClient só retorna 100%.
Ou vc utiliza a String “CPU” ou usa o método getCPUUsage() na classe NSClient.