Commit 343182e5 authored by Rainer Türner's avatar Rainer Türner
Browse files

Part of MVP v1 developments by Net Group

parent 34fa25df
Pipeline #3768 failed with stages
in 0 seconds
MIT License
Copyright (c) 2022 buerokratt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# byk-commons
# Java Commons
A library for common utility methods.
## Licence
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://koodivaramu.eesti.ee/buerokratt/plug-and-play/byk-commons.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://koodivaramu.eesti.ee/buerokratt/plug-and-play/byk-commons/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
See licence [here](LICENCE.md).
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ee.ria.java.commons</groupId>
<artifactId>commons</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.2.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.13.2</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-jre8</artifactId>
<version>2.33.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.13.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
<version>5.6.3</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>3.9.1.2184</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.8</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<useSystemClassLoader>false</useSystemClassLoader>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.3.0</version>
</plugin>
<plugin>
<groupId>org.owasp</groupId>
<artifactId>dependency-check-maven</artifactId>
<version>7.1.0</version>
</plugin>
</plugins>
</build>
</project>
package commons;
/**
* Helper functions to encode or decode an input value to or from base64
*/
public class Base64 {
private Base64() {
throw new IllegalStateException("Utility class");
}
/**
* @param base64EncodedString String that has been encoded to base64
* @return Input string decoded from base64 to a string
*/
public static String decodeBase64(String base64EncodedString) {
return new String(java.util.Base64.getDecoder().decode(base64EncodedString));
}
/**
* @param object Any object
* @return Input object as base64 encoded string
*/
public static String encodeBase64(Object object) {
return java.util.Base64.getEncoder().encodeToString(object.toString().getBytes());
}
}
package commons;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Helper functions to convert dates between formats
*/
public class DateFormat {
private DateFormat() {
throw new IllegalStateException("Utility class");
}
/**
* @param dateValue String of the date to be converted
* @param inputFormat String of the format of the input date
* @param outputFormat String of the format of the output date
* @param timeZone String of the timezone to convert the date to
* @return String of the formatted date
*/
public static String formatDate(String dateValue, String inputFormat, String outputFormat, String timeZone) {
if (dateValue.isEmpty() || outputFormat.isEmpty()) return dateValue;
Date date = parseDate(dateValue, inputFormat);
if ("UTC".equalsIgnoreCase(timeZone)) date = dateToUTC(date);
return new SimpleDateFormat(outputFormat).format(date);
}
private static Date parseDate(String dateValue, String inputFormat) {
try {
return new SimpleDateFormat(inputFormat).parse(dateValue);
} catch (ParseException e) {
Timestamp timestamp = new Timestamp(Long.parseLong(dateValue) * 1000);
return new Date(timestamp.getTime());
}
}
private static Date dateToUTC(Date date) {
return new Date(date.getTime() - Calendar.getInstance().getTimeZone().getOffset(date.getTime()));
}
}
package commons;
import java.time.Instant;
/**
* Helper functions to get time data
*/
public class DateUtils {
private DateUtils() {
throw new IllegalStateException("Utility class");
}
/**
* @return current system Instant
*/
public static Instant getInstant() {
return Instant.now();
}
}
package commons;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public class Encryption {
private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
private Encryption() {
throw new IllegalStateException("Utility class");
}
public static Boolean matches(String rawPassword, String encodedPassword) {
boolean matches = encoder.matches(rawPassword, encodedPassword);
if (!matches) throw new IllegalArgumentException();
else return matches;
}
public static String encodePassword(String password) {
return encoder.encode(password);
}
}
package commons;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
/**
* Helper function to convert a date into Unix epoch time in seconds
*/
public class EpochTime {
private EpochTime() {
throw new IllegalStateException("Utility class");
}
/**
* @param dateValue String of the date to be converted
* @param inputFormat Format of the input date
* @return Date in Unix epoch seconds or input if either parameter is empty
*/
public static String toEpochSeconds(String dateValue, String inputFormat) {
if (dateValue.isEmpty() || inputFormat.isEmpty()) return dateValue;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(inputFormat);
LocalDateTime dateTime = LocalDateTime.parse(dateValue, formatter);
ZoneId zoneId = ZoneId.systemDefault();
return String.valueOf(dateTime.atZone(zoneId).toEpochSecond());
}
}
package commons;
/**
* Helper function to remove HTML tags from a string
*/
public class EscapeHtml {
private EscapeHtml() {
throw new IllegalStateException("Utility class");
}
/**
* @param input String to remove HTML from
* @return Input string with anything between less than and greater than signs removed
*/
public static String escapeHtml(String input) {
if (input.isEmpty()) return "";
return input.replaceAll("<[^>]*+>", "");
}
}
package commons;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Queue;
/**
* Helper function to extract a JSON value by #. delimited JSON keys
*/
public class ExtractByKey {
private static final String SPLITTER_STRING = "#.";
private static final ObjectMapper MAPPER = new ObjectMapper();
private ExtractByKey() {
throw new IllegalStateException("Utility class");
}
/**
* @param inputKeys String of key or keys split by `#.`
* @param inputJson JSON to extract values from
* @return List of JsonNodes extracted from jsonNode by inputKeys
*/
public static List<JsonNode> extractByKey(String inputKeys, String inputJson) throws JsonProcessingException {
Queue<String> keys = new LinkedList<>(Arrays.asList(inputKeys.split(SPLITTER_STRING)));
return getMatchingNodes(keys, MAPPER.readTree(inputJson));
}
private static List<JsonNode> getMatchingNodes(Queue<String> keys, JsonNode body) {
String firstKey = keys.poll();
List<JsonNode> potentialNodes = getNodesMatchingSingleKey(body, firstKey);
return keys.isEmpty() ? potentialNodes : getNodesMatchingAllKeys(keys, potentialNodes);
}
private static List<JsonNode> getNodesMatchingSingleKey(JsonNode body, String firstKey) {
List<JsonNode> nodes = new ArrayList<>(body.findValues(firstKey));
for (int i = 0; i < nodes.size(); i++) {
nodes.addAll(nodes.get(i).findValues(firstKey));
}
return nodes;
}
private static List<JsonNode> getNodesMatchingAllKeys(Queue<String> extracts, List<JsonNode> nodes) {
String extract = extracts.poll();
List<JsonNode> matchingNodes = new ArrayList<>();
nodes.stream()
.map(node -> node.get(extract))
.filter(Objects::nonNull)
.forEach(matchingNodes::add);
return extracts.isEmpty() ? matchingNodes : getNodesMatchingAllKeys(extracts, matchingNodes);
}
}
package commons;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.format.ResolverStyle;
import java.util.Arrays;
import java.util.List;
/**
* Helper function to validate personal id code
*/
public class IdCodeValidation {
private static final List<Integer> MULTIPLIER_ONE = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 1);
private static final List<Integer> MULTIPLIER_TWO = Arrays.asList(3, 4, 5, 6, 7, 8, 9, 1, 2, 3);
private IdCodeValidation() { throw new IllegalStateException("Utility class"); }
/**
* @param idCode String to validate
* @return correct idCode
*/
public static String validateIdCode(String idCode) {
if (!idCode.substring(0, 2).equalsIgnoreCase("EE")) return null;
if (idCode.length() != 13) return null;
if (!idCode.substring(2, 13).matches("[0-9]+")) return null;
if (!isGenderValid(Integer.parseInt(idCode.substring(2, 3)))) return null;
if (!isDateValid(
Integer.parseInt(idCode.substring(2, 3)),
idCode.substring(3, 9))) {
return null;
}
if (!verifyControlNumber(idCode)) return null;
return idCode;
}
private static boolean isGenderValid(int gender) {
return gender <= 6 && gender >= 1;
}
private static boolean isDateValid(int gender, String date) {
String fullDate = getFullDate(gender, date);
try {
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("uuuuMMdd")
.withResolverStyle(ResolverStyle.STRICT);
LocalDate.parse(fullDate, formatter);
} catch (DateTimeParseException e) {
return false;
}
return true;
}
private static String getFullDate(int gender, String date) {
switch (gender) {
case 1:
case 2:
return "18" + date;
case 3:
case 4:
return "19" + date;
case 5:
case 6:
return "20" + date;
default:
return date;
}
}
private static boolean verifyControlNumber(String idCode) {
int controlNumber = Integer.parseInt(idCode.substring(12, 13));
int remainder = calculateRemainder(idCode, MULTIPLIER_ONE);
if (remainder == 10) {
remainder = calculateRemainder(idCode, MULTIPLIER_TWO);
}
if (remainder == 10) {
remainder = 0;
}
return remainder == controlNumber;
}
private static int calculateRemainder(String idCode, List<Integer> multiplierList) {
int remainder = 0;
for (int i = 0; i < 10; i++) {
remainder += Integer.parseInt(idCode.substring(i + 2, i + 3)) * multiplierList.get(i);
}
return remainder % 11;
}
}
package commons;
/**
* Helper function to check if a string equals an object
*/
public class IsEqual {
private IsEqual() {
throw new IllegalStateException("Utility class");
}
/**
* @param string String to compare to
* @param object Object to compare with
* @return Either the string if the string and object are equal or an empty string
*/
public static boolean equals(String string, Object object) {
return string.equals(object);
}
}
package commons;
/**
* Helper function to check if a string is empty
*/
public class IsNotEmpty {
private IsNotEmpty() {
throw new IllegalStateException("Utility class");
}
/**
* @param string Input string
* @return True if input string is not empty, false if input string is empty