GWT java URL Validator - java

Does someone knows a function that validate if a url is valid or not purely in GWT java without using any JSNI

I am using this one (making use of regular expressions):
private RegExp urlValidator;
private RegExp urlPlusTldValidator;
public boolean isValidUrl(String url, boolean topLevelDomainRequired) {
if (urlValidator == null || urlPlusTldValidator == null) {
urlValidator = RegExp.compile("^((ftp|http|https)://[\\w#.\\-\\_]+(:\\d{1,5})?(/[\\w#!:.?+=&%#!\\_\\-/]+)*){1}$");
urlPlusTldValidator = RegExp.compile("^((ftp|http|https)://[\\w#.\\-\\_]+\\.[a-zA-Z]{2,}(:\\d{1,5})?(/[\\w#!:.?+=&%#!\\_\\-/]+)*){1}$");
}
return (topLevelDomainRequired ? urlPlusTldValidator : urlValidator).exec(url) != null;
}

org.apache.commons.validator.UrlValidator and static method isValid(String url) might be of help here.

You should use regular expression in GWT. Here is similar topics Regex in GWT to match URLs and Regular Expressions and GWT

Related

Wrong values from string empty test (java x kotlin)

I'm having a super weird behavior from a code that I was testing. The test I wrote was to see the behavior of the class if the Android returned an empty package name. After some debugging, I found this (consider that packageName is empty):
val resultFromKotlin = packageName.isNullOrEmpty()
val resultFromJava = StringUtils.isEmpty(packageName)
Is this expected? Can someone tell what the deal with this?
ps1.: In the picture above, Android Studio was complaining of isNullOrEmpty saying that could be simplified since packageName can't be null at that point.
ps2.: For references:
The StringUtils class is written in Java as follow:
public static boolean isEmpty(String str) {
return str == null || TextUtils.isEmpty(str.trim());
}
TextUtils is also from Java, but it's part of Android library:
public static boolean isEmpty(#Nullable CharSequence str) {
return str == null || str.length() == 0;
}
This is how kotlin implements it's extension method:
public inline fun CharSequence?.isNullOrEmpty(): Boolean {
contract {
returns(false) implies (this#isNullOrEmpty != null)
}
return this == null || this.length == 0
}
EDIT 08/11/2018:
Just for clarification, my problem is the wrong value returned from Java, not searching for an equivalence in the test, also:
This seems to be a problem with TextUtils when running tests.
If you are running unit tests, Android frameworks methods are mocked, and this one in particular returns false. Use instrumentation tests to run against a full Android runtime.
Here is where the issue is discussed.
I have tested manually by recreating the function, and it is returning true.
I would suggest using Apache Commons StringUtils implementation: StringUtils

Unable to retrieve the value of a specific text in java

I have a long text like below:
name="sessionValidity" value="2018-09-13T16:28:28Z" type="hidden"
name="shipBeforeDate" value= "2018-09-17" name="merchantReturnData"
value= "",name="shopperLocale" value="en_GB" name="skinCode"
value="CeprdxkMuQ" name="merchantSig"
value="X70xAkOaaAeWGxNgWnTJolmy6/FFoFaBD47IzyBYWf4="
Now, I have to find all the data which are stored in the value string.
Please help.
Usually the worst thing you could do is parsing an HTML with regex. Detailed explonation here.
For the purpose of parsing the data and manipulate it the right way you should considering using an advanced markup parser like jaxb, jsoup, or any other.
Of course it is a case specific decision and in your case maybe this one could do the work...
private static List<String> extractValuesAsUselessList(String theString) {
List<String> attributes = new ArrayList<>();
if (theString != null && !theString.equals("")) {
Matcher matcher = Pattern.compile("\\s([\\w+|-|:]+)=\"(.*?)\"").matcher(theString);
while (matcher.find()) {
if ("value".equals(matcher.group(1))) {
attributes.add(matcher.group(2));
}
}
}
return attributes;
}

Java Method to Check if URL Fits Pattern

I have the need to do some primitive url matching in java. I need a method that will return true, saying
/users/5/roles
matches
/users/*/roles
Here is what I am looking for and what I tried.
public Boolean fitsTemplate(String path, String template) {
Boolean matches = false;
//My broken code, since it returns false and I need true
matches = path.matches(template);
return matches;
}
One option is to replace the * with some kind of regex equivalent such as [^/]+, but the kind of pattern being used here is actually called a "glob" pattern. Starting in Java 7, you can use FileSystem.getPathMatcher to match file paths against glob patterns. For a complete explanation of the glob syntax, see the documentation for getPathMatcher.
public boolean fitsTemplate(String path, String template) {
return FileSystems.getDefault()
.getPathMatcher("glob:" + template)
.matches(Paths.get(path));
}

Android check if an email address is valid or not?

I develop an android app that can send emails to users.
But it turned out that some email addresses are not valid.
How check if the email address entered by the user is valid or not?
if you want check validate of email you can use:
public static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
but there is no way to find out what email address is real
you can use following method for removing if/else.
public static boolean isValidEmail(CharSequence target) {
return target != null && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
This code works totally fine and it gives you a boolean value. So if its true it will give true and false it will give you false
android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
Probably the best way to check if the email is real, is to actually send an email to that address with a verification code/link that will activate that user on your site. Using regular expressions will only make sure the email is valid, but not necessarily real.
You can use a Regular expression to validate an email address, so:
public boolean isEmailValid(String email)
{
final String EMAIL_PATTERN =
"^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
final Pattern pattern = Pattern.compile(EMAIL_PATTERN);
final Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
Here is a link with more RegExes to choose from.
There is no way of checking email is real or not. But You can check only the validation that is it in correct format or not.
There is no way to know if an email exists or not. Specially if it is on a site like yopmail or similar, which I believe would accept any mail to any account on their domain.
However, you can check:
1. if the address has the correct syntax and is on a registered domain (regex for syntax and a dns check if there is a mailserver for the site behind the #)
2. send an e-mail and check the response, some providers might send you back an error if the mail is not registered on their site.
Use below code:
if(validateEmail(mEdtTxtEmail.getText().toString().trim())){
// your code
}
private boolean validateEmail(String data){
Pattern emailPattern = Pattern.compile(".+#.+\\.[a-z]+");
Matcher emailMatcher = emailPattern.matcher(data);
return emailMatcher.matches();
}
Use :
if (!Patterns.EMAIL_ADDRESS.matcher(your_edit_text.getText().toString()).matches()){
loginEmail.setError("Please enter a Valid E-Mail Address!");
}else {
//email is valid
}
Here is a Kotlin version using Kotlin Extensions (extending the String object, so you can call stringName.isValidEmail():
fun String.isValidEmail(): Boolean {
return android.util.Patterns.EMAIL_ADDRESS.matcher(this).matches()
}

Java inline predicates: cannot be resolved to a variable

Sorry for the simple question - I come from the .NET stack. All I want is an inline Predicate. Please tell me what I'm doing wrong:
toReturn = Iterables.find(articles, a -> a.toString().equals(input));
It tells me that 'a cannot be resolved to a variable'. I'm assuming that I just need an import or that I'm using an old version of Java? Thanks in advance!
What you're trying to do is not possible in Java 7 or earlier; it exists in Java 8 and later though. With Java 7 and prior you are able to use lambdaj to similar effect though. It would look something like this:
toReturn = Iterables.find(articles, new Predicate<Object>() {
public boolean apply(Object item) {
return item.toString().equals(input);
}
});
You can check out more details here.
Edit:
As pointed out in the comments, there are alternatives. As you're using Iterables I'm guessing you would want a com.google.common.base.Predicate which can be defined very similarly:
toReturn = Iterables.find(articles, new Predicate<Object>() {
public boolean apply(Object item) {
return item.toString().equals(input);
}
public boolean equals(Object obj) {
// check whether the other object is also a Predicate
}
});

Categories

Resources