SNMP4J adding user - snmp

I've been doing some very basic SNMP4J programming. All I want to do is send a simple "get" request but so far my responses have been null. I opened up wireshark and found that in the under Simple Network Management Protocol, my msgUserName is blank and I need that to be populated.
I thought I had set it using the following code:
Snmp snmp = new Snmp(transport);
USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
SecurityModels.getInstance().addSecurityModel(usm);
transport.listen();
UsmUser user = new UsmUser(new OctetString("SNMPManager"), AuthSHA.ID,new OctetString("password"),null,null);
// add user to the USM
snmp.getUSM().addUser(user.getSecurityName(), user);
Am I going about it the wrong way? If not, how do I set the msgUserName as seen in my wireshark dump of the get-request? I'm very new to SNMP, so I'm essentially running off examples.

This is a working snmpset you can write snmp get same way.Snmp4j v2 and v3 not using same api classes.
private void snmpSetV3(VariableBinding[] bindings) throws TimeOutException, OperationFailed {
Snmp snmp = null;
try {
PDU pdu = new ScopedPDU();
USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
SecurityModels.getInstance().addSecurityModel(usm);
snmp = new Snmp(new DefaultUdpTransportMapping());
snmp.getUSM().addUser(new OctetString(Username), new UsmUser(new OctetString(Username), AuthMD5.ID, new OctetString(Password), AuthMD5.ID, null));
ScopedPDU scopedPDU = (ScopedPDU) pdu;
scopedPDU.setType(PDU.SET);
scopedPDU.addAll(bindings);
UserTarget target = new UserTarget();
target.setAddress(new UdpAddress(IPAddress + "/" + Port));
target.setVersion(version); //SnmpConstants.version3
target.setRetries(retries);
target.setTimeout(timeout);
target.setSecurityLevel(securityLevel); //SecurityLevel.AUTH_NOPRIV
target.setSecurityName(new OctetString(Username));
snmp.listen();
ResponseEvent response = snmp.send(pdu, target);
if (response.getResponse() != null) {
PDU responsePDU = response.getResponse();
if (responsePDU != null) {
if (responsePDU.getErrorStatus() == PDU.noError) {
return;
}
throw new OperationFailed("Error: Request Failed, "
+ "Error Status = " + responsePDU.getErrorStatus()
+ ", Error Index = " + responsePDU.getErrorIndex()
+ ", Error Status Text = " + responsePDU.getErrorStatusText());
}
}
throw new TimeOutException("Error: Agent Timeout... ");
} catch (IOException e) {
throw new OperationFailed(e.getMessage(), e);
} finally {
if (snmp != null) {
try {
snmp.close();
} catch (IOException ex) {
_logger.error(ex.getMessage(), ex);
}
}
}
}

Related

How to Keep Alive SNMP agent

I succcesfully created SNMP agent using snmp4j libraray
Here is the refrence code.
My query is how can i make this agent to run always to listen all incoming OIDs from manager.??
public synchronized void listen() throws IOException
{
TransportIpAddress address2= new UdpAddress(2069);
AbstractTransportMapping transport;
if (address2 instanceof TcpAddress)
{
transport = new DefaultTcpTransportMapping((TcpAddress) address2);
}
else
{
// transport = new DefaultUdpTransportMapping( (UdpAddress) address2);
transport = new DefaultUdpTransportMapping();
}
ThreadPool threadPool = ThreadPool.create("DispatcherPool", 10);
MessageDispatcher mtDispatcher = new MultiThreadedMessageDispatcher(threadPool, new MessageDispatcherImpl());
// add message processing models
mtDispatcher.addMessageProcessingModel(new MPv1());
mtDispatcher.addMessageProcessingModel(new MPv2c());
// add all security protocols
SecurityProtocols.getInstance().addDefaultProtocols();
SecurityProtocols.getInstance().addPrivacyProtocol(new Priv3DES());
//Create Target
CommunityTarget target = new CommunityTarget();
target.setCommunity( new OctetString("password"));
Snmp snmp = new Snmp(mtDispatcher, transport);
snmp.addCommandResponder(this);
transport.listen();
System.out.println("Listening on " + address);
try
{
this.wait();
}
catch (InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}

Android Asynctask return problems

I am facing a problem in value 'return' in Asynctask class in doInBackground method. I am getting an error, about 'missing return statement in below code.
`public class ForecastNetwork extends AsyncTask {
public final String TAG = ForecastNetwork.class.getSimpleName();
#Override
protected Void doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(TAG, "Error closing stream", e);
}
}
}
}`
What Should I return at the end?
I assume that you forgot to return the processing result
forecastJsonStr = buffer.toString();
return forecastJsonStr;

Google GeoLocation API returns different results for the same wifi access point

We are using Google's geolocation API to get the latlong for the wifi access points. We are seeing inconsistent results. Google's API returns different latlong on different boxes. When I test on my development box, I get the latlong which points to a location in US. When I test the same on the amazon ec2 box, I get the latlong which points to a location in Japan. Has anybody else experienced the same with Google's GeoLocation API?
Below is the code and the response strings from both hosts. JDK and JSON jar version is same on both the hosts.
public void testWifiIdMappingApi() {
String apiUrl = "https://www.googleapis.com/geolocation/v1/geolocate?key=xxxxxxxxxxxxxxxxxxxxxxxx";
InputStream inputStream = null;
HttpsURLConnection con = null;
DataOutputStream wr = null;
try {
URL url = new URL(apiUrl);
con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
JSONObject obj = new JSONObject();
JSONArray wifiAry = new JSONArray();
JSONObject wifiObj = new JSONObject();
wifiObj.put("macAddress", "6c:f3:7f:4b:37:74");
wifiObj.put("signalStrength", 60);
wifiAry.add(wifiObj);
wifiObj = new JSONObject();
wifiObj.put("macAddress", "6c:f3:7f:4b:37:75");
wifiObj.put("signalStrength", 60);
wifiAry.add(wifiObj);
obj.put("wifiAccessPoints", wifiAry);
System.out.println(obj.toString());
wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(obj.toString());
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
inputStream = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
inputStream = con.getInputStream();
} else {
inputStream = con.getErrorStream();
}
final char[] buffer = new char[4096];
StringBuilder response = new StringBuilder();
Reader r = new InputStreamReader(inputStream, "UTF-8");
int read;
do {
read = r.read(buffer, 0, buffer.length);
if (read > 0) {
response.append(buffer, 0, read);
}
} while (read >= 0);
System.out.println(new java.util.Date() + " - "
+ response.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null)
inputStream.close();
if (wr != null)
wr.close();
if (con != null)
con.disconnect();
} catch (Exception e) {
}
}
}
Input JSON String
{"wifiAccessPoints":[{"signalStrength":60,"macAddress":"6c:f3:7f:4b:37:74"},
{"signalStrength":60,"macAddress":"6c:f3:7f:4b:37:75"}]}
Response on the amazon ec2 host
{
"location": {
"lat": 40.603124,
"lng": 140.463922
},
"accuracy": 122000.0
}
Response on my development box (windows 7)
{
"location": {
"lat": 37.593392,
"lng": -122.04383
},
"accuracy": 22000.0
}
You might want to pass the considerIp field as False in your POST body. This would be what Google determines to be your location when the wifi routers aren't doing their job.

BlackBerry - Downloaded images are corrupted on wifi with HttpConnection

In my app I need to download several images from a server. I use this code to get a byte array :
HttpConnection connection = null;
InputStream inputStream = null;
byte[] data = null;
try
{
//connection = (HttpConnection)Connector.open(url);
connection = (HttpConnection)Connector.open(url, Connector.READ_WRITE, true);
int responseCode = connection.getResponseCode();
if(responseCode == HttpConnection.HTTP_OK)
{
inputStream = connection.openInputStream();
data = IOUtilities.streamToBytes(inputStream);
inputStream.close();
}
connection.close();
return data;
}
catch(IOException e)
{
return null;
}
The url are formed with the suffix ";deviceSide=false;ConnectionType=MDS - public" (without spaces) and it is working perfectly well.
The problem is that with phones that do not have a sim card, we can't connect to the internet via the MDS server. So we changed to use the connection factory and let BB choose whatever he wants :
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(url);
if (connDesc != null)
{
final HttpConnection httpConn;
httpConn = (HttpConnection)connDesc.getConnection();
try
{
httpConn.setRequestMethod(HttpConnection.GET);
final int iResponseCode = httpConn.getResponseCode();
if(iResponseCode == HttpConnection.HTTP_OK)
{
InputStream inputStream = null;
try{
inputStream = httpConn.openInputStream();
byte[] data = IOUtilities.streamToBytes(inputStream);
return data;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
finally{
try
{
inputStream.close();
} catch (IOException e)
{
e.printStackTrace();
return null;
}
}
}
}
catch (IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
}
return null;
The connection works because it select the good prefix (interface=wifi in our case), but this create another problem.
Some images are not well downloaded, some of them (not the sames at each try) are corrupted, but only when the phone use a wifi connection to get these images.
How can I avoid this problem ? What method to get a connection do I have to use ? Is it possible to check if the user have a sim card in orderto use MDS - public ?
Here is an example of a corrupted image :
error image http://nsa30.casimages.com/img/2012/06/28/120628033716123822.png
try this:
public static String buildURL(String url) {
String connParams = "";
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
connParams = ";interface=wifi"; //Connected to a WiFi access point.
} else {
int coverageStatus = CoverageInfo.getCoverageStatus();
//
if ((coverageStatus & CoverageInfo.COVERAGE_BIS_B) == CoverageInfo.COVERAGE_BIS_B) {
connParams = ";deviceside=false;ConnectionType=mds-public";
} else if ((coverageStatus & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
// Have network coverage and a WAP 2.0 service book record
ServiceRecord record = getWAP2ServiceRecord();
//
if (record != null) {
connParams = ";deviceside=true;ConnectionUID=" + record.getUid();
} else {
connParams = ";deviceside=true";
}
} else if ((coverageStatus & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
// Have an MDS service book and network coverage
connParams = ";deviceside=false";
}
}
Log.d("connection param"+url+connParams);
//
return url+connParams;
}
private static ServiceRecord getWAP2ServiceRecord() {
String cid;
String uid;
ServiceBook sb = ServiceBook.getSB();
ServiceRecord[] records = sb.getRecords();
//
for (int i = records.length -1; i >= 0; i--) {
cid = records[i].getCid().toLowerCase();
uid = records[i].getUid().toLowerCase();
//
if (cid.indexOf("wptcp") != -1
&& records[i].getUid().toLowerCase().indexOf("wap2") !=-1
&& uid.indexOf("wifi") == -1
&& uid.indexOf("mms") == -1) {
return records[i];
}
}
//
return null;
}
What happens when you append interface=wifi? Can you run the network diagnostic tool attached to below kb article and run all tests with SIM removed
http://supportforums.blackberry.com/t5/Java-Development/What-Is-Network-API-alternative-for-legacy-OS/ta-p/614822
Please also note that when download large files over BES/MDS there are limits imposed by MDS. Please ensure you review the below kb article
http://supportforums.blackberry.com/t5/Java-Development/Download-large-files-using-the-BlackBerry-Mobile-Data-System/ta-p/44585
You can check to see if coverage is sufficient for BIS_B (MDS public) but that won't help you if you are trying to support SIM-less users. I wonder if the problem is in an incomparability between the connection on Wi-Fi and IOUtilities.streamToBytes(). Try coding as recommended in the API documents.

Any hints for https form get and post parse html project android?

I'm creating an Android app that should do the following;
Use a form on a https (SSL!) page to login and receive a cookie
Issue httpGET actions to get html
parse that html and show it in a view, list or something.
I've been fooling around with Jsoup, httpUnit and HTMLUnit for quite some time now, but I'm running in to several problems;
A. Login is fine, works.. (I get the website's welcome page) but then, when I issue a GET statement (and include the cookie), I am redirected to the login form. So the response html is not what I expected. (might have something to do with a keepalivestrategy?)
B. InputBuffers are too small to receive entire HTML pages and set them up for parsing.
NB : I do not have control over the webserver
I'm totally new at this, so a tutorial or code snippets would be helpful.
For instance, this is what I use to login to the website :
public int checkLogin() throws Exception {
ArrayList<NameValuePair> data = new ArrayList<NameValuePair>();
data.add(new BasicNameValuePair("userid", getUsername()));
data.add(new BasicNameValuePair("password", getPassword()));
data.add(new BasicNameValuePair("submit_login", "Logmein"));
Log.d(TAG, "Cookie name : " + getCookieName());
Log.d(TAG, "Cookie cont : " + getCookie());
HttpPost request = new HttpPost(BASE_URL);
request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
request.getParams().setParameter("http.protocol.handle-redirects",false);
request.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));
HttpResponse response;
httpsclient.getCookieStore().clear();
List<Cookie> cookies = httpsclient.getCookieStore().getCookies();
Log.d(TAG, "Number of Cookies pre-login : " + cookies.size());
response = httpsclient.execute(request);
cookies = httpsclient.getCookieStore().getCookies();
Log.d(TAG, "Number of Cookies post-login : " + cookies.size());
String html = "";
// Problem : buffer is too small!
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line);
}
in.close();
html = str.toString();
Document doc = Jsoup.parse(html);
Log.v(TAG, "Ik heb nu dit : " + doc.toString());
if (cookies.size() > 0){
storeCookie(cookies.get(0).getName(), cookies.get(0).getValue());
return MensaMobileActivity.REQUEST_SUCCESS;
} else {
return MensaMobileActivity.REQUEST_ERROR;
}
}
You don't handle the SSL certificate at all, that's at least a part of the problem. I struggled starting to learn this recently as well. This block of code will grab the SSL cert from the webpage you're accessing.
try {
URL url = new URL(YOUR_WEBPAGE_HERE);
HttpsURLConnection connect = (HttpsURLConnection)url.openConnection();
connect.connect();
Certificate[] certs = connect.getServerCertificates();
if (certs.length > 0) {
cert = new File("YOUR_PATH_TO_THE_FILE");
//write the certificate obtained to the cert file.
OutputStream os = new FileOutputStream(cert);
os.write(certs[0].getEncoded());
return true;
}
}
catch (SSLPeerUnverifiedException e) {
e.printStackTrace();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (CertificateEncodingException e) {
e.printStackTrace();
}

Resources