Program in Jade Running on Netbeans not Transferring Message - java

I have created an agent which accepts a value and then passes a message on to the next agent. I am having problem with entering a value and so my message is also not being transfered. Here is my Agent class, below. Does anyone know what I can do to fix it?
public class Prgm extends Agent {
int val;
protected void setup() {
Objects[] args = getArguments();
if (args!=null && args.length > 0)
val = Integer.parseInt((String) args[0]);
addBehaviour(new OneShotBehaviour(this) {
public void action() {
if (val == 1) {
ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
msg.setLanguage("english");
msg.SetOntology("DG Status");
msg.SetContent("DG connected");
msg.addReceiver(new AID("r1", AID.ISLOCALNAME));
myAgent.send(msg);
} else {
ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
msg.addReceiver(new AID("r1", AID.ISLOCALNAME));
msg.setLanguage("english");
msg.setOntology("DG Status");
msg.setContent("DG not connected");
send(msg);
}
}
});
}

If you don't need to use ontologies right away don't. For strings you can use:
ACLmessage.setContent("string message") and String stringmsg=ACLmessage.getContent()
If you need something more try Java serialization, it's way simpler than using ontologies.
Also I don't think this line is acceptable. new AID("r1", AID.ISLOCALNAME). One would typically contact the df (directory facilitator) agent querying available agents or services. Try something like this
DFAgentDescription template = new DFAgentDescription();
ServiceDescription sd= new ServiceDescription();
sd.setType(Service);
sd.setName(agentName);
template.addServices(sd);
try {
DFAgentDescription[] result = DFService.search(this, template);
listAgents.clear();
for(int i = 0; i<result.length;++i)
{
listAgents.addElement(result[i].getName());
}
//System.out.println(listAgents);
} catch (FIPAException e) {
// TODO Auto-generated catch block
e.printStackTrace();
log(this.getAID() +"!!error in requesting service ="+Service);
}
return (AID) listAgents.get(0);

Related

How can i find my pc local ip address on my wireless network and pass the ip to my android device?

To find the ip address of the pc i'm using with c#
In the constructor:
localipadd = GetLocalIPAddress();
And the GetLocalIPAdress method:
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("Local IP Address Not Found!");
}
For example i'm getting the ip 10.0.01
Now the problem is how can i transfer this ip address string to my android device ?
The reason i need to do it is that on the c# i'm running a web server:
In the constructor:
var ws = new WebServer(
request => Task.Run(() => SendResponseAsync(request)),
"http://+:8098/");
ws.Run();
And the WebServer class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Threading;
namespace Automatic_Record
{
class WebServer
{
private readonly HttpListener _listener = new HttpListener();
private readonly Func<HttpListenerRequest, Task<string>> _responderMethod;
public WebServer(string[] prefixes, Func<HttpListenerRequest, Task<string>> method)
{
if (!HttpListener.IsSupported)
throw new NotSupportedException(
"Needs Windows XP SP2, Server 2003 or later.");
// URI prefixes are required, for example
// "http://localhost:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
// A responder method is required
if (method == null)
throw new ArgumentException("method");
foreach (string s in prefixes)
_listener.Prefixes.Add(s);
_responderMethod = method;
_listener.Start();
}
public WebServer(Func<HttpListenerRequest, Task<string>> method, params string[] prefixes)
: this(prefixes, method) { }
public void Run()
{
ThreadPool.QueueUserWorkItem((o) =>
{
Console.WriteLine("Webserver running...");
try
{
while (_listener.IsListening)
{
ThreadPool.QueueUserWorkItem(async (c) =>
{
var ctx = c as HttpListenerContext;
try
{
string rstr = await _responderMethod(ctx.Request);
System.Diagnostics.Trace.Write(ctx.Request.QueryString);
//ctx.Request.QueryString
byte[] buf = Encoding.UTF8.GetBytes(rstr);
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
}
catch { } // suppress any exceptions
finally
{
// always close the stream
ctx.Response.OutputStream.Close();
}
}, _listener.GetContext());
}
}
catch { } // suppress any exceptions
});
}
public void Stop()
{
_listener.Stop();
_listener.Close();
}
}
}
And on my android device using android studio i did a client that connect to the pc web server. Today what i'm doing is finding on my own the pc ip address and assign it to the android studio.
In the MainActivity:
private String[] ipaddresses = new String[]{
"http://10.0.0.1:8098/?cmd=nothing",
"http://192.168.1.5:8098/?cmd=nothing"};
And then a button listen method with button click Listener:
public void addListenerOnButton()
{
btnClick = (Button) findViewById(R.id.checkipbutton);
btnClick.setOnClickListener(new OnClickListener()
{
byte[] response = null;
#Override
public void onClick(View arg0)
{
text = (TextView) findViewById(R.id.textView2);
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
for (int i = 0; i < ipaddresses.length; i++)
{
counter = i;
try
{
response = Get(ipaddresses[i]);
} catch (Exception e)
{
String err = e.toString();
}
if (response != null)
{
try
{
final String a = new String(response, "UTF-8");
text.post(new Runnable()
{
#Override
public void run()
{
text.setText(a + " On \n" + ipaddresses[counter]);
status1.setText("Connected");
String successconnected = null;
successconnected = "Successfully connected";
textforthespeacch = successconnected;
MainActivity.this.initTTS();
}
});
iptouse = ipaddresses[i].substring(0, ipaddresses[i].lastIndexOf("=") + 1);
connectedtoipsuccess = true;
connectedSuccess = true;
Logger.getLogger("MainActivity(inside thread)").info(a);
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
Logger.getLogger("MainActivity(inside thread)").info("encoding exception");
}
Logger.getLogger("MainActivity(inside thread)").info("test1");
break;
}
else
{
}
}
counter = 0;
if (response == null)
{
text.post(new Runnable()
{
#Override
public void run()
{
text.setText("Connection Failed");
status1.setText("Connection Failed");
String successconnected = null;
successconnected = "connection failed";
textforthespeacch = successconnected;
MainActivity.this.initTTS();
}
});
}
}
});
t.start();
}
});
}
So this is how it work today:
I went to my living room and there i added to my router my pc static ip.
Then i went to my pc room i have another router with another network and i added there the pc static ip too.
And then added both ip's to the android studio code and then i'm looping over the array to see the one that connected and then i know this is the right ip to use.
The problem is that i can't ask the user/s to assign to the router a static ip and then fill the android studio with the array.....
What i need to do is somehow to assign the pc ip automatic to the android studio(to my android device) so it will be able to use it.
So i know using the c# to find my pc ip but how do i pass it to the android device and use it ?
I could scan make a scan on the android studio something that will scan all the ips from 0 to 255 and then to try to identify the one that is the pc but this might take a very long time.
Another option maybe could be sending the ip i found on my pc using the c# via gmail and get it with the android studio from the gmail and add it to the array ? Is that logic ?

How to make a Spring Shell command fail?

Imagine I have following Spring Shell commands class:
import org.springframework.shell.core.CommandMarker;
#Component
public class MyShellCommands implements CommandMarker {
#CliCommand(value = COMMAND_RUN, help = "")
public String run() {
[...]
// Something can go wrong here
[...]
}
}
If some error occurs in the method, I want the command to fail.
How can I make the run command fail, i. e. make sure that in case of error in the command, following assertion fails:
JLineShellComponent shell = ...;
final CommandResult result = shell.executeCommand("run");
assertThat(result.isSuccess()).isTrue(); // I want result.isSuccess() to be false, if run fails
?
Throwing a runtime exception does work, you'll even be able to retrieve it via CommandResult.getException()
Here is the code from spring-shell where the CommandResult is set to true or false.
Just look for occurances of return new CommandResult(false... and try to see if you can cause any of the scenarios that lead to the that to occur.
For example I notice that if the parseResult == null then a false status is set.
public CommandResult executeCommand(String line) {
// Another command was attempted
setShellStatus(ShellStatus.Status.PARSING);
final ExecutionStrategy executionStrategy = getExecutionStrategy();
boolean flashedMessage = false;
while (executionStrategy == null || !executionStrategy.isReadyForCommands()) {
// Wait
try {
Thread.sleep(500);
} catch (InterruptedException ignore) {}
if (!flashedMessage) {
flash(Level.INFO, "Please wait - still loading", MY_SLOT);
flashedMessage = true;
}
}
if (flashedMessage) {
flash(Level.INFO, "", MY_SLOT);
}
ParseResult parseResult = null;
try {
// We support simple block comments; ie a single pair per line
if (!inBlockComment && line.contains("/*") && line.contains("*/")) {
blockCommentBegin();
String lhs = line.substring(0, line.lastIndexOf("/*"));
if (line.contains("*/")) {
line = lhs + line.substring(line.lastIndexOf("*/") + 2);
blockCommentFinish();
} else {
line = lhs;
}
}
if (inBlockComment) {
if (!line.contains("*/")) {
return new CommandResult(true);
}
blockCommentFinish();
line = line.substring(line.lastIndexOf("*/") + 2);
}
// We also support inline comments (but only at start of line, otherwise valid
// command options like http://www.helloworld.com will fail as per ROO-517)
if (!inBlockComment && (line.trim().startsWith("//") || line.trim().startsWith("#"))) { // # support in ROO-1116
line = "";
}
// Convert any TAB characters to whitespace (ROO-527)
line = line.replace('\t', ' ');
if ("".equals(line.trim())) {
setShellStatus(Status.EXECUTION_SUCCESS);
return new CommandResult(true);
}
parseResult = getParser().parse(line);
if (parseResult == null) {
return new CommandResult(false);
}
setShellStatus(Status.EXECUTING);
Object result = executionStrategy.execute(parseResult);
setShellStatus(Status.EXECUTION_RESULT_PROCESSING);
if (result != null) {
if (result instanceof ExitShellRequest) {
exitShellRequest = (ExitShellRequest) result;
// Give ProcessManager a chance to close down its threads before the overall OSGi framework is terminated (ROO-1938)
executionStrategy.terminate();
} else {
handleExecutionResult(result);
}
}
logCommandIfRequired(line, true);
setShellStatus(Status.EXECUTION_SUCCESS, line, parseResult);
return new CommandResult(true, result, null);
} catch (RuntimeException e) {
setShellStatus(Status.EXECUTION_FAILED, line, parseResult);
// We rely on execution strategy to log it
try {
logCommandIfRequired(line, false);
} catch (Exception ignored) {}
return new CommandResult(false, null, e);
} finally {
setShellStatus(Status.USER_INPUT);
}
}

Java RMI server side threading

I'm just getting started with RMI and I'm trying to write a simple program that simulates a train booking system. I have the basics set up - Server, Client, and a Remote object exported. It works fine with one Client connection. However when more than 1 Client connects, the Clients seem to be executing in the same thread. This is the case when I run multiple Clients on the same machine or when I connect a Client from another laptop.
I was under the impression that RMI handled threading on the server side? If not, how do I go about handling multiple Client connections given the code below?
Here are the classes of interest.
Server.....
public class Server {
public Server() {
try {
Booking stub = (Booking) UnicastRemoteObject.exportObject(new BookingProcess(), 0);
Registry registry = LocateRegistry.getRegistry();
registry.bind("Booking", stub);
System.err.println("Server Ready");
} catch (RemoteException e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
} catch (AlreadyBoundException e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
public static void main(String[] args) {
Server server = new Server();
}
}
BookingProcess.....(I've left out the private methods that processInput(String input) uses)
public class BookingProcess implements Booking {
private static Journey dublinGalway = new Journey("Dublin to Galway");
private static Journey dublinLimerick = new Journey("Dublin to Limerick");
private static Journey dublinCork = new Journey("Dublin to Cork");
private Journey currentJourney;
private enum State {
INITIAL, JOURNEYS_DISPLAYED, JOURNEY_CHOSEN, ANOTHER_BOOKING_OFFERED, SOLD_OUT;
}
private State currentState = State.INITIAL;
public synchronized String processInput(String input) {
String output = "";
if(currentState == State.INITIAL) {
if(bookedOut()) {
output = "Sorry, there are no seats remaining on any route. Get the bus.";
currentState = State.SOLD_OUT;
}
else {
output = "Please choose a journey to book: " + "1: " + dublinGalway.getDescription() + ", 2: " + dublinLimerick.getDescription() + ", 3: " + dublinCork.getDescription();
currentState = State.JOURNEYS_DISPLAYED;
}
}
else if(currentState == State.JOURNEYS_DISPLAYED) {
output = this.processJourneyChoice(input);
}
else if(currentState == State.JOURNEY_CHOSEN) {
output = "Do you wish to confirm this booking? (y/n)";
if(input.equalsIgnoreCase("y")) {
if(bookingConfirmed()) {
output = "Thank you. Your journey from " + currentJourney.getDescription() + " is confirmed. Hit return to continue.";
//currentState = State.ANOTHER_BOOKING_OFFERED;
}
else {
output = "Sorry, but the last seat on the " + currentJourney.getDescription() + " route has just been booked by another user.";
//currentState = State.ANOTHER_BOOKING_OFFERED;
}
currentState = State.ANOTHER_BOOKING_OFFERED;
}
else if(input.equalsIgnoreCase("n")) {
output = "You have cancelled this booking. Hit return to continue.";
currentState = State.ANOTHER_BOOKING_OFFERED;
}
}
else if(currentState == State.ANOTHER_BOOKING_OFFERED) {
output = "Would you like to make another booking? (y/n)";
if(input.equalsIgnoreCase("y")) {
output = "Hit Return to continue.";
currentState = State.INITIAL;
}
else if(input.equalsIgnoreCase("n")){
output = "Goodbye.";
try {
Thread.currentThread().join(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
currentState = State.INITIAL;
}
}
else if(currentState == State.SOLD_OUT) {
output = "Goodbye.";
}
return output;
}
And finally Client......
public class Client {
public static void main(String[] args) {
Client client = new Client();
client.runClient();
}
public void runClient() {
try {
BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));
Registry registry = LocateRegistry.getRegistry("localhost");
Booking stub = (Booking) registry.lookup("Booking");
String serverResponse = stub.processInput("begin");
System.out.println("Server: " + serverResponse);
while((serverResponse = stub.processInput(consoleInput.readLine())) != null) {
System.out.println(serverResponse);
if(serverResponse.equals("Goodbye.")) {
break;
}
}
} catch (Exception e) {
System.err.println("Client exception " + e.toString());
e.printStackTrace();
}
}
}
As for as RMI server threads, the answer is that it may or may not run in a separate thread. See the documentation here:
http://docs.oracle.com/javase/6/docs/platform/rmi/spec/rmi-arch3.html
3.2 Thread Usage in Remote Method Invocations
A method dispatched by the RMI runtime to a remote object implementation may or may not execute in a separate thread. The RMI runtime makes no guarantees with respect to mapping remote object invocations to threads. Since remote method invocation on the same remote object may execute concurrently, a remote object implementation needs to make sure its implementation is thread-safe.
You can take server side thread dumps and you would see that the RMI TCP Connection threads IDs keep changing, however as #jtahlborn noticed the server side method is synchronized so it would execute serially, not necessarily in a single thread though.
Your server side processInput() method is synchronized, so, yes, the calls will be handled serially. what does that have to do with RMI?
UPDATE:
if you want to have separate currentState and currentJourney values for each client session, then you need to use the RMI remote session pattern, see this answer for details.

login in flex and java using multithreading

I have problem with my login application in java and flex. we use fingerprint login. the system waits for 60 seconds for any fingerprint input from the user. After that it automatically goes out of the page. The user also has text password option on that page. When user clicks on that option, control goes to some other page. But the problem is whenver user click on text password option, he is redirected but the thread of 60 seconds keep running. Can any one help me how to stop that thread. Here is my code. I am using blocking queue concept to get out of the input screen by inputting some dummy value of one bit.
private void interruptCaptureProcess() {
System.out.println("Interrupting Capture Process.");
ExactScheduledRunnable fingerScanInterruptThread = new ExactScheduledRunnable()
{
public void run()
{
try
{
if (capture != null)
{
DPFPSampleFactoryImpl test = new DPFPSampleFactoryImpl();
samples.put(test.createSample(new byte[1]));
capture.stopCapture();
}
}
catch (Exception e)
{
LOGGER.error("interruptCaptureProcess", e);
e.printStackTrace();
}
}
};
timeOutScheduler.schedule(fingerScanInterruptThread, getTimeOutValue(), TimeUnit.SECONDS);
}
/**
* Scans and Verifies the user finger print by matching it with the previous registered template for the user.
*
* #param userVO is the user value object which has to be verified.
* #return the acknowledgment string according to result for operation performed.
* #throws UserServiceException when there is an error in case of getting user record.
*/
public String verifyUserFingerPrint(Long userId) throws LoginServiceException {
System.out.println("Performing fingerprint verification...\n");
interruptCaptureProcess();
UserVO userVO = null;
try {
userVO = new UserService().findUserById(userId, true);
if (userVO != null) {
stopCaptureProcess();
DPFPSample sample = getSample(selectReader(), "Scan your finger\n");
timeOutScheduler.shutdownNow();
if (sample.serialize().length == 1) {
System.out.println("Coming in code");
return null;
} else if (sample.serialize().length == 2) {
System.out.println("Capturing Process has been Timed-Out");
return TIMEOUT;
}
if (sample == null)
throw new UserServiceException("Error in scanning finger");
DPFPFeatureExtraction featureExtractor = DPFPGlobal.getFeatureExtractionFactory()
.createFeatureExtraction();
DPFPFeatureSet featureSet = featureExtractor.createFeatureSet(sample,
DPFPDataPurpose.DATA_PURPOSE_VERIFICATION);
DPFPVerification matcher = DPFPGlobal.getVerificationFactory().createVerification();
matcher.setFARRequested(DPFPVerification.MEDIUM_SECURITY_FAR);
byte[] tempByte = userVO.getFingerPrint();
DPFPTemplateFactory facotory = new DPFPTemplateFactoryImpl();
for (DPFPFingerIndex finger : DPFPFingerIndex.values()) {
DPFPTemplate template = facotory.createTemplate(tempByte);
if (template != null) {
DPFPVerificationResult result = matcher.verify(featureSet, template);
// Fix of enh#1029
Map<ScriptRxConfigType, Map<ScriptRxConfigName, String>> scriptRxConfigMap = ScriptRxConfigMapSingleton
.getInstance().getScriptRxConfigMap();
Map<ScriptRxConfigName, String> fingerPrintPropertiesMap = scriptRxConfigMap
.get(ScriptRxConfigType.FINGERPRINT);
String fingerPrintDemoMode = fingerPrintPropertiesMap.get(ScriptRxConfigName.DEMOMODE);
if (fingerPrintDemoMode != null && fingerPrintDemoMode.equalsIgnoreCase("DemoEnabled")) {
return "LOGS_MSG_101";
}
// End of fix of enh#1029
if (result.isVerified()) {
System.out.println("Matching finger: %s, FAR achieved: %g.\n" + fingerName(finger)
+ (double) result.getFalseAcceptRate() / DPFPVerification.PROBABILITY_ONE);
return "LOGS_MSG_101";
}
}
}
}
} catch (IndexOutOfBoundsException iob) {
LOGGER.error("verifyUserFingerPrint", iob);
throw new LoginServiceException("LOGS_ERR_101", iob);
} catch (Exception exp) {
LOGGER.error("verifyUserFingerPrint", exp);
System.out.println("Failed to perform verification.");
throw new LoginServiceException("LOGS_ERR_105", exp);
} catch (Throwable th) {
LOGGER.error("verifyUserFingerPrint", th);
throw new LoginServiceException("LOGS_ERR_106", th.getMessage(), th);
}
System.out.println("No matching fingers found for \"%s\".\n" + userVO.getFirstName().toUpperCase());
throw new LoginServiceException("LOGS_ERR_107", null);
}
/* finger scanning process
*/
private void stopCaptureProcess() {
ExactScheduledRunnable fingerScanInterruptThread = new ExactScheduledRunnable() {
public void run() {
try {
DPFPSampleFactoryImpl test = new DPFPSampleFactoryImpl();
samples.put(test.createSample(new byte[2]));
capture.stopCapture();
} catch (Throwable ex) {
ex.printStackTrace();
}
}
};
timeOutScheduler.schedule(fingerScanInterruptThread, getTimeOutValue(), TimeUnit.SECONDS);
}
/**
* API will get the value for the finger scanner time out configuration(Default will be 60 seconds)
*/
private long getTimeOutValue() {
long waitTime = 60;
String configValue = ScriptRxSingleton.getInstance().getConfigurationValue(ConfigType.Security,
ConfigName.FingerprintTimeout);
try {
waitTime = Long.valueOf(configValue);
} catch (NumberFormatException e) {
LOGGER.debug("Configuration value is not a number for FingerTimeOut", e);
}
return waitTime;
}
Stopping blocking tasks in Java is a complicated topic, and requires cooperation between the blocking code and the code that wants to unblock it. The most common way in Java is to interrupt the thread that is blocking, which works if the code that is blocking and the code around it understands interruption. If that's not the case you're out of luck. Here's an answer that explains one way to interrupt a thread that is blocking in an Executor: https://stackoverflow.com/a/9281038/1109

Create new thread in for loop inside public void method()

I have a class that ping IP addresses. To start ping I have public vod run() method to start pinging. Problem is that I want ping more IP addresses at same time (for each IP address I need new Thread). So how can I create new Thread inside for loop. Here is code of my ping class:
public void run()
{
if (dbConnection.ConnectToDB())
{
for (;GateWayKey<=GateWayKeyStop;GateWayKey++)
{
if(stop || this.isInterrupted()){
return;
}
ip="192.168."+GateWayKey+".1";
InetAddress address;
try {
address = InetAddress.getByName(ip);
try {
if (address.isReachable(PingTime))
{
//System.out.println("Pronaden GateWay: "+ip)
// labele.IP
sql="INSERT INTO `iptables` (`IP` , `COMPUTER_NAME` , `GATEWAY_KEY`) VALUES ('"+ip+"', '"+address.getHostName().toString()+"', '"+GateWayKey+"');";
framedocs.WriteMonitorData (ip, address.getHostName().toString(),"2000","DA",dbConnection.WriteToDB(sql));
for (;SubNetKey<=SubNetKeyStop;SubNetKey++)
{
if(stop || this.isInterrupted()){
return;
}
InetAddress addressIps = InetAddress.getByName("192.168."+GateWayKey+"."+SubNetKey);
System.out.println("Provjeravam IP: "+addressIps);
if (addressIps.isReachable(PingTime))
{
ip="192.168."+GateWayKey+"."+SubNetKey;
System.out.println("Pronaden IP: "+ip);
sql="INSERT INTO `iptables` (`IP` , `COMPUTER_NAME` , `GATEWAY_KEY`) VALUES ('"+ip+"', '"+addressIps.getHostName().toString()+"', '"+GateWayKey+"');";
framedocs.WriteMonitorData (ip, address.getHostName().toString(),"2000","DA",dbConnection.WriteToDB(sql));
}
else
{
framedocs.WriteMonitorData (addressIps.toString(), "N/A","2000","NE","N/A");
}
}
}
else
{
framedocs.WriteMonitorData (ip, "N/A","2000","NE","N/A");
}
} catch (IOException e) {
// TODO Auto-generated catch block
framedocs.WriteMonitorData (ip, "N/A","2000",e.getMessage(),"N/A");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
;
framedocs.WriteMonitorData (ip, "N/A","2000",e.getMessage(),"N/A");
}
}
}
else
{
framedocs.WriteMonitorData ("MySQL error", "N/A","N/A","N/A","N/A");
}
}
A general way to do these kinds of tasks is, first, create a class to hold the results you want to get from each thread:
final class PingResult {
public String ip;
public String hostname;
//... other things you want go here
}
Then create a callable that does the actual work
class PingTask extends Callable<PingResult>{
private final String gateWayKey, subNetKey;
//... other parameters you need go here
public Ping( String gwKey, String snKey /*+ others? */ ){
// This is just a way to pass parameters to your pinging function
this.gateWayKey = gwKey;
this.subNetKey = snKey;
// ...
}
public PingResult call(){
// Do actual pinging work here
if ( /* Success */ )
{
PingResult result = new PingResult();
result.ip= /*Fill these in*/;
result.hostname = /* ... */;
return result;
}
// Otherwise we failed, I'm using null as a failure sentinel
// (you can come up with something better)
return null;
}
}
Then in your calling code, set up a thread pool, cue up the requests, and then process the results.
// Might need to tweak the # for best performance
final int NUM_THREADS = Runtime.getRuntime.availableProcesses();
ExecutorService exec = Executors.newFixedThreadPool( NUM_THREADS );
List<Future<PingResult>> results = new ArrayList<PingResult>();
for(/* ... */){
results.add( exec.submit( new PingTask( gateway, subnet ) ) );
}
for( Future<PingResult> future : results ){
PingResult result = future.get();
// Process the result here (this is where you insert into the DB)
}
exec.shutdown(); // VERY IMPORTANT. If you don't do this the JVM will never stop.
create a new class inside your main class and do your operations in that inner class
every-time you need to create a new thread just initiate a new instance of that inner class and call its methods created for this purpose
If you find this answer not useful check my other answer on multi-threading.

Categories

Resources