Get IP and execute on IF statement - java

I can't process with my code.
I want to start my application if local Internet Protocol is equal to "XXX"
What i have wrote already wrote
Code:
InetAddress IP=InetAddress.getLocalHost();
System.out.println("SYSTEM IP = "+IP.getHostAddress());
Console :
SYSTEM IP= 192.168.0.69
How can i check: if my Internet Protocol is equal to 192.168.0.69 (or any i will get on other PC)
code executes;
else:
stops?
Thanks for advice if any!

getHostAddress returns a String:
public String getHostAddress()
↑
So simply do:
if("192.168.0.69".equals(IP.getHostAddress())) {
//...
}
It's preferable not to use magic strings, so make it static final String..

if(IP.getHostAddress().equals("192.168.0.69")){
//code executes
}else{
// stops
}

if(IP != null && IP.getHostAddress().equals("192.168.0.69"))
{
System.out.println("The address is matched");
}
IP.getHostAddress() method return the value in `String` so you can check the IP address using `equals` method.

Related

Java exception, RegEx

i'm new to java programming and i'm trying to validate an email value using RegEx, the program should throw an exception when the user provides a wrong value, i managed to do this with an if-else. However, when i try to handle the error using a try-catch block the RegEx does not work anymore and the wrong value gets displayed anyways. How can i solve this?
here's the code
try {
String emailRegex = "^(.+)#(.+).(.+)$";
if(email.matches(emailRegex)) {
Pattern pattern = Pattern.compile(emailRegex);
System.out.println(pattern.matcher(email).matches());
} else {
throw new IllegalArgumentException();
}
} catch (IllegalArgumentException ex) {
System.out.println(ex.getLocalizedMessage());
}
This regular expression rejects valid email addresses. Even if you did fix it. For example, foo#bar is actually valid (top-level domains can contain MX records. A few do!). This is the general formula for 'is it valid email':
Does it contain spaces? If yes, reject.
Does it contain at least 1 #? If no, reject.
Is the last # at position 0 (i.e. at the start), or at the end? Reject.
Otherwise, pass. There are a few invalid emails that would nevertheless pass, but this is by and large no problem: foo#bar is not really legal, but the only real way to know that, is to send an email to it and request the user click a link inside it before they can continue. No regexp is ever going to figure out if the email address entered by a user is in fact a valid email address, let alone an email address that belongs to that user, hence, there is no real point in trying to go any further than that. You're attempting to catch honest typoes, not actually validate anything, because that is impossible. Note that it can easily become legal tomorrow - someone just needs to set up the bar top level domain and make sure there's an MX record for it in its DNS registration and voila. foo#bar is now legal.
Your regex is close to this ideal; you just want ^.+#.+$
NB: If you want to break spec and reject any email addresses to top-level domains, your regex is broken. Your intent is clearly to want foo#a.b, but you don't do that - that middle ., nestled between (.+), is still a regex dot operator, meaning: "any character". You'd want \\. for that instead. But, don't - as I said, TLDs are themselves rare as mail servers, but valid according to spec!
Fix this and your code 'works', but note that your code can go only one of two ways:
The regexp matches, in which case you again run the string through the regexp (seems rather pointless to do it twice!), and then trivially prints 'true'. The entire Pattern pattern = ...; System.out.println(...) might as well be System.out.println("true"); - that's what it will always do - yes, the regexp that just matched, is still going to match, of course.
The regexp does not match, in which case we get to the else block, which throws an exception. This then goes to the catch block which can only catch this (as nothing else throws IllegalArgumentEx here), and prints the 'localized message', which is null here.
So, this code prints true if it matches, and null if it does not. That seems.. weird. And is needlessly complicated if that's what you wanted.
Better:
class Test {
private static final Pattern EMAIL_PATTERN = Pattern.compile("^.+#.+$");
public static boolean isValidEmail(String email) {
return EMAIL_PATTERN.matcher(email).matches();
}
public static void main(String[] args) {
var keyboard = new Scanner(System.in);
while (true) {
System.out.print("Enter an email address: ");
String line = keyboard.nextLine().trim();
if (line.isEmpty()) System.exit(0);
if (isValidEmail(line)) {
System.out.println("Valid");
} else {
System.out.println("Not valid");
}
}
}
}
The try/catch block do not add anything useful here. You use try/catch when you want to transfer an error condition across method calls, not within the same method call, and not when the only meaningful data you can convey is a boolean flag. If that's all you have ('valid' or 'not valid'), almost always you just want a boolean.
If you really want the exception instead:
class Test {
private static final Pattern EMAIL_PATTERN = Pattern.compile("^.+#.+$");
public static void validateEmail(String email) throws IllegalArgumentException {
if (!EMAIL_PATTERN.matcher(email).matches()) {
throw new IllegalArgumentException("Email '" + email + "' is not valid");
}
}
public static void main(String[] args) {
var keyboard = new Scanner(System.in);
while (true) {
System.out.print("Enter an email address: ");
String line = keyboard.nextLine().trim();
if (line.isEmpty()) System.exit(0);
try {
validateEmail(line);
System.out.println("Valid");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
}

JAVA in android studio The value true assigned is never used

I wrote A method to check that the password A user enters when registering to the app is valid.
A valid password will be with length of 8-16 charachters and contains only numbers,uppercase and lowercase letters.
according to android studio in the For loop when the value is OK it will never assign the value true to the variables and I can't understand why.
Is it becuase I am trying to work directly with EditText or am I just doing it wrong?
This is the method:
boolean PasswordTest(EditText password){//function to check that the password is OK
boolean upLetter=false,lowLetter=false,digit=false;
int i;
if(password.length()<8||password.length()>16){
Toast.makeText(getApplicationContext(),"Password must be between 8-16 characters",Toast.LENGTH_LONG).show();
return false;
}
for(i=0;i<password.getText().length();i++) {
if (Character.isDigit(password.getText().charAt(i))) {
digit = true; //The value true assigned to digit is never used
} else if (Character.isUpperCase(password.getText().charAt(i))) {
upLetter = true; //The value true assigned to upLetter is never used
} else if (Character.isLowerCase(password.getText().charAt(i))) {
lowLetter = true; //The value true assigned to lowLetter is never used
} else {
Toast.makeText(getApplicationContext(),"Password must contain uppercase,lowercase and numbers",Toast.LENGTH_LONG).show();
return false;
}
}
Toast.makeText(getApplicationContext(),"all data is correct",Toast.LENGTH_LONG).show();
return true;
}
thanks for the help
according to android studio in the For loop when the value is OK it will never assign the value true to the variables and I can't understand why.
You misread the warning.
Your code is assigning values to these 3 local variables (or well, it should do that, depending on the input data).
But then the method ends, and these 3 local variables cease to exist.
The warning tells you that these assignments are meaningless because there is no other code following that uses the 3 local variables for anything.
In other words: you have to step back and ask yourself: "okay, now that the loop is over, how should I use these 3 local variables to do something else".
So: this has nothing to do with the editor you are using. The tool tells you that the code you have written "makes no sense". When you do not use the result of an operation, then why compute it?!
You could switch this over to regex and make it simple.
Pattern pattern;
Matcher matcher;
final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=])(?=\\S+$).{4,}$";
boolean PasswordTest(EditText password){//function to check that the password is OK
pattern = Pattern.compile(PASSWORD_PATTERN);
matcher = pattern.matcher(password);
return matcher.matches();
}
And then on the method calling the PasswordTest check and then show a Toast message.

how to pass a variable through sendKeys in selenium webdriver?

I want to pass the float variable 'f' through sendKeys in the below program.Can someone please let me know the same? As of now, it is throwing
"The method sendKeys(CharSequence...) in the type WebElement is not applicable for the arguments ".
Code:
public static String isEditable(String s1) {
f=Float.parseFloat(s1);
System.out.println(f);
boolean bool=webDriver.findElement(By.xpath("expression")).isEnabled();
if(bool) {
if((f<0) || (f>6)) {
error="Value must be between 0.00% and 6.00%";
System.out.println(error);
} else {
webDriver.findElement(By.xpath(""expression")).sendKeys(f);
}
} else {
error="Please enter a valid Number";
}
return error;
}
Convert the float to a string:
webDriver.findElement(By.xpath("...")).sendKeys(Float.toString(f));
I know you already accepted an answer but I wanted to clean up your code a little and give you some feedback.
I changed the name of the function because a function named isEditable() should return a boolean indicating whether some field is editable. That's not what your function is doing so it should be given a more appropriate name. I made a guess at what the actual name should be... I could be way off but you should name it something more along the lines of what it's actually doing... putting text in a field.
I removed the isEnabled() check because that should be done in the function that sets the fund number. Each function should do one thing and only one thing. This function validates that the rate passed is in a valid range and then puts it in the field.
I removed the duplicate code that was scraping the INPUT twice. Just do it once, save it in a variable, and reuse that variable. In this case, there's no need to scrape it twice.
and as d0x said, you shouldn't convert the s1 string to a float and then back to string when you sendKeys() ... just send the s1 string. Translating it back doesn't help readability, it just means you wrote more code that someone after you will need to understand. Favor clean code... it's always more readable.
public static String enterRate(String s1)
{
f = Float.parseFloat(s1);
WebElement input = webDriver.findElement(By.xpath(".//*[#id='p_InvestmentSelection_4113']/div/div/div[5]/div/ul/li/div[3]/div[2]/label/div[1]/input"));
if ((f < 0) || (f > 6))
{
error = "Value must be between 0.00% and 6.00%";
}
else
{
input.sendKeys(s1);
}
return error;
}
Can you try passing s1 instead of f. Because the method takes a string, not a float.
Your method should look like this:
String selector = "expression";
webDriver.findElement(By.xpath(selector)).sendKeys(f);
And please use better variable names like userInput instead of s1 or userInputAsFloat instead of f or investmentInputVisible instead of bool etc.

Handle one or multiple words in Java Socket .readLine()

I am building an application where I have a server and a client that talk to each other -over telnet. (via socket). The server program is monitoring a tank of some gass, and sends temperature level and preassure level via socket to the accepted clients.
I have managed to get the client and server to talk to each other when I write stuff --in telnet--, but...
I need some help to handle the data that I send.
I have made a loginscript to determine if the user is a valid user or not.
So I can write two words like "myname" "space" "mypassword" and I get a green light and returns a valid user.
But when I only write one word, and hit enter, it gives me:
Exeption in thread... java.lang.Array.IndexOutOfBoundsExeption EXEPT for when I write exit or logout!
(All users are hardcoded in the script for ease of use for testing. (The login script works fine by it self, and returns valid user = false when I write something wrong.)
Here is my code. Some pseudo code is added since I am not 100% sure of what to do...;)
String telNetCommand = dataIn.readLine();
System.out.println(telNetCommand);
String dataInArray[] = telNetCommand.split(" ");
user.isValid(dataInArray[0], dataInArray[1]);
if (dataInArray[1] == "\n") {
//Ignore login request and continue telnet-logging?
}
The client application has a button for each command, like:
"Send me every n'th data", or "Send me a batch of data every n'th second. If command equals exit, or logout - > break operation....
// --------------// USER INPUT FROM CLIENT APP //--------------------------//
// --------------// CONTINUE ? //----------------------------//
if (command.equals("CONTINUE")) {
continueSession();
else { //..Kill session
}
}
// --------------// SKIP <N> //----------------------------//
if (command.equals("SKIP_N")) {
skipEveryNthData();
}
// --------------// BATCH <N> //---------------------------//
if (command.equals("BATCH_N")) {
batchEveryNthData();
}
// --------------// LOGG OUT #1 //-------------------------//
if (command.equals("logout") || command.equals("exit")) {
break;
}
Maybe I am getting a bit confused now, but I think that I need to put all data into an array, and check
if
dataInArray[0] == "CONTINUE"
dataInArray[0] == "SKIP_N", or
dataInArray[0] == "BATCH_N"
(then send some data back)...
and...
if dataInArray[1] == "enter" ("\n") execute the single word commands ...??
if dataInArray[0] == "LOG_IN" or "PASSWORD" check if valid user is true..
Thanks for any help, and/or tips! :)
In this part of your code:
String dataInArray[] = telNetCommand.split(" ");
user.isValid(dataInArray[0], dataInArray[1]);
You assume that the telNetCommand string contains a space. If it does not, dataInArray will only contain one element and dataInArray[1] will throw an IndexOutOfBoundsExeption.
You should check the size of the array:
if (dataInArray.length < 2) {
//no space in the command - do what you need to do
//for example an error message
}
The IndexOutOfBoundsExeption more than likely being caused by:
user.isValid(dataInArray[0], dataInArray[1]);
Make sure that the incoming String telNetCommand contains at least one space so that you have at 2 Strings in the array. You could do this checking the size of the array:
if (dataInArray.length < 2) {
throw new IllegalArgumentException(telNetCommand + " only contains " + dataInArray.length + " elements");
}
Also, on a different note, make sure to use String.equals when checking String content:
if ("\n".equals(dataInArray[1])) {
Thanks guys. I don't get any errors now... And here is what I ended up doing.
I had to set it == 2 in order not to get any errors.
while (true) {
String telnetCommand = dataIn.readLine();
System.out.println(telnetCommand);
String dataInArray[] = telnetCommand.split(" ");
if (dataInArray.length == 2) {
user.isValid(dataInArray[0], dataInArray[1]);
}
if (dataInArray.length < 2) {
if (telnetCommand.equals("CONTINUE")) {
continueThisSession();
System.out.println("Running method continueThisSession");
}
if (telnetCommand.equals("SKIP_N")) {
skipEveryNthData();
System.out.println("Running method skipEveryNthData");
}
if (telnetCommand.equals("BATCH_N")) {
batchEveryNthData();
System.out.println("Running method batchEveryNthData");
}
if (telnetCommand.equals("logout") || telnetCommand.equals("exit")) {
break;
}
}
}
Peace :)

Check valid IPv4 Address in Java

I am using the sun.net.util.IPAddressUtil package to check whether the string contains a valid IPv4 and IPv6 address or not.
Code Snippet is:-
String ipv4addr="200";
if(IPAddressUtil.isIPv4LiteralAddress(ipv4addr))
{
System.out.println("valid ipv4 address");
}
else
{
System.out.println("not valid");
}
But for addresses such as 200 and 300 it is still saying it is a valid IPv4 address, which it isn't.
When I used the same package and checked for IPV6 address using :-
String ipv6addr="200";
if(IPAddressUtil.isIPv6LiteralAddress(ipv6addr))
{
System.out.println("valid ipv6 address");
}
else
{
System.out.println("not valid");
}
I get the correct result. However, IPv4 does not seem to be working or may be I am using it incorrectly. Please guide me. I don't want to use regex for IPv4 validation...
There's a reason you're getting a "valid" result: 200 is a valid IPv4 address.
See, to the computer, an IPv4 address is just a 32-bit number. The dots are entirely for our convenience, because we humans suck at memorizing big precise numbers. But they don't have to be there; there are rules about how an address gets parsed depending on how many parts it has.
When an address consists of one number, it's considered a 32-bit number, and each byte is 8 bits of that number. If you were to parse "200" as an IP address, it would be equivalent to 0.0.0.200. Likewise, "2130706433" would be equivalent to 127.0.0.1.
There are also standards for when an address has two parts like 0.200 (first part is the first byte, and the second part is a 24-bit number representing the other 3 bytes), and even 0.0.200 (first two numbers are bytes, the last part is 16 bits and takes up the other 2 bytes). The "unusual" formats are leftovers from the days of IP address classes, but almost all software that has to parse addresses will understand them. (If you pop open your browser and go to http://1249739112* or even http://74.125.33128*, for example, Google's home page will come up.)
* See the comments for clickable links. Thanks, "link validator". :P
See http://download.oracle.com/javase/6/docs/api/java/net/Inet4Address.html or http://www.perlmonks.org/?node_id=221512, or http://en.wikipedia.org/wiki/IPv4#Address_representations, for some more details.
Java understands these formats as well (as does .net, as well as any decent OS), and parses the address correctly whether it contains 1, 2, 3, or 4 parts.
If you want to check that a would-be address actually looks like "xxx.xxx.xxx.xxx", then you'll probably want to explicitly check that using a pattern, or using a validation library that considers 32-bit numbers as invalid addresses (even though they are valid). I wouldn't bother, though -- if you use the lookup functions provided, you can accept an address in any standard format and it will work.
(All this mess changes with IPv6; there's a much stricter format, and you can't just type in some 36-digit number and expect it to work. But the platform still knows how to parse an address, and you should trust it to do so.)
Check out Guava's InetAddresses class which contains static utility methods for working with IP addresses. (As I understand it uses the sun.net.util.IPAddressUtil class behind the scenes.)
System.out.println(InetAddresses.isInetAddress("400")); // false
It's not a good idea to use internal "sun" packaged classes, I'd try using Apache's Validator
http://commons.apache.org/validator/
which has IP Address validation.
If you want to validate if a string is valid IP address representation, the source code of org.apache.http.conn.util.InetAddressUtils uses these regular expressions:
IPV4_PATTERN = Pattern.compile(
"^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");
IPV6_STD_PATTERN = Pattern.compile(
"^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$");
IPV6_HEX_COMPRESSED_PATTERN = Pattern.compile(
"^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$");
That string is an IPv4 string format that was originally introduced by the aton_inet utility in BSD Unix and has persisted until this day in the various Unix and Linux flavours and elsewhere.
https://linux.die.net/man/3/inet_aton
The IPAddress Java library will do validation that can be configured to support aton_inet formats or not. The javadoc is available at the link. Disclaimer: I am the project manager.
Verify if an address is valid, allow inet_aton style:
String str = "200";
IPAddressString addrString = new IPAddressString(str);
try {
IPAddress addr = addrString.toAddress();
System.out.println("valid address: " + addr.toCanonicalString());
} catch(IPAddressStringException e) {
System.out.println(e.getMessage());
}
Output:
valid address: 0.0.0.200
Verify if an address is valid, do not allow inet_aton style:
IPAddressStringParameters parameters = new
IPAddressStringParameters.Builder().allow_inet_aton(false).toParams();
addrString = new IPAddressString(str, parameters);
try {
IPAddress addr = addrString.toAddress();
System.out.println("valid address: " + addr.toCanonicalString());
} catch(IPAddressStringException e) {
System.out.println(e.getMessage());
}
Output:
200 IP Address error: options do not allow IPv4 address with less than four segments
After a small research I ended up with something like this
public static boolean isValidIP4Address(String ipAddress) {
if (ipAddress.matches("^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$")) {
String[] groups = ipAddress.split("\\.");
for (int i = 0; i <= 3; i++) {
String segment = groups[i];
if (segment == null || segment.length() <= 0) {
return false;
}
int value = 0;
try {
value = Integer.parseInt(segment);
} catch (NumberFormatException e) {
return false;
}
if (value > 255) {
return false;
}
}
return true;
}
return false;
}
which was fine for simple checks.

Categories

Resources