NullPointerException in SNMP protocol - java

I am trying to add a client to my snmp protocol program. I added this code for my main method:
public static void main(String[] args) throws IOException{
SimpleSnmpClient client = new SimpleSnmpClient("udp:10.0.0.50/161");
String sysDescr = client.getAsString(new OID(".1.3.6.1.2.1.1.1.0"));
System.out.println(sysDescr);
}
and the site I learned from said the output should be about some kind of information about the device run this program.
My SimpleSnmpClient code:
public class SimpleSnmpClient {
private String address;
private Snmp snmp;
public static void main(String[] args) throws IOException{
SimpleSnmpClient client = new SimpleSnmpClient("udp:10.0.0.50/161");
String sysDescr = client.getAsString(new OID(".1.3.6.1.2.1.1.1.0"));
System.out.println(sysDescr);
}
public SimpleSnmpClient(String address) {
super();
this.address = address;
try {
start();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// Since snmp4j relies on asynch req/resp we need a listener
// for responses which should be closed
public void stop() throws IOException {
snmp.close();
}
private void start() throws IOException {
TransportMapping transport = new DefaultUdpTransportMapping();
snmp = new Snmp(transport);
// Do not forget this line!
transport.listen();
}
public String getAsString(OID oid) throws IOException {
ResponseEvent event = get(new OID[]{oid});
return event.getResponse().get(0).getVariable().toString();
}
public void getAsString(OID oids,ResponseListener listener) {
try {
snmp.send(getPDU(new OID[]{oids}), getTarget(),null, listener);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private PDU getPDU(OID oids[]) {
PDU pdu = new PDU();
for (OID oid : oids) {
pdu.add(new VariableBinding(oid));
}
pdu.setType(PDU.GET);
return pdu;
}
public ResponseEvent get(OID oids[]) throws IOException {
ResponseEvent event = snmp.send(getPDU(oids), getTarget(), null);
if(event != null) {
return event;
}
throw new RuntimeException("GET timed out");
}
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;
}
/**
* Normally this would return domain objects or something else than this...
*/
public List<List<String>> getTableAsStrings(OID[] oids) {
TableUtils tUtils = new TableUtils(snmp, new DefaultPDUFactory());
#SuppressWarnings("unchecked")
List<TableEvent> events = tUtils.getTable(getTarget(), oids, null, null);
List<List<String>> list = new ArrayList<List<String>>();
for (TableEvent event : events) {
if(event.isError()) {
throw new RuntimeException(event.getErrorMessage());
}
List<String> strList = new ArrayList<String>();
list.add(strList);
for(VariableBinding vb: event.getColumns()) {
strList.add(vb.getVariable().toString());
}
}
return list;
}
public static String extractSingleString(ResponseEvent event) {
return event.getResponse().get(0).getVariable().toString();
}
}
But I received NULLPointerException:
Exception in thread "main" java.lang.NullPointerException
at org.bihe.SimpleSnmpClient.getAsString(SimpleSnmpClient.java:70)
at org.bihe.SimpleSnmpClient.main(SimpleSnmpClient.java:41)
It refer to the line:
return event.getResponse().get(0).getVariable().toString();
and I have no idea why it is happening? Can anyone help me to solve this problem?

If you time-out you can get a null response. From the ResponseEvent docs: "a PDU instance if a response has been received. If the request timed out then null will be returned."
Perhaps you server isn't up or isn't available. Try accessing it with some known app like snmpwalk just to distinguish your code from some network issue.

Does the device you are trying to get a response from have a community string set? A community is like a password, and is set on a device to prevent people from retrieving information from this device without authorization. If the community string is incorrect, you won't receive a response.

make sure you added same community string for SNMP service agent.
for windows...
open services -> right click in SNMP - > under security tab ->add community String

I faced the same issue today. And, I resolved it by doing the following:
Type "services.msc" in Windows Run dialog box and hit enter. This
will open the Services window.
Double click on the "SNMP Service" and select "Security" tab. In
"Accepted Community Names" section, add the community name "public"
with Security level "READ ONLY" or "READ WRITE" (based on your need).
Then click OK button to finish this process.
Now, try to run the program. It will return the result.
I've got the below while running it from NetBeans on my Windows 10 Operating System.
Output:
Hardware: Intel64 Family 6 Model 60 Stepping 3 AT/AT COMPATIBLE - Software: Windows Version 6.3 (Build 16299 Multiprocessor Free)

Related

Angular 8 socket.io-client 2.2.0 and Java netty-socket.io message not being received?

I am using netty-socket.io and I implemented the server like the demo.
I receive onConnect event both on server and client, but when I sent a message {message: message} I don't get anything on the server event though I see the message being sent in the network tab.
Configuration config = new Configuration();
config.setHostname("localhost");
config.setPort(9092);
final SocketIOServer server = new SocketIOServer(config);
server.addConnectListener(socketIOClient -> System.out.println("Connection test"));
server.addEventListener("messageevent", MessageEventObject.class, new DataListener<MessageEventObject>() {
#Override
public void onData(SocketIOClient socketIOClient, MessageEventObject messageEventObject, AckRequest ackRequest) throws Exception {
System.out.println("message received!");
}
});
server.start();
My MessageEventObject has String message property, constructor getters and setters, looking the same as client-sided.
And this is my websocket service client-sided:
export class WebsocketService {
private socket;
private subject = new Subject < any > ();
constructor() {
console.log('test!');
}
public connect(host: string, port: number) {
this.socket = io(`http://${host}:${port}`, {
'reconnection': false
});
this.socket.on('connect', this.onConnected);
this.socket.on('connect_error', this.onConnectionFailure);
}
public getConnectionStateUpdate(): Observable < any > {
return this.subject.asObservable();
}
public sendMessage(message: string) {
console.log('test');
this.socket.emit('messageevent', {
message: message
});
}
private onConnected = () => {
this.subject.next({
connected: true
});
}
private onConnectionFailure = () => {
this.subject.next({
connected: false
});
}
}
Is there anything that I did wrong?
I would love to answer my own question after tons of debugging and breaking my head, my laziness to use Engine IO with tomcat or jetty, and just wanting to use that awesome netty package which does not require any servlets, I tried to fix it and figure out.
At first I thought it was the client's protocol version, so I used the exact same client as the demo shows on their github page here but that didn't work so the problem is server-sided.
It appears that your object (MessageEventObject) must have a default empty constructor aswell in addition to your other constructors, probably because netty tries to build an empty object and it fails which causes an exception that you don't see.

NullPointerException while connecting to Mqtt on-line broker

I'm trying to connect to the on-line broker https://test.mosquitto.org/ using the code below and the Paho library in Java:
private final String brokerURI = "test.mosquitto.org:1883"; //should be changed to 8883 with SSL
try { //tentativo di creazione del client
client = new MqttClient(brokerURI, idClient); <--NullPointerException here
client.setCallback(new ClientCallback(codaTopic, codaMessaggi, finestra)); //set delle callback
setConnectionOptions(); //set delle opzioni connessione
client.connect(opzioni); //connessione al server
} catch (MqttException e) {
System.err.println(e.getMessage());
System.err.println("Connessione fallita Client, riavviare il sistema.");
}
Connection options are set here:
private void setConnectionOptions() {
opzioni = new MqttConnectOptions();
opzioni.setAutomaticReconnect(true);
opzioni.setCleanSession(false);
opzioni.setConnectionTimeout(30);
opzioni.setKeepAliveInterval(60);
}
but it continues to show a NullPointerException while creating the MqttClient. In particular the console displays:
Exception in thread "Thread-3" java.lang.NullPointerException
at org.eclipse.paho.client.mqttv3.MqttConnectOptions.validateURI(MqttConnectOptions.java:489)
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.<init>(MqttAsyncClient.java:291)
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.<init>(MqttAsyncClient.java:185)
at org.eclipse.paho.client.mqttv3.MqttClient.<init>(MqttClient.java:226)
at org.eclipse.paho.client.mqttv3.MqttClient.<init>(MqttClient.java:138)
at client.Client.run(Client.java:78)
How can i manage to connect and use SSL?
Surfing the net none of the tutorial or guides were useful, I already downloaded the mosquitto.org.crtfile for SSL connection, but i don't know where to use it and I found no tutorials.
EDIT
Changing the BrokerUri to
private final String brokerURI = "tcp://test.mosquitto.org:1883"; //indirizzo broker
the console shows the error
Client non connesso (32104)
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:31)
at org.eclipse.paho.client.mqttv3.internal.ClientComms.sendNoWait(ClientComms.java:166)
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.subscribe(MqttAsyncClient.java:835)
at org.eclipse.paho.client.mqttv3.MqttClient.subscribe(MqttClient.java:322)
at org.eclipse.paho.client.mqttv3.MqttClient.subscribe(MqttClient.java:315)
at client.Client.subscribe(Client.java:214)
at client.Client.run(Client.java:89)
while trying to subscribe to a Topic with the instruction
client.subscribe(topic, 1);
The topic argument is a String that contains the topic name.
Mosquitto's URI needs the protocol. Taking a look at its source code, this is where your exception is being thrown, class MqttConnectOpts.java :
protected static int validateURI(String srvURI) {
try {
URI vURI = new URI(srvURI);
if (!vURI.getPath().equals("")) {
throw new IllegalArgumentException(srvURI);
}
if (vURI.getScheme().equals("tcp")) {
return URI_TYPE_TCP;
}
else if (vURI.getScheme().equals("ssl")) {
return URI_TYPE_SSL;
}
else if (vURI.getScheme().equals("local")) {
return URI_TYPE_LOCAL;
}
else {
throw new IllegalArgumentException(srvURI);
}
} catch (URISyntaxException ex) {
throw new IllegalArgumentException(srvURI);
}
}
So, it accepts 3 types of protocol prefixes: tcp, ssl, local. Regarding your example, you could try it this way:
TCP
private final String brokerURI = "tcp://test.mosquitto.org:1883";
SSL
private final String brokerURI = "ssl://test.mosquitto.org:8883";

Connecting to SSL WebService

I want to connect to a web service in a SSL connection. I connect to it and I get Service and Port but when I send Requests, it just returns null.
I searched the web but I could not understand what is the problem. may be because it is SSL, I need to connect it different as an Http connection, is it true?
I used auto code generators, they return null too, WireShark says that SSL Packages transmitted correctly but I cannot read the SOAP from these packages because they are SSL.
I test the web service with some applications and the tools and got correct answers from them.
Question:
is it possible that the null value is because SSL connection?
what mistakes could make this null returning?
How can I see the SOAP messeges I send and I get?
Here is My Java Code:
public class WS_TheServeice
{
private static QName qname;
private static URL url;
private static Service service;
private static ImplementationServicePortType sender;
static
{
qname = new QName("http://wservice.com/", "ImplementationService");
try
{
url = new URL("https://to-service?wsdl");
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
service = Service.create(url, qname);
sender = service.getPort(ImplementationServicePortType.class);
}
public static boolean PayToAcceptor(int AcceptorID, int Kipa) throws Exception
{
getUserInfo req = new getUserInfo();
req.zpID = AcceptorID;
req.kipa = Kipa;
getUserInfoResponse user_info = new getUserInfoResponse();//user_info is not NULL here
user_info = sender.getUserInfo(req);//But web server makes it NULL
if (user_info!=null) //// ---- HERE, IT Always return NULL
{
System.out.println("YouWon");
return true;
}
else
{
System.out.println("YouLoose");
return false;
}
}
public static void main(String Args[]) throws Exception
{
PayToAcceptor(12345, 1);
}
}
thanks.
Did you figure out how to do this? I've had similar problems in the past..
Did you try this: SSL Connection for consuming web services ?

Java Kryonet servers, client not receiving server response

I am trying to teach myself some networking in Java using the Kryonet library. The following code is almost identical to the code in the kyronet tutorial. https://code.google.com/p/kryonet/#Running_a_server
The client is successfully sending the message "Here is the request!" to the server (the server is printing it out) however the client is not receiving any response from the server even though the server is sending one.
I've tried unsuccessfully to fix it, can anyone see or suggest a possible problem/solution with the code?
(The code follows)
Client
public class Client_test {
Client client = new Client();
public Client_test() {
Kryo kryo = client.getKryo();
kryo.register(SomeRequest.class);
kryo.register(SomeResponse.class);
client.start();
try {
client.connect(50000, "127.0.0.1", 54555, 54777);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
client.addListener(new Listener() {
public void received (Connection connection, Object object) {
if (object instanceof SomeResponse) {
SomeResponse response = (SomeResponse)object;
System.out.println(response.text);
}
}
});
SomeRequest request = new SomeRequest();
request.text = "Here is the request!";
client.sendTCP(request);
}
}
Server
public class ServerGame {
Server server = new Server();
public ServerGame() {
Kryo kryo = server.getKryo();
kryo.register(SomeRequest.class);
kryo.register(SomeResponse.class);
server.start();
try {
server.bind(54555, 54777);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
server.addListener(new Listener() {
public void received (Connection connection, Object object) {
if (object instanceof SomeRequest) {
SomeRequest request = (SomeRequest)object;
System.out.println(request.text);
SomeResponse response = new SomeResponse();
response.text = "Thanks!";
connection.sendTCP(response);
}
}
});
}
}
Response & Request classes
public class SomeRequest {
public String text;
public SomeRequest(){}
}
public class SomeResponse {
public String text;
public SomeResponse(){}
}
After many hours watching youtube videos and sifting through the web I found the answer. Which I will post on here as it seems that quite a few people have had this problem so I would like to spread the word.
Basically the client would shut down immediately, before it could receive and output the message packet. This is because "Starting with r122, client update threads were made into daemon threads, causing the child processes to close as soon as they finish initializing.", the solution is "Maybe you could use this? new Thread(client).start();".
So basically instead of using
client.start();
to start the client thread you must use
new Thread(client).start();
Which I believe stops the thread being made into a daemon thread which therefore stops the problem.
Source: https://groups.google.com/forum/?fromgroups#!topic/kryonet-users/QTHiVmqljgE
Yes, inject a tool like Fiddler in between the two so you can see the traffic going back and forth. It's always easier to debug with greater transparency, more information.

Custom gRPC command for Dropwizard exits immediately

I've created an application using Dropwizard that starts a gRPC server. I do not use the regular server, and want to start my application using java -jar my-fat.jar grpc config.yml instead.
I've come as far as to add the command as the only available command during startup by overriding the corresponding method in the application class:
public class App extends Application<Configuration> {
public static void main(String[] args) throws Exception {
new App().run(args);
}
#Override
protected void addDefaultCommands(final Bootstrap<Configuration> bootstrap) {
bootstrap.addCommand(new GrpcCommand(this));
}
}
I can launch my application using java -jar my-fat.jar grpc config.yml. My command looks like this:
public class GrpcCommand extends EnvironmentCommand<Configuration> {
public GrpcCommand(Application<Configuration> application) {
this(application, "grpc", "Runs the Dropwizard application as a gRPC server");
}
/**
* Creates a new environment command.
*
* #param application the application providing this command
* #param name the name of the command, used for command line invocation
* #param description a description of the command's purpose
*/
protected GrpcCommand(final Application<Configuration> application, final String name, final String description) {
super(application, name, description);
}
#Override
protected void run(final Environment environment, final Namespace namespace, final Configuration configuration) throws Exception {
final var certificateService = AzureCertificateService.createWithClients(
AzureSecretClient.create(configuration.getKeyVaultConfiguration()),
AzureCertificateClient.create(configuration.getKeyVaultConfiguration())
);
final var validationService = CertificateValidationService.create(certificateService);
final var signingService = CertificateSigningService.create(certificateService);
final Pair<X509Certificate, KeyPair> certificate = certificateService.getSigningCertificateWithKeyPair();
final BaseApiImpl baseApi = new BaseApiImpl(validationService, signingService);
final GrpcServer grpcServer = GrpcServer.newBuilder()
.withBaseApi(baseApi)
.withConfiguration(configuration.getGrpcConfiguration())
.withCertificate(certificate.getLeft())
.withPrivateKey(certificate.getRight().getPrivate())
.build();
new Thread(() -> {
try {
grpcServer.start();
} catch (Exception e) {
e.printStackTrace();
}
}).run();
environment.healthChecks().register("grpc-server", new GrpcServerHealthCheck(grpcServer));
}
}
The way that thread is started is not for production use, I'm just trying to get forward. The start method for the GrpcServer class:
#Override
public void start() throws Exception {
final NettyServerBuilder nettyServerBuilder = NettyServerBuilder.forPort(configuration.getPort())
.addService(baseApi)
.intercept(new OriginInterceptor());
if (certificate != null && privateKey != null) {
LOG.info("Got certificate and private key, enabling SSL");
nettyServerBuilder.sslContext(buildSslContext());
}
server = nettyServerBuilder
.build()
.start();
LOG.info("Server started at port {}", server.getPort());
}
And I see the message GrpcServer: Server started at port 50441 in my log when I start. However, the application does not stay open. What am I missing? Shouldn't my use of the thread create a thread that stops the application from exiting? How can I keep the application running after the gRPC server has started?
When I disabled the server command, Jetty isn't started either (of course), which kept the application alive previously.
I found the simplest solution in the gRPC Hello World Example.
My start method now looks like this:
public void start() throws Exception {
// Everything else as above
Runtime.getRuntime().addShutdownHook(new Thread(GrpcServer.this::stop));
LOG.info("Server started at port {}", server.getPort());
blockUntilShutdown();
}
private void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}

Categories