scan IP without SNMP agent - java

Using as an example a following code from https://www.jitendrazaa.com/blog/java/snmp/create-snmp-client-in-java-using-snmp4j/ to monitor a network when I send OIDs to an empty IP or to a device without SNMP the program throws an exception.
I use a for loop to read IPs. I have tried to change the flow of execution in different ways without success.
the program falls in the getAsStrint method with java.lang.NullPointerException
public class SNMPManager {
Snmp snmp = null;
String address = null;
/**
* Constructor
*
* #param add
*/
public SNMPManager(String add) {
address = add;
}
public static void main(String[] args) throws IOException {
/**
* Port 161 is used for Read and Other operations
* Port 162 is used for the trap generation
*/
for (int i = 37; i < 40; i++) {
System.out.println("ip x.x.x." + i);
SNMPManager client = new SNMPManager("udp:192.168.1." + i + "/161");
//SNMPManager client = new SNMPManager("udp:192.168.1.37/161");
client.start();
/**
* OID - .1.3.6.1.2.1.1.1.0 => SysDec
* OID - .1.3.6.1.2.1.1.5.0 => SysName
* => MIB explorer will be usefull here, as discussed in previous article
*/
String sysDescr = client.getAsString(new OID(".1.3.6.1.2.1.1.5.0"));
System.out.println(".1.3.6.1.2.1.1.5.0" + " - SysName: " + sysDescr);
String sysDescr2 = client.getAsString(new OID(".1.3.6.1.2.1.1.1.0"));
System.out.println(".1.3.6.1.2.1.1.1.0" + " - SysDec: " + sysDescr2);
}
}
/**
* Start the Snmp session. If you forget the listen() method you will not
* get any answers because the communication is asynchronous
* and the listen() method listens for answers.
*
* #throws IOException
*/
private void start() throws IOException {
TransportMapping transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
// Do not forget this line!
transport.listen();
}
/**
* Method which takes a single OID and returns the response from the agent as a String.
*
* #param oid
* #return
* #throws IOException
*/
public String getAsString(OID oid) throws IOException {
ResponseEvent event = get(new OID[]{oid});
return event.getResponse().get(0).getVariable().toString();
}
/**
* This method is capable of handling multiple OIDs
*
* #param oids
* #return
* #throws IOException
*/
public ResponseEvent get(OID oids[]) throws IOException {
PDU pdu = new PDU();
for (OID oid : oids) {
pdu.add(new VariableBinding(oid));
}
pdu.setType(PDU.GET);
ResponseEvent event = snmp.send(pdu, getTarget(), null);
if (event != null) {
return event;
}
throw new RuntimeException("GET timed out");
}
/**
* This method returns a Target, which contains information about
* where the data should be fetched and how.
*
* #return
*/
private Target getTarget() {
Address targetAddress = GenericAddress.parse(address);
CommunityTarget target = new CommunityTarget();
target.setCommunity(new OctetString("public"));
target.setAddress(targetAddress);
target.setRetries(2);
target.setTimeout(1500);
target.setVersion(SnmpConstants.version2c);
return target;
}

make getAsString(OID oid) method like this
public String getAsString(OID oid) throws IOException {
ResponseEvent event = get(new OID[]{oid});
if(event.getResponse() != null){
return event.getResponse().get(0).getVariable().toString();
} else {
return "no target"
}
}
there are no target that is why null pointer exception

Related

Java Client-Server and Observer

I am implementing a Java Client-Server application for a university task and I'm stuck at the following point: I am obliged to use client-server and also update the view whenever the data in the database changes. What I have done is that whenever a change in the database should occur I notify all the clients with the "CHANGE IN DATA" message and then the client should read and understand this message in order to call a method that will update it's graphic interface. However, or I'm mistaking the reading part on client side or because of some error, the clients don't read the "CHANGE IN DATA" message so the whole gets stuck at this point and the view doesn't update.
Here are some relevant codes!
Server class:
public class FinesPaymentServer implements Runnable {
private Database database;
private UserGateway userGateway;
private FineGateway fineGateway;
private DriverGateway driverGateway;
private Socket connection;
private int ID;
static ArrayList<Socket> clientsConnected;
/**
* Constructor of the class connecting to the database and initializing the socket
* #param database the database used
* #param connection the socket for the server
* #param ID the id
*/
private FinesPaymentServer(Database database, UserGateway userGateway, FineGateway fineGateway, DriverGateway driverGateway, Socket connection, int ID) {
this.connection = connection;
this.userGateway = userGateway;
this.fineGateway = fineGateway;
this.driverGateway = driverGateway;
this.database = database;
this.ID = ID;
}
/**
* Run method of the threads for each socket on the server
*/
public void run() {
try {
while(true)
readFromClient(connection);
} catch (IOException | SQLException e) {
System.out.println(e);
}
}
/**
* Read method from the client
* #param client the client socket from where to read
* #throws IOException
* #throws SQLException
*/
public void readFromClient(Socket client) throws IOException, SQLException {
BufferedInputStream is = new BufferedInputStream(client.getInputStream());
InputStreamReader reader = new InputStreamReader(is);
StringBuffer process = new StringBuffer();
int character;
while((character = reader.read()) != 13) {
process.append((char)character);
}
System.out.println("[SERVER READ]: "+process);
String[] words = process.toString().split("\\s+");
switch (process.charAt(0)) {
case 'a' :
{
int type = database.verifyLogin(words[1], words[2]);
sendMessage(client, ""+type + " ");
break;
}
case 'b' :
{
String rs = userGateway.getUsers();
sendMessage(client, rs);
break;
}
case 'c' :
{
userGateway.createUser(words[1], words[2], words[3]);
notifyClients();
break;
}
case 'd' :
{
userGateway.updateUser(words[1], words[2], words[3]);
notifyClients();
break;
}
case 'e' :
{
userGateway.deleteUser(words[1]);
notifyClients();
break;
}
}
try {
Thread.sleep(1000);
} catch (Exception e){}
String time_stamp = new java.util.Date().toString();
String returnCode = "Single Socket Server responded at " + time_stamp + (char) 13;
sendMessage(client, returnCode);
}
/**
* Method for sending messages from the server to the client
* #param client the client socket where to send the message
* #param message the message itself to be sent
* #throws IOException
*/
private void sendMessage(Socket client, String message) throws IOException {
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(client.getOutputStream()));
writer.write(message);
System.out.println("[SERVER WRITE]: "+message);
writer.flush();
}
public void notifyClients() throws IOException
{
for(Socket s : clientsConnected)
{
sendMessage(s, "CHANGE IN DATA ");
}
}
/**
* #param args the command line arguments
* #throws java.sql.SQLException
*/
public static void main(String[] args) throws SQLException {
Database database = new Database();
UserGateway userGateway = new UserGateway();
FineGateway fineGateway = new FineGateway();
DriverGateway driverGateway = new DriverGateway();
clientsConnected = new ArrayList<>();
// Setting a default port number.
int portNumber = 2015;
int count = 0;
System.out.println("Starting the multiple socket server at port: " + portNumber);
try {
ServerSocket serverSocket = new ServerSocket(portNumber);
System.out.println("Multiple Socket Server Initialized");
//Listen for clients
while(true) {
Socket client = serverSocket.accept();
clientsConnected.add(client);
Runnable runnable = new FinesPaymentServer(database, userGateway, fineGateway, driverGateway, client, ++count);
Thread thread = new Thread(runnable);
thread.start();
}
} catch (Exception e) {}
}
}
The client class:
public class FinesPaymentClient implements Runnable {
private String hostname = "localhost";
private int port = 2015;
Socket socketClient;
AdministratorModel adminModel;
PoliceModel policeModel;
PostModel postModel;
/**
* Constructor of the class
* #param hostname the host name of the connection
* #param port the port of the connection
* #throws UnknownHostException
* #throws IOException
*/
public FinesPaymentClient(String hostname, int port, AdministratorModel adminModel, PoliceModel policeModel, PostModel postModel) throws UnknownHostException, IOException
{
this.hostname = hostname;
this.port = port;
this.adminModel = adminModel;
this.policeModel = policeModel;
this.postModel = postModel;
connect();
}
/**
* Method for connecting to the host by a socket
* #throws UnknownHostException
* #throws IOException
*/
public void connect() throws UnknownHostException, IOException {
System.out.println("Attempting to connect to " + hostname + ":" + port);
socketClient = new Socket(hostname, port);
System.out.println("Connection Established");
}
/**
* Method for reading response from the server
* #return the string read from the server
* #throws IOException
*/
public String readResponse() throws IOException {
String userInput;
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(socketClient.getInputStream()));
System.out.println("[CLIENT READ]:");
while ((userInput = stdIn.readLine()) != null) {
System.out.println(userInput);
return userInput;
}
return userInput;
}
/**
* Method for closing connection between client and server
* #throws IOException
*/
public void closeConnection() throws IOException {
socketClient.close();
}
/**
* Method for writing messages to the server
* #param message the message to be sent
* #throws IOException
*/
public void writeMessage(String message) throws IOException {
String time_stamp = new java.util.Date().toString();
// Please note that we placed a char(13) at the end of process...
// we use this to let the server know we are at the end
// of the data we are sending
String process = message + (char) 13;
BufferedWriter stdOut = new BufferedWriter(
new OutputStreamWriter(socketClient.getOutputStream()));
stdOut.write(process);
System.out.println("[CLIENT WRITE]: "+process);
// We need to flush the buffer to ensure that the data will be written
// across the socket in a timely manner
stdOut.flush();
}
#Override
public void run() {
try {
String response;
while(true)
{
response = readResponse();
System.out.println("HERE"+response.substring(0, 13));
if(response.substring(0, 13).equals("CHANGE IN DATA"))
{
adminModel.setChange();
}
}
} catch (IOException e) {
System.out.println(e);
}
}
/**
* Main method of the application
* #param arg the parameters given as arguments
* #throws SQLException
* #throws UnknownHostException
* #throws IOException
*/
public static void main(String arg[]) throws SQLException, UnknownHostException, IOException {
AdministratorModel adminModel = new AdministratorModel();
PoliceModel policeModel = new PoliceModel();
PostModel postModel = new PostModel();
FinesPaymentClient client = new FinesPaymentClient("localhost", 2015, adminModel, policeModel, postModel);
Runnable client2 = new FinesPaymentClient("localhost", 2015, adminModel, policeModel, postModel);
Thread thread = new Thread(client2);
thread.start();
Login login = new Login();
ClientSide clientSide = new ClientSide(login, client, adminModel, policeModel, postModel);
}
}
ClientSide class:
public class ClientSide {
private final Login login;
private FinesPaymentClient client;
AdministratorModel adminModel;
PoliceModel policeModel;
PostModel postModel;
/**
* Constructor instantiating needed classes
* #param login an instance of the login class
* #param client the client needing the control logic
* #param adminModel
* #param policeModel
* #param postModel
* #throws SQLException using classes connecting to a database sql exceptions can occur
*/
public ClientSide(Login login, FinesPaymentClient client, AdministratorModel adminModel, PoliceModel policeModel, PostModel postModel) throws SQLException
{
this.login = login;
this.client = client;
this.adminModel = adminModel;
this.policeModel = policeModel;
this.postModel = postModel;
login.addButtonListener(new ButtonListener());
}
/**
* Listener for the login button. Reads, verifies and provides the interface according to logged in user type.
*/
class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
try
{
client.writeMessage("a " + login.field1.getText()+ " " + login.field2.getText());
String response = client.readResponse();
if(response.charAt(0) == '1')
{
login.setVisible(false);
AdministratorGUI administratorGUI = new AdministratorGUI(adminModel, client);
AdministratorController adminController = new AdministratorController(client, administratorGUI, adminModel);
}
//if user is post office employee
else if(response.charAt(0) == '2')
{
login.setVisible(false);
PostGUI postGUI = new PostGUI();
PostController postController = new PostController(client, postGUI, postModel);
}
//if user is police employee
else if(response.charAt(0) == '3')
{
login.setVisible(false);
PoliceGUI policeGUI = new PoliceGUI();
PoliceController policeController = new PoliceController(client, policeGUI, policeModel);
}
else
{
JOptionPane.showMessageDialog(null,"Login failed! Please try again!");
}
}
catch (IOException ex)
{
Logger.getLogger(ClientSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
I'm 99% sure that the error is on client side reading the message sent from the server as notification, but I simply cannot figure it out how could I retrieve that message. Right now I have a try in the client threads run method, but doesn't work. Other classes and other functionalities work just fine, this is my only problem. Do you have any ideas what the mistake could be? I would appreciate any help.

Generate JSON Web token

I have this class to generate a JSON Web token with I got from this post.
I need an id and a expression date to create a token.
Do I have to set up some kind of server to get the id and the expression date?
/**
* Provides static methods for creating and verifying access tokens and such.
*
* #author davidm
*
*/
public class AuthHelper {
private static final String AUDIENCE = "NotReallyImportant";
private static final String ISSUER = "crazyquote";
private static final String SIGNING_KEY = "LongAndHardToGuessValueWithSpecialCharacters#^($%*$%";
/**
* Creates a json web token which is a digitally signed token that contains
* a payload (e.g. userId to identify the user). The signing key is secret.
* That ensures that the token is authentic and has not been modified. Using
* a jwt eliminates the need to store authentication session information in
* a database.
*
* #param userId
* #param durationDays
* #return
*/
public static String createJsonWebToken(String userId, Long durationDays) {
// Current time and signing algorithm
Calendar cal = Calendar.getInstance();
HmacSHA256Signer signer;
try {
signer = new HmacSHA256Signer(ISSUER, null, SIGNING_KEY.getBytes());
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
}
// Configure JSON token
JsonToken token = new net.oauth.jsontoken.JsonToken(signer);
token.setAudience(AUDIENCE);
token.setIssuedAt(new org.joda.time.Instant(cal.getTimeInMillis()));
token.setExpiration(new org.joda.time.Instant(cal.getTimeInMillis()
+ 1000L * 60L * 60L * 24L * durationDays));
// Configure request object, which provides information of the item
JsonObject request = new JsonObject();
request.addProperty("userId", userId);
System.out.println("request " + request);
JsonObject payload = token.getPayloadAsJsonObject();
payload.add("info", request);
try {
return token.serializeAndSign();
} catch (SignatureException e) {
throw new RuntimeException(e);
}
}
/**
* Verifies a json web token's validity and extracts the user id and other
* information from it.
*
* #param token
* #return
* #throws SignatureException
* #throws InvalidKeyException
*/
public static TokenInfo verifyToken(String token) {
try {
final Verifier hmacVerifier = new HmacSHA256Verifier(
SIGNING_KEY.getBytes());
VerifierProvider hmacLocator = new VerifierProvider() {
#Override
public List<Verifier> findVerifier(String id, String key) {
return Lists.newArrayList(hmacVerifier);
}
};
VerifierProviders locators = new VerifierProviders();
locators.setVerifierProvider(SignatureAlgorithm.HS256, hmacLocator);
net.oauth.jsontoken.Checker checker = new net.oauth.jsontoken.Checker() {
#Override
public void check(JsonObject payload) throws SignatureException {
// don't throw - allow anything
}
};
// Ignore Audience does not mean that the Signature is ignored
JsonTokenParser parser = new JsonTokenParser(locators, checker);
JsonToken jt;
try {
jt = parser.verifyAndDeserialize(token);
} catch (SignatureException e) {
throw new RuntimeException(e);
}
JsonObject payload = jt.getPayloadAsJsonObject();
TokenInfo t = new TokenInfo();
String issuer = payload.getAsJsonPrimitive("iss").getAsString();
String userIdString = payload.getAsJsonObject("info")
.getAsJsonPrimitive("userId").getAsString();
if (issuer.equals(ISSUER) && !StringUtils.isBlank(userIdString)) {
t.setUserId(new ObjectId(userIdString));
t.setIssued(new DateTime(payload.getAsJsonPrimitive("iat")
.getAsLong()));
t.setExpires(new DateTime(payload.getAsJsonPrimitive("exp")
.getAsLong()));
return t;
} else {
return null;
}
} catch (InvalidKeyException e1) {
throw new RuntimeException(e1);
}
}
}
I would expect the user's ID in this context is either the username sent to the application by the user themselves, or some other kind of ID that you can look up based on the principal the user sent. The expiration date you simply choose. How long do you want the token to be valid before the user has to relogin? Now, on the topic of servers, there's nothing in the OAuth2 protocol mandating a server or a web context. What kind of application are you building?

inputstream null pointer exception when using modified last.fm's Caller.java

For some reason I'm getting null pointer exception. It's downloading the image here and logcat points me to call
public Result call(final String method, final String apiKey, final String... params) {
return call(method, apiKey, map(params));
}
/**
* Performs the web-service call. If the <code>session</code> parameter is
* <code>non-null</code> then an authenticated call is made. If it's
* <code>null</code> then an unauthenticated call is made.<br/>
* The <code>apiKey</code> parameter is always required, even when a valid
* session is passed to this method.
*
* #param method The method to call
* #param apiKey A Last.fm API key
* #param params Parameters
* #param session A Session instance or <code>null</code>
* #return the result of the operation
*/
public Result call(final String method, final String apiKey, Map<String, String> params) {
params = new WeakHashMap<String, String>(params);
InputStream inputStream = null;
// no entry in cache, load from web
if (inputStream == null) {
// fill parameter map with apiKey and session info
params.put(PARAM_API_KEY, apiKey);
try {
final HttpURLConnection urlConnection = openPostConnection(method, params);
inputStream = getInputStreamFromConnection(urlConnection);
if (inputStream == null) {
lastResult = Result.createHttpErrorResult(urlConnection.getResponseCode(),
urlConnection.getResponseMessage());
return lastResult;
}
} catch (final IOException ignored) {
}
}
try {
final Result result = createResultFromInputStream(inputStream);
lastResult = result;
return result;
} catch (final IOException ignored) {
} catch (final SAXException ignored) {
}
return null;
}
It finally cracks at the line "new InputSource(new InputStreamReader(inputStream, "UTF-8")));".
/**
* #param inputStream
* #return
* #throws SAXException
* #throws IOException
*/
private Result createResultFromInputStream(final InputStream inputStream) throws SAXException,
IOException {
final Document document = newDocumentBuilder().parse(
new InputSource(new InputStreamReader(inputStream, "UTF-8")));
final Element root = document.getDocumentElement(); // lfm element
final String statusString = root.getAttribute("status");
final Status status = "ok".equals(statusString) ? Status.OK : Status.FAILED;
if (status == Status.FAILED) {
final Element errorElement = (Element)root.getElementsByTagName("error").item(0);
final int errorCode = Integer.parseInt(errorElement.getAttribute("code"));
final String message = errorElement.getTextContent();
return Result.createRestErrorResult(errorCode, message);
} else {
return Result.createOkResult(document);
}
}
Any ideas? I have no idea what might be wrong. If sufficient info is provided then let me know - I'll get what you need. I'm a beginner. :)

Exception in CXF client for web service

I have generated CXF client for a secured web service (file upload) and try to call it. I have following files in my generated folder
CarbonAppUploader(class)
CarbonAppUploaderPortType(Interface)
UploadApp(class).
.........
..........
Following is my client
public class MyTest {
public static void main(String[] args) throws IOException {
JaxWsProxyFactoryBean clientFactory = new JaxWsProxyFactoryBean();
clientFactory.setAddress( "https://localhost:8243/services/CarbonAppUploader.CarbonAppUploaderHttpsEndpoint/" );
clientFactory.setServiceClass( CarbonAppUploader.class );
clientFactory.setUsername("admin");
clientFactory.setPassword("admin");
UploadApp req = new UploadApp();
FileInputStream fileInputStream;
File file1 = new File("/home/malintha/support/....../AxisCApp-1.0.0.car");
byte[] bFile = new byte[(int) file1.length()];
//convert file into array of bytes
fileInputStream = new FileInputStream(file1);
fileInputStream.read(bFile);
fileInputStream.close();
//convert array of bytes into file
FileOutputStream fileOuputStream =
new FileOutputStream("/home/malintha/support/....../AxisCApp-1.0.0.car");
fileOuputStream.write(bFile);
fileOuputStream.close();
org.wso2.carbon.application.upload.xsd.ObjectFactory of=new org.wso2.carbon.application.upload.xsd.ObjectFactory();
UploadedFileItem file=new UploadedFileItem();
file.setFileName(of.createUploadedFileItemFileName("AxisCApp-1.0.0.car"));
file.setFileName(of.createUploadedFileItemFileType("CAR"));
file.setDataHandler(of.createUploadedFileItemDataHandler(bFile));
List<UploadedFileItem> flies=new ArrayList<UploadedFileItem>();
flies.add(0,file);
UploadApp myApp = new UploadApp();
myApp.fileItems=flies;
req.getFileItems().add( file );
CarbonAppUploaderPortType uploadSvc = (CarbonAppUploaderPortType) clientFactory.create();
uploadSvc.uploadApp( req );
}
}
when I run this class I got a exception as follows
INFO: Creating Service {http://upload.application.carbon.wso2.org/}CarbonAppUploaderService from class org.wso2.carbon.application.upload.CarbonAppUploader
Exception in thread "main" java.lang.IllegalArgumentException: org.wso2.carbon.application.upload.CarbonAppUploader is not an interface
at java.lang.reflect.Proxy.getProxyClass0(Proxy.java:470)
clientFactory.create(); method call cause this exception. How can I solve this ?
This is carbonAppUploader class
#WebServiceClient(name = "CarbonAppUploader",
wsdlLocation = "file:/home/malintha/software/axis2-bin/bin/src/org/CappUpload /src/main/resources/myService.wsdl",
targetNamespace = "http://upload.application.carbon.wso2.org")
public class CarbonAppUploader extends Service {
public final static URL WSDL_LOCATION;
public final static QName SERVICE = new QName("http://upload.application.carbon.wso2.org", "CarbonAppUploader");
public final static QName CarbonAppUploaderHttpsSoap12Endpoint = new QName("http://upload.application.carbon.wso2.org", "CarbonAppUploaderHttpsSoap12Endpoint");
public final static QName CarbonAppUploaderHttpsSoap11Endpoint = new QName("http://upload.application.carbon.wso2.org", "CarbonAppUploaderHttpsSoap11Endpoint");
public final static QName CarbonAppUploaderHttpsEndpoint = new QName("http://upload.application.carbon.wso2.org", "CarbonAppUploaderHttpsEndpoint");
static {
URL url = null;
try {
url = new URL("file:/home/malintha/software/axis2-bin/bin/src/org/CappUpload/src/main/resources/myService.wsdl");
} catch (MalformedURLException e) {
java.util.logging.Logger.getLogger(CarbonAppUploader.class.getName())
.log(java.util.logging.Level.INFO,
"Can not initialize the default wsdl from {0}", "file:/home/malintha/software/axis2-bin/bin/src/org/CappUpload/src/main/resources/myService.wsdl");
}
WSDL_LOCATION = url;
}
public CarbonAppUploader(URL wsdlLocation) {
super(wsdlLocation, SERVICE);
}
public CarbonAppUploader(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
public CarbonAppUploader() {
super(WSDL_LOCATION, SERVICE);
}
/**
*
* #return
* returns CarbonAppUploaderPortType
*/
#WebEndpoint(name = "CarbonAppUploaderHttpsSoap12Endpoint")
public CarbonAppUploaderPortType getCarbonAppUploaderHttpsSoap12Endpoint() {
return super.getPort(CarbonAppUploaderHttpsSoap12Endpoint, CarbonAppUploaderPortType.class);
}
/**
*
* #param features
* A list of {#link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* #return
* returns CarbonAppUploaderPortType
*/
#WebEndpoint(name = "CarbonAppUploaderHttpsSoap12Endpoint")
public CarbonAppUploaderPortType getCarbonAppUploaderHttpsSoap12Endpoint(WebServiceFeature... features) {
return super.getPort(CarbonAppUploaderHttpsSoap12Endpoint, CarbonAppUploaderPortType.class, features);
}
/**
*
* #return
* returns CarbonAppUploaderPortType
*/
#WebEndpoint(name = "CarbonAppUploaderHttpsSoap11Endpoint")
public CarbonAppUploaderPortType getCarbonAppUploaderHttpsSoap11Endpoint() {
return super.getPort(CarbonAppUploaderHttpsSoap11Endpoint, CarbonAppUploaderPortType.class);
}
/**
*
* #param features
* A list of {#link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* #return
* returns CarbonAppUploaderPortType
*/
#WebEndpoint(name = "CarbonAppUploaderHttpsSoap11Endpoint")
public CarbonAppUploaderPortType getCarbonAppUploaderHttpsSoap11Endpoint(WebServiceFeature... features) {
return super.getPort(CarbonAppUploaderHttpsSoap11Endpoint, CarbonAppUploaderPortType.class, features);
}
/**
*
* #return
* returns CarbonAppUploaderPortType
*/
#WebEndpoint(name = "CarbonAppUploaderHttpsEndpoint")
public CarbonAppUploaderPortType getCarbonAppUploaderHttpsEndpoint() {
return super.getPort(CarbonAppUploaderHttpsEndpoint, CarbonAppUploaderPortType.class);
}
/**
*
* #param features
* A list of {#link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* #return
* returns CarbonAppUploaderPortType
*/
#WebEndpoint(name = "CarbonAppUploaderHttpsEndpoint")
public CarbonAppUploaderPortType getCarbonAppUploaderHttpsEndpoint(WebServiceFeature... features) {
return super.getPort(CarbonAppUploaderHttpsEndpoint, CarbonAppUploaderPortType.class, features);
}
}

How to do polling and get the incoming messages in a database

The incoming data has to be fed back into the polling method and also should be processed further for another class.
public List<KAAMessage> fullPoll() throws Exception {
Statement st = dbConnection.createStatement();
ResultSet rs = st.executeQuery("select * from msg_new_to_bde where ACTION = 804 order by SEQ DESC");
List<KpiMessage> pojoCol = new ArrayList<KpiMessage>();
while (rs.next()) {
KpiMessage filedClass = convertRecordsetToPojo(rs);
pojoCol.add(filedClass);
}
return pojoCol;
}
/**
* Converts a provided record-set to a {#link KpiMessage}.
*
* The following attributes are copied from record-set to pojo:
*
* <ul>
* <li>SEQ</li>
* <li>TABLENAME</li>
* <li>ENTRYTIME</li>
* <li>STATUS</li>
* </ul>
*
* #param rs
* the record-set to convert
* #return the converted pojo class object
* #throws SQLException
* if an sql error occurs during processing of recordset
*/
private KpiMessage convertRecordsetToPojo(ResultSet rs) throws SQLException {
KpiMessage msg = new KpiMessage();
int sequence = rs.getInt("SEQ");
msg.setSequence(sequence);
int action = rs.getInt("ACTION");
msg.setAction(action);
String tablename = rs.getString("TABLENAME");
msg.setTableName(tablename);
Timestamp entrytime = rs.getTimestamp("ENTRYTIME");
Date entryTime = new Date(entrytime.getTime());
msg.setEntryTime(entryTime);
Timestamp processingtime = rs.getTimestamp("PROCESSINGTIME");
if (processingtime != null) {
Date processingTime = new Date(processingtime.getTime());
msg.setProcessingTime(processingTime);
}
String keyInfo1 = rs.getString("KEYINFO1");
msg.setKeyInfo1(keyInfo1);
String keyInfo2 = rs.getString("KEYINFO2");
msg.setKeyInfo2(keyInfo2);
return msg;
}
This class has the Poll() method which reads message from the database. In the database I have SequeceID as unique number and it keeps on increasing for new data, but how can I get this new messages and feed it back to polling?
P.S: Please comment if you are down voting or closing my post because I am new here and I'd like to know the details.
this the Controller Class which runs the thread for the Poll() method.
public class RunnableController {
/** Here This Queue initializes the DB and have the collection of incoming message
*
*/
private static Collection<KaMessage> incomingQueue = new ArrayList<KAMessage>();
private Connection dbConncetion;
private ExecutorService threadExecutor;
private void initializeDb()
{
//catching exception must be adapted - generic type Exception prohibited
DBhandler con = new DBhandler();
try {
dbConncetion = con.initializeDB();
} catch (Exception e) {
e.printStackTrace();
}
}
private void initialiseThreads()
{
try {
threadExecutor = Executors.newFixedThreadPool(10);
PollingSynchronizer read = new PollingSynchronizer(incomingQueue,
dbConncetion);
threadExecutor.submit(read);
}catch (Exception e){
e.printStackTrace();
}
}
private void shutDownThreads()
{
try {
threadExecutor.shutdown();
dbConncetion.close();
}catch (Exception e){
e.printStackTrace();
}
}
/** Here This Queue passes the messages and have the collection of outgoing message
*
*/
// private Collection<KpiMessage> outgingQueue = new ArrayList<KpiMessage>();
/**
* Main
*
* #param args
* #throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
RunnableController controller = new RunnableController();
System.out.println(incomingQueue.size());
controller.initializeDb();
controller.initialiseThreads();
System.out.println("Repetetive polling for each 6 seconds");
KpiProcessor kp = new KpiProcessor();
try {
} catch (Exception e) {
e.printStackTrace();
}
}
}

Categories

Resources