String validation method java

Validate password in java

In this post, we will see how to validate a password in java.
Here are rules for password:

  1. Must have at least one numeric character
  2. Must have at least one lowercase character
  3. Must have at least one uppercase character
  4. Must have at least one special symbol among @#$%
  5. Password length should be between 8 and 20

Using regex

Here is standard regex for validating password.

Here is explanation for above regex

^ asserts position at start of a line
Group (?=.*\\d)
Assert that the Regex below matches
.* matches any character (except for line terminators)
\\ matches the character \ literally (case sensitive)
d matches the character d literally (case sensitive)
Group (?=.*[a-z])
Assert that the Regex below matches
.* matches any character (except for line terminators)
Match a single character present in the list below [a-z]
a-z a single character in the range between a (index 97) and z (index 122) (case sensitive)
Group (?=.*[A-Z])
Assert that the Regex below matches
.* matches any character (except for line terminators)
Match a single character present in the list below [A-Z]
A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive)
Group (?=.*[@#$%])
Assert that the Regex below matches
.* matches any character (except for line terminators)
Match a single character present in the list below [@#$%]
@#$% matches a single character in the list @#$% (case sensitive)
. matches any character (except for line terminators)
Quantifier — Matches between 8 and 20 times, as many times as possible, giving back as needed (greedy)
$ asserts position at the end of a line

Читайте также:  Least squares regression python

Here is java program to implement it.

Источник

Check Whether a String Is Valid JSON in Java

announcement - icon

Repeatedly, code that works in dev breaks down in production. Java performance issues are difficult to track down or predict.

Simply put, Digma provides immediate code feedback. As an IDE plugin, it identifies issues with your code as it is currently running in test and prod.

The feedback is available from the minute you are writing it.

Imagine being alerted to any regression or code smell as you’re running and debugging locally. Also, identifying weak spots that need attending to, based on integration testing results.

Of course, Digma is free for developers.

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

1. Overview

When working with raw JSON values in Java, sometimes there is a need to check whether it is valid or not. There are several libraries that can help us with this: Gson, JSON API, and Jackson. Each tool has its own advantages and limitations.

In this tutorial, we’ll implement JSON String validation using each of them and take a closer look at the main differences between the approaches with practical examples.

2. Validation with JSON API

The most lightweight and simple library is the JSON API.

The common approach for checking if a String is a valid JSON is exception handling. Consequently, we delegate JSON parsing and handle the specific type of error in case of incorrect value or assume that value is correct if no exception occurred.

2.1. Maven Dependency

First of all, we need to include the json dependency in our pom.xml:

2.2. Validating with JSONObject

Firstly, to check if the String is JSON, we will try to create a JSONObject. Further, in case of a non-valid value, we will get a JSONException:

public boolean isValid(String json) < try < new JSONObject(json); >catch (JSONException e) < return false; >return true; >

Let’s try it with a simple example:

String json = "[email protected]\", \"name\": \"John\">"; assertTrue(validator.isValid(json));
String json = "Invalid_Json"; assertFalse(validator.isValid(json));

However, the disadvantage of this approach is that the String can be only an object but not an array using JSONObject.

For instance, let’s see how it works with an array:

String json = "[[email protected]\", \"name\": \"John\">]"; assertFalse(validator.isValid(json));

2.3. Validating with JSONArray

In order to validate regardless of whether the String is an object or an array, we need to add an additional condition if the JSONObject creation fails. Similarly, the JSONArray will throw a JSONException if the String is not fit for the JSON array as well:

public boolean isValid(String json) < try < new JSONObject(json); >catch (JSONException e) < try < new JSONArray(json); >catch (JSONException ne) < return false; >> return true; >

As a result, we can validate any value:

String json = "[[email protected]\", \"name\": \"John\">]"; assertTrue(validator.isValid(json));

3. Validation with Jackson

Similarly, the Jackson library provides a way to validate JSON based on Exception handling. It is a more complex tool with many types of parsing strategies. However, it’s much easier to use.

3.1. Maven Dependency

 com.fasterxml.jackson.core jackson-databind 2.13.0 

3.2. Validating with ObjectMapper

We use the readTree() method to read the entire JSON and get a JacksonException if the syntax is incorrect.

In other words, we don’t need to provide additional checks. It works for both objects and arrays:

ObjectMapper mapper = new ObjectMapper() .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) .build() public boolean isValid(String json) < try < mapper.readTree(json); >catch (JacksonException e) < return false; >return true; >

Let’s see how we can use this with examples:

String json = "[email protected]\", \"name\": \"John\">"; assertTrue(validator.isValid(json)); String json = "[[email protected]\", \"name\": \"John\">]"; assertTrue(validator.isValid(json)); String json = "Invalid_Json"; assertFalse(validator.isValid(json));

Note that we’ve also enabled the FAIL_ON_TRAILING_TOKENS option, to ensure the validation will fail if there is any text after a valid JSON besides whitespace.

Without this option, a JSON of the form <“email”:”[email protected]”>text will still appear as valid, even though it’s not.

4. Validation with Gson

Gson is another common library that allows us to validate raw JSON values using the same approach. It’s a complex tool that’s used for Java object mapping with different types of JSON handling.

4.1. Maven Dependency

Let’s add the gson Maven dependency:

 com.google.code.gson gson 2.8.5 

4.2. Non-Strict Validation

Gson provides JsonParser to read specified JSON into a tree of JsonElements. Consequently, it guarantees that we get JsonSyntaxException if there’s an error while reading.

Therefore, we can use the parse() method to compute String and handle Exception in case of a malformed JSON value:

public boolean isValid(String json) < try < JsonParser.parseString(json); >catch (JsonSyntaxException e) < return false; >return true; >

Let’s write some tests to check the main cases:

String json = "[email protected]\", \"name\": \"John\">"; assertTrue(validator.isValid(json)); String json = "[[email protected]\", \"name\": \"John\">]"; assertTrue(validator.isValid(json));

The main difference of this approach is that the Gson default strategy considers separate string and numeric values to be valid as part of the JsonElement node. In other words, it considers a single string or number as valid as well.

For example, let’s see how it works with a single string:

String json = "Invalid_Json"; assertTrue(validator.isValid(json));

However, if we want to consider such values as malformed, we need to enforce a strict type policy on our JsonParser.

4.3. Strict Validation

To implement a strict type policy, we create a TypeAdapter and define the JsonElement class as a required type match. As a result, JsonParser will throw a JsonSyntaxException if a type is not a JSON object or array.

We can call the fromJson() method to read raw JSON using a specific TypeAdapter:

final TypeAdapter strictAdapter = new Gson().getAdapter(JsonElement.class); public boolean isValid(String json) < try < strictAdapter.fromJson(json); >catch (JsonSyntaxException | IOException e) < return false; >return true; >

Finally, we can check whether a JSON is valid:

String json = "Invalid_Json"; assertFalse(validator.isValid(json));

5. Conclusion

In this article, we’ve seen different ways to check whether a String is valid JSON.

Each approach has its advantages and limitations. While the JSON API can be used for simple object validation, the Gson can be more extensible for raw value validation as part of a JSON object. However, the Jackson is easier to use. Therefore, we should use the one that fits better.

Also, we should check if some library is already in use or applies for the rest of the goals as well.

As always, the source code for the examples is available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Оцените статью