I need to make an agent in SNMP4J, but the documentation on how to get started is pretty poor. Does anyone have any experience with SNMP4J and could give me an idea on how to get started? Thanks.
You can download the source code for SNMP4JAgent here:
http://www.snmp4j.org/html/download.html
The source code includes a sample agent -- look in the org.snmp4j.agent.example package for all of the related classes.
http://www.snmp4j.org/agent/doc/org/snmp4j/agent/example/SampleAgent.html
One way of getting started would be to create an agent using the example code and then modify it to suit your needs. The JavaDoc describing each of the classes is a bit terse, but it's complete.
Good documentation of SNMPv3 implementation using SNMP4j libraries is really hard to find. There are no working examples of SNMPv3 agents in the official documentation. I wrote a basic SNMP Agent that can connect using SNMPv3 protocol, and perform GET and SET operations on the server.
import java.io.IOException;
import org.snmp4j.PDU;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.UserTarget;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.MPv3;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.security.AuthGeneric;
import org.snmp4j.security.AuthSHA;
import org.snmp4j.security.PrivAES128;
import org.snmp4j.security.PrivacyGeneric;
import org.snmp4j.security.SecurityModels;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.security.USM;
import org.snmp4j.security.UsmUser;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.TransportIpAddress;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultTcpTransportMapping;
import org.snmp4j.transport.DefaultUdpTransportMapping;
public class SNMPV3Agent {
private Address nmsIP;
private String user;
private String securityName;
private String privacyPassword;
private String authorizationPassword;
private AuthGeneric authProtocol;
private PrivacyGeneric privacyProtocol;
private String protocol;
private long timeOut = 1000L;
private int noOfRetries = 2;
private Snmp snmp;
private UserTarget target;
SNMPV3Agent(String ip, String protocol, int snmpPort, String username,
String securityName, String privacyPassword, String authPassowrd,
AuthGeneric authProtocol, PrivacyGeneric privacyProtocol) {
nmsIP = GenericAddress.parse(protocol + ":" + ip + "/" + snmpPort);
System.out.println("NMS IP set : " + nmsIP.toString());
this.protocol = protocol;
this.user = username;
this.securityName = securityName;
this.privacyPassword = privacyPassword;
this.authorizationPassword = authPassowrd;
this.authProtocol = authProtocol;
this.privacyProtocol = privacyProtocol;
}
public static void main(String[] args) {
SNMPV3Agent agent = new SNMPV3Agent("nms/server-ip", "udp", 162,
"abhinav", "abhinav", "myprivpass", "myauthpass",
new AuthSHA(), new PrivAES128());
try {
agent.startAgent();
ResponseEvent response = agent
.snmpGetOperation(SnmpConstants.sysName);
System.out.println(response.getResponse());
// Similarly you can perform set operation.
} catch (IOException e) {
e.printStackTrace();
}
}
public void startAgent() throws IOException {
if (snmp == null) {
TransportMapping<? extends TransportIpAddress> transport = null;
if (protocol.equalsIgnoreCase("udp")) {
System.out.println("UDP Protocol selected.");
transport = new DefaultUdpTransportMapping();
} else {
System.out.println("TCP Protocol selected.");
transport = new DefaultTcpTransportMapping();
}
snmp = new Snmp(transport);
USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(
MPv3.createLocalEngineID()), 0);
SecurityModels.getInstance().addSecurityModel(usm);
transport.listen();
snmp.getUSM().addUser(
new OctetString(user),
new UsmUser(new OctetString(securityName), authProtocol
.getID(), new OctetString(authorizationPassword),
privacyProtocol.getID(), new OctetString(
privacyPassword)));
target = createUserTarget();
}
}
public ResponseEvent snmpSetOperation(VariableBinding[] vars)
throws IOException {
PDU setPdu = new ScopedPDU();
for (VariableBinding variableBinding : vars) {
setPdu.add(variableBinding);
}
return snmp.send(setPdu, target);
}
public ResponseEvent snmpGetOperation(OID oid) throws IOException {
PDU getPdu = new ScopedPDU();
getPdu.add(new VariableBinding(oid));
return snmp.get(getPdu, target);
}
private UserTarget createUserTarget() {
UserTarget target = new UserTarget();
target.setAddress(nmsIP);
target.setRetries(noOfRetries);
target.setTimeout(timeOut);
target.setVersion(3);
target.setSecurityLevel(3);
target.setSecurityName(new OctetString(securityName));
return target;
}
public long getTimeOut() {
return timeOut;
}
public void setTimeOut(long timeOut) {
this.timeOut = timeOut;
}
public int getNoOfRetries() {
return noOfRetries;
}
public void setNoOfRetries(int noOfRetries) {
this.noOfRetries = noOfRetries;
}
}
Adding other operations such as GETBulk will be relatively easy once you understand how GET and SET works. Let me know if you need more clarifications in the comments.
Here is a great link that describes the snmp class which is the core of snmp4j
http://www.snmp4j.org/doc/org/snmp4j/package-summary.html
Also take a look at the SnmpRequest.java for a quick example
Related
Trying everyting but it does not work :(
The complete code and example can be found here: https://examples.javacodegeeks.com/core-java/nio/java-nio-ssl-example/
Also you can download the full source (it is only 3 classes) by clicking here: https://examples.javacodegeeks.com/wp-content/uploads/2015/12/NioSSLExample.zip
Thanks for any help!
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;
public class NioSSLExample
{
public static void main(String[] args) throws Exception
{
InetSocketAddress address = new InetSocketAddress("www.amazon.com", 443);
Selector selector = Selector.open();
SocketChannel channel = SocketChannel.open();
channel.connect(address);
channel.configureBlocking(false);
int ops = SelectionKey.OP_CONNECT | SelectionKey.OP_READ;
SelectionKey key = channel.register(selector, ops);
// create the worker threads
final Executor ioWorker = Executors.newSingleThreadExecutor();
final Executor taskWorkers = Executors.newFixedThreadPool(2);
// create the SSLEngine
final SSLEngine engine = SSLContext.getDefault().createSSLEngine();
engine.setUseClientMode(true);
engine.beginHandshake();
final int ioBufferSize = 32 * 1024;
final NioSSLProvider ssl = new NioSSLProvider(key, engine, ioBufferSize, ioWorker, taskWorkers)
{
#Override
public void onFailure(Exception ex)
{
System.out.println("handshake failure");
ex.printStackTrace();
}
#Override
public void onSuccess()
{
System.out.println("handshake success");
SSLSession session = engine.getSession();
try
{
System.out.println("local principal: " + session.getLocalPrincipal());
System.out.println("remote principal: " + session.getPeerPrincipal());
System.out.println("cipher: " + session.getCipherSuite());
}
catch (Exception exc)
{
exc.printStackTrace();
}
//HTTP request
StringBuilder http = new StringBuilder();
http.append("GET / HTTP/1.0\r\n");
http.append("Connection: close\r\n");
http.append("\r\n");
byte[] data = http.toString().getBytes();
ByteBuffer send = ByteBuffer.wrap(data);
this.sendAsync(send);
}
#Override
public void onInput(ByteBuffer decrypted)
{
// HTTP response
byte[] dst = new byte[decrypted.remaining()];
decrypted.get(dst);
String response = new String(dst);
System.out.print(response);
System.out.flush();
}
#Override
public void onClosed()
{
System.out.println("ssl session closed");
}
};
// NIO selector
while (true)
{
key.selector().select();
Iterator keys = key.selector().selectedKeys().iterator();
while (keys.hasNext())
{
keys.next();
keys.remove();
ssl.processInput();
}
}
}
}
http.append("GET / HTTP/1.0\r\n");
http.append("Connection: close\r\n");
http.append("\r\n");
While this is in theory a correct HTTP/1.0 request in practice, most systems today require that a Host header is included. While this is mandatory only with HTTP/1.1 it is needed if an IP address hosts multiple domains:
http.append("GET / HTTP/1.0\r\n");
http.append("Host: www.amazon.com\r\n");
http.append("\r\n");
Also note that the Connection: close is unnecessary since it is implicit with HTTP/1.0 (but not with HTTP/1.1).
Apart from that HTTP is way more complex than this simple request and even this one had its problems as you saw. If you need to implement it for yourself please study the standards instead of making assumptions of how servers react or looking only at a few examples.
Can some one give me a direction how can I implement this aws email template tutorial by a java code? Through java code I want to set this AWS Email Template and through java only I want to set the parameter values to the template and through java only I want to send the email.
I cant find any tutorial or direction from which I can translate above requests in java code.
The "code" in your link is actually just some JSON templates for sending and formatting email, and a few calls to an AWS command line tool. If you need to make AWS send email calls from a Java process then you need to take a look at:
The SES API
The Javadoc for the Java client lib
I am able to code it successfully. Pasting the example code here.
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder;
import com.amazonaws.services.simpleemail.model.BulkEmailDestination;
import com.amazonaws.services.simpleemail.model.BulkEmailDestinationStatus;
import com.amazonaws.services.simpleemail.model.Destination;
import com.amazonaws.services.simpleemail.model.SendBulkTemplatedEmailRequest;
import com.amazonaws.services.simpleemail.model.SendBulkTemplatedEmailResult;
public class AmazonSESSample2 {
public static void main(String[] args) throws IOException {
String accessKeyId = "accessKeyId";
String secretKeyId = "secretKeyId";
String region = "us-east-1";
List<BulkEmailDestination> listBulkEmailDestination = null;
SendBulkTemplatedEmailRequest sendBulkTemplatedEmailRequest = null;
try {
AmazonSimpleEmailService client = getAmazonSESClient(accessKeyId, secretKeyId, region);
listBulkEmailDestination = new ArrayList<>();
for(String email : getRecievers()) {
String replacementData="{"
+ "\"FULL_NAME\":\"AAA BBB\","
+ "\"USERNAME\":\""+email+"\","
+ "}";
BulkEmailDestination bulkEmailDestination = new BulkEmailDestination();
bulkEmailDestination.setDestination(new Destination(Arrays.asList(email)));
bulkEmailDestination.setReplacementTemplateData(replacementData);
listBulkEmailDestination.add(bulkEmailDestination);
}
sendBulkTemplatedEmailRequest = new SendBulkTemplatedEmailRequest();
sendBulkTemplatedEmailRequest.setSource("noreply#mydomain.com");
sendBulkTemplatedEmailRequest.setTemplate("welcome-email-en_GB-v1");
sendBulkTemplatedEmailRequest.setDefaultTemplateData("{\"FULL_NAME\":\"friend\", \"USERNAME\":\"unknown\"}");
sendBulkTemplatedEmailRequest.setDestinations(listBulkEmailDestination);
SendBulkTemplatedEmailResult res = client.sendBulkTemplatedEmail(sendBulkTemplatedEmailRequest);
System.out.println("======================================");
System.out.println(res.getSdkResponseMetadata());
System.out.println("======================================");
for(BulkEmailDestinationStatus status : res.getStatus()) {
System.out.println(status.getStatus());
System.out.println(status.getError());
System.out.println(status.getMessageId());
}
} catch (Exception ex) {
System.out.println("The email was not sent. Error message: " + ex.getMessage());
ex.printStackTrace();
}
}
public static List<String> getRecievers() {
ArrayList<String> list = new ArrayList<>();
list.add("aaa+1#gmail.com");
list.add("aaa+2#gmail.com");
list.add("aaa+3#gmail.com");
list.add("aaa+4#gmail.com");
return list;
}
public static AmazonSimpleEmailService getAmazonSESClient(String accessKeyId, String secretKeyId, String region) {
BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKeyId, secretKeyId);
AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.withRegion(region)
.build();
return client;
}
}
In my application (java) I need to support two types of RPCs:
Administration RPC and User RPC. I am using avro to create these RPCs, currently I am opening two HttpServers one per RPC using code similar to the following:
Server serverAdmins = new HttpServer(new ReflectResponder(AdministrationRPC.class, arpcImpl), adminRpcPort);
Server serverUsers = new HttpServer(new ReflectResponder(UsersRPC.class, urpcImpl), usersRpcPort);
...
This works, but it look like a waste for me - I am looking for a way to use a single http server with two ports or two urls on the same port (any of these options is good for me), something like:
Server server = new new HttpServer(new ReflectResponder(AdministrationRPC.class, arpcImpl), adminRpcPort);
server.addResponder(new ReflectResponder(UsersRPC.class, urpcImpl), usersRpcPort);
...
the addResponder method does not exists of course, the only method that looks similar is the addConnector method - but even after thorough googling I couldn't find how to apply it to my needs..
Is there a way to start two avro responders on the same http server?
I managed to resolve this issue by writing a simple class which allow for what I want, see code below.
import java.io.IOException;
import java.net.URL;
import org.apache.avro.ipc.HttpTransceiver;
import org.apache.avro.ipc.Responder;
import org.apache.avro.ipc.ResponderServlet;
import org.apache.avro.ipc.reflect.ReflectRequestor;
import org.apache.avro.ipc.reflect.ReflectResponder;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;
/**
*
* #author bennyl
*/
public class MultiResponderHttpServer {
private final Context context;
private final Server server;
private final int port;
public MultiResponderHttpServer(int port) {
this.port = port;
server = new Server(port);
context = new Context(server, "/", Context.SESSIONS);
}
public void addResponder(String baseUri, Responder responder) throws IOException {
ResponderServlet servlet = new ResponderServlet(responder);
ServletHolder holder = new ServletHolder(servlet);
context.addServlet(holder, baseUri);
}
public int getPort() {
return port;
}
public void close() throws Exception {
server.stop();
}
public void start() throws Exception {
server.start();
}
public void join() throws InterruptedException {
server.join();
}
public static void main(String[] args) throws IOException, InterruptedException {
MultiResponderHttpServer server = new MultiResponderHttpServer(8888);
server.addResponder("/test_a/*", new ReflectResponder(TestProtocol.class,
(TestProtocol) why -> "a received a message: '" + why + "'"));
server.addResponder("/test_b/*", new ReflectResponder(TestProtocol.class,
(TestProtocol) why -> "b received a message: '" + why + "'"));
server.start();
HttpTransceiver atrans = new HttpTransceiver(new URL("http://localhost:" + server.getPort() + "/test_a/"));
HttpTransceiver btrans = new HttpTransceiver(new URL("http://localhost:" + server.getPort() + "/test_b/"));
System.out.println(ReflectRequestor.getClient(TestProtocol.class, atrans).go("message to a"));
System.out.println(ReflectRequestor.getClient(TestProtocol.class, btrans).go("message to b"));
server.close();
server.join();
}
public interface TestProtocol {
String go(String why);
}
}
I'm trying to make a search through the Fedora Commons web service. I'm interested in the findObjects method. How can I make a search in Java equal to the example described on the findObjects syntax documentation.
I'm particularly interested in this type of request:
http://localhost:8080/fedora/search?terms=fedora&pid=true&title=true
I'll attach some code, I have a class that can call my Fedora service already.
package test.fedora;
import info.fedora.definitions._1._0.types.DatastreamDef;
import info.fedora.definitions._1._0.types.MIMETypedStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import javax.xml.ws.BindingProvider;
import org.w3c.dom.Document;
public class FedoraAccessor {
info.fedora.definitions._1._0.api.FedoraAPIAService service;
info.fedora.definitions._1._0.api.FedoraAPIA port;
final String username = "xxxx";
final String password = "yyyy";
public FedoraAClient() {
service = new info.fedora.definitions._1._0.api.FedoraAPIAService();
port = service.getFedoraAPIAServiceHTTPPort();
((BindingProvider) port.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, username);
((BindingProvider) port).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);
}
public List findObjects() {
//how?
}
public List<DatastreamDef> listDatastreams(String pid, String asOfTime) {
List<DatastreamDef> result = null;
try {
result = port.listDatastreams(pid, asOfTime);
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
}
It's easier using the client from mediashelf (http://mediashelf.github.com/fedora-client/). Here's an example searching for objects containing the string foobar in the title:
#Test
public void doTest() throws FedoraClientException {
connect();
FindObjectsResponse response = null;
response = findObjects().pid().title().query("title~foobar").execute(fedoraClient);
List<String> pids = response.getPids();
List<String> titles = new ArrayList<String>();
for (String pid : pids) {
titles.add(response.getObjectField(pid, "title").get(0));
}
assertEquals(7, titles.size());
}
Greetings!
I am trying to find a way in Java to programmatically enable/disable a port on a network switch over SNMP. I tried using SNMP4J but couldn't get much help on the mailing list on how to use it. I'm not too concerned what library is used (open source vs commercial) as long as it gets the job done.
The switch I am trying to work with is a Cisco 3750 switch.
Regards,
James
You can use following simple code to enable/disable switch port using snmp4j.
It enables port 1 and disables port 6.
package com.mobinet.snmp;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.Integer32;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultTcpTransportMapping;
/**
*
* #author batbayar
*/
public class SnmpTest {
private String address = "192.168.1.254/161"; // switch address and snmp port
private String writeCommunity = "myCommunityWrite"; // write community name
private Snmp snmp;
private CommunityTarget target;
public SnmpTest() {
try {
TransportMapping transport = new DefaultTcpTransportMapping();
snmp = new Snmp(transport);
Address targetAddress = GenericAddress.parse(address);
target = new CommunityTarget();
target.setCommunity(new OctetString(writeCommunity));
target.setAddress(targetAddress);
target.setRetries(2);
target.setTimeout(1500);
target.setVersion(SnmpConstants.version2c);
PDU command = new PDU();
command.setType(PDU.SET);
command.add(new VariableBinding(new OID("1.3.6.1.2.1.2.2.1.7.1"), new Integer32(2))); // port 1 down
command.add(new VariableBinding(new OID("1.3.6.1.2.1.2.2.1.7.6"), new Integer32(1))); // port 6 up
ResponseEvent response = snmp.send(command, target);
System.out.println("response: " + response);
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SnmpTest test = new SnmpTest();
}
}
I have had good luck with the Westhawk Java SNMP stack.
For a simple SNMP set, the syntax will look something like this:
public static boolean setOid(String hostAddress, int portNumber, String communityName, String oidToSet, String valueToSet) {
SnmpContextPool context = null;
try {
context = new SnmpContextPool(hostAddress, portNumber, SnmpContextFace.STANDARD_SOCKET);
context.setCommunity(communityName);
SetPdu oneSetPdu = new SetPdu(context);
AsnObject obj = new AsnOctets(valueToSet); // use AsnInteger here if you are setting an integer value
oneSetPdu.addOid(oidToSet, obj);
return oneSetPdu.send();
} catch (Exception e) {
//TODO: Handle exceptions properly
e.printStackTrace();
} finally {
if (context != null) {
context.destroy();
}
}
return false;
}
You could try reading the docs...
A (nearly) complete example for the
SNMP4J API usage is the console tool.
It can be found in the
org.snmp4j.tools.console.SnmpRequest
class.