I am converting a nodejs code into Java8.
In node there are code as shown below
var ipToEndAt = ippp.prev("192.168.1.225");
result of ipToEndAt is "192.168.1.224"
I need to convert this line into a java code. I searched for SubnetUtils library, but couldn't find anything appropriate.
similar i also need to increment ip address by 1
can anyone suggest a library or a code snippet ? which ever would be best
Although it's not overly hard to do it yourself, there's an InetAddresses class in Guava that allows this kind of operations. And Guava is a very useful addition to your toolchest anyways.
InetAddress address = InetAddress.getByName("192.168.1.225");
address = InetAddresses.decrement(address);
See, that looks almost identical to the JS code.
In your comment you state that you are unable to use the decrement method, which indicates that you have a really old version of Guava.
https://github.com/google/guava/commit/d39130651d8a90f5ebe066de7f0b2311806e5152#diff-1207ec0a4b5d3f5e5c2236b7373eefc9
The project home page contains instructions on how to add the current version (25.1) to your project's dependencies.
This can be done with the IPAddress Java library, in a manner that is polymorphic between IPv4 and IPv6. Also, it is not limited to incrementing or decrementing by 1 as with Guava, you can use any long value and catch AddressValueException in the case of overflow. Disclaimer: I am the project manager of IPAddress.
Sample code:
IPAddress result = increment("192.168.1.225", -1);
System.out.println(result);
result = increment("::", 1);
System.out.println(result);
static IPAddress increment(String addrStr, long inc) throws AddressValueException {
return new IPAddressString(addrStr).getAddress().increment(inc);
}
Output:
192.168.1.224
::1
More elaborate sample code at the IPAddress wiki
Related
How can I call a windows UWP API from the JVM?
For example the Windows.Security.Credentials API.
When attempting to use JNA none of the native library names I have tried will link, and I can't actually find a DLL that matches the name Windows.Security.Credentials.dll as described in the documentation.
Is what I want to do even possible, how can I link to and call UWP API's?
Update: I completely missed the mark on my first answer, was thinking JNI, not JNA, which looks a bit more like C# pInvoke. The code below is roughly what you'll need, but you'll need to reconstruct the v-tables for IInspectable and IPasswordVault. You can use the activation factory instead of activating the instance through RoActivateInstance, but then you'll need to reconstruct the interface for IActivationFactory as well. Otherwise the call suquence below is correct, if in the wrong language.
You can link and call against RoActivateInstance or RoGetActivationFactory and use the low-level COM-styl ABI interfaces defined the SDK in Windows.Security.Credentials.h. Same import lib as above.
eg:
IInspectable *pI {};
Windows::Security::Credentials::IPasswordVault pPV;
HRESULT hr = RoActivateInstance(L"Windows.Security.Credentials.PasswordVault", &pI);
if (SUCCEEDED(hr)) {
hr = pI->QueryInterface(__uuidof(Windows::Security::Credentials::IPasswordVault), (void**)&pPV);
}
if (SUCCEEDED(hr)) {
IVectorView<IPasswordCredential> *pPV{}; // namespaces omitted
hr = pPV->RetrieveAll(&pPV);
}
I'm trying to create an SNMP4j agent and am finding it difficult to understand the process correctly. I have successfully created an agent that can be queried from the command line using snmpwalk. What I am having difficulty with is understanding how I am meant to update the values stored in my implemented MIB.
The following shows the relevant code I use for creating the MIB (I implement Host-Resources-MIB)
agent = new Agent("0.0.0.0/" + port);
agent.start();
agent.unregisterManagedObject(agent.getSnmpv2MIB());
modules = new Modules(DefaultMOFactory.getInstance());
HrSWRunEntryRow thisRow = modules.getHostResourcesMib().getHrSWRunEntry()
.createRow(oidHrSWRunEntry);
final OID ashEnterpriseMIB = new OID(".1.3.6.1.4.1.49266.0");
thisRow.setHrSWRunIndex(new Integer32(1));
thisRow.setHrSWRunName(new OctetString("RunnableAgent"));
thisRow.setHrSWRunID(ashEnterpriseMIB);
thisRow.setHrSWRunPath(new OctetString("All is good in the world")); // Max 128 characters
thisRow.setHrSWRunParameters(new OctetString("Everything is working")); // Max 128 characters
thisRow.setHrSWRunType(new Integer32(HrSWRunTypeEnum.application));
thisRow.setHrSWRunStatus(new Integer32(HrSWRunStatusEnum.running));
modules.getHostResourcesMib().getHrSWRunEntry().addRow(thisRow);
agent.registerManagedObject(modules.getHostResourcesMib());
This appears to be sufficient to create a runnable agent. What I do not understand is how I am meant to change the values stored in the MIB (how do I, for example, change the value of HrSWRunStatus). There seem to be a few kludge ways but they don't seem to fit with the way the library is written.
I have come across numerous references to using/overriding the methods
prepare
commit
undo
cleanup
But cannot find any examples where this is done. Any help would be gratefully received.
In protected void registerManagedObjects(), you need to do something like new MOMutableColumn(columnId, SMIConstants.SYNTAX_INTEGER, MOAccessImpl.ACCESS_READ_WRITE, null); for your HrSWRunStatus. Take a look at the TestAgent.java example of SNMP4J-agent source.
I established connection to a SAP Server and I would like to print a list of BAPIs in my Java program. I am using sapjco3.jar.
Is there any way to do it?
You can also use the function module SWO_QUERY_API_METHODS. The following code snippet works with JCo 2:
IFunctionTemplate functionTemplate = Repository.getFunctionTemplate("SWO_QUERY_API_METHODS");
JCO.Function function = functionTemplate.getFunction();
mConnection.execute(function);
ParameterList exportParameter = function.getExportParameterList();
System.out.println("exportParameter: " + exportParameter);
ParameterList importParameter = function.getImportParameterList();
System.out.println("importParameter: " + importParameter);
ParameterList tableParameter = function.getTableParameterList();
System.out.println("tableParameter: " + tableParameter);
As far as I know, there is no "BAPI to get a list of BAPIs", so this would be a non-trivial task. You could try to use RFC_FUNCTION_SEARCH to search for function modules named BAPI*, but that's not guaranteed to give you a) only official BAPIs and b) all of the official BAPIs...
You can use the BAPI_MONITOR_GETLIST to get a list of all BAPIs in your system together with meta data.
You could make an ABAP function searching for all RFC functions in table TFDIR, with FMODE ='R' (remote). However, This will give you all remote-callable function, not only BAPIs.
I am using JSCH API to find length of RSA SSH keys .
I use the following code to do that:
KeyPairRSA KPR = (KeyPairRSA) KeyPairRSA.load(jsch, keypath);
System.out.println("size " +KPR.getKeySize());
This returns me always length 1024 .I think its bug with API itself.
Can anyone please tell me how to find length of RSA/DSA SSH keys?
Thanks a lot in advance.
I'm the author of JSch.
It is a bug or the incompleteness of KeyPair* classes.
They had been just introduced for the key-pair generation purposes.
But, in our internal development version, KeyPair* classes have been overhauled, and
that method has worked well.
# This is off-topic, but we have added the support for Putty's private key format, as a bonus! :-)
Anyway, the fix will be available in the next release, and if you can't wait for it,
replace KeyPairRSA#getKeySize() with the following,
public int getKeySize(){
return (new java.math.BigInteger(n_array)).bitLength();
}
Is there any way to verify in Java code that an e-mail address is valid. By valid, I don't just mean that it's in the correct format (someone#domain.subdomain), but that's it's a real active e-mail address.
I'm almost certain that there's no 100% reliable way to do this, because such a technique would be the stuff of spammer's dreams. But perhaps there's some technique that gives some useful indication about whether an address is 'real' or not.
Here is what I have around. To check that the address is a valid format, here is a regex that verifies that it's nearly rfc2822 (it doesn't catch some weird corner cases). I found it on the 'net last year.
private static final Pattern rfc2822 = Pattern.compile(
"^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$"
);
if (!rfc2822.matcher(email).matches()) {
throw new Exception("Invalid address");
}
That will take care of simple syntax (for the most part). The other check I know of will let you check if the domain has an MX record. It looks like this:
Hashtable<String, String> env = new Hashtable<String, String>();
env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
DirContext ictx = new InitialDirContext(env);
Attributes attrs = ictx.getAttributes(domainName, new String[] {"MX"});
Attribute attr = attrs.get("MX");
if (attr == null)
// No MX record
else
// If attr.size() > 0, there is an MX record
This, I also found on the 'net. It came from this link.
If these both pass, you have a good chance at having a valid address. As for if the address it's self (not just the domain), it's not full, etc... you really can't check that.
Note that the second check is time intensive. It can take anywhere from milliseconds to >30 seconds (if the DNS does not respond and times out). It's not something to try and run real-time for large numbers of people.
Hope this helps.
EDIT
I'd like to point out that, at least instead of the regex, there are better ways to check basic validity. Don and Michael point out that Apache Commons has something, and I recently found out you can use .validate() on InternetAddress to have Java check that the address is really RFC-8222, which is certainly more accurate than my regex.
You cannot really verify that an email exists, see my answer to a very similar question here: Email SMTP validator
Without sending an email, it could be hard to get 100%, but if you do a DNS lookup on the host that should at least tell you that it is a viable destination system.
Apache commons provides an email validator class too, which you can use. Simply pass your email address as an argument to isValid method.
Do a DNS lookup on the hostname to see if that exists. You could theoretically also initiate a connection to the mailserver and see if it tells you whether the recipient exists, but I think many servers pretend they know an address, then reject the email anyway.
The only way you can be certain is by actually sending a mail and have it read.
Let your registration process have a step that requires responding to information found only in the email. This is what others do.
I'm not 100% sure, but isn't it possible to send an RCPT SMTP command to a mail server to determine if the recipient is valid? It would be even more expensive than the suggestion above to check for a valid MX host, but it would also be the most accurate.
If you're using GWT, you can't use InternetAddress, and the pattern supplied by MBCook is pretty scary.
Here is a less scary regex (might not be as accurate):
public static boolean isValidEmail(String emailAddress) {
return emailAddress.contains(" ") == false && emailAddress.matches(".+#.+\\.[a-z]+");
}
public static boolean isValidEmail(String emailAddress) {
return emailAddress.contains(" ") == false && emailAddress.matches(".+#.+\\.[a-z]+");
}