diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..d31a2bf --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,4 @@ +# Changelog +# 0.1.0 + * ? + diff --git a/README.md b/README.md index 0a849e2..1442a71 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,34 @@ # power-framework - -## Requirements - * Maven - * Java 8 (for example: Amazon Corretto 8 - https://docs.aws.amazon.com/corretto/latest/corretto-8-ug/downloads-list.html) - +## Important notes to read first: + + 1. This is a hobbyist project. + 2. This project is licenced as LGPL 2.1, which also means it is distributed without any warranty. + 3. In case, you find a bug or propose an improvement: + * Raise an issue or participate a new discussion. + +## About + +Power Framework is a Java library. + +It contains several modules: view, collections, json, time, db, persistence, random, reflection, sql, xml and web and others. + +View is an abstraction of JavaFX. Window class may be the most used class of this module and is used as a place for everything user sees. Window class uses custom decorations, system decorations are not used. + +Collections contains full implementation of some collection type like linked list, queue, stack, list, map, set, properties, tree and others. + +Json is used to represent json object and json array as a Java Object. Json files can be parsed to JsonObject instance. Every instance of JsonObject or JsonArray can be printed to minimal or pretty String. + +DB is used to give abstraction for jdbc and SQLite, hides implementation. Database package can be used to store permanent data. + +Persistence is used to dynamically manage SQLite database, create table ddl, insert, update and delete statements are automatically generated from Java classes using reflection. Persistence behaves maybe like the Hibernate library. + +Random is used to generate pseudorandom numbers and is based on linear congruent function and using seeds. + +Time contains some classes used to represent date and time without time zone information, universal date and time, date and time with time zone information. There are also some classes representing durations and period. Time module is partially an abstraction on Java SE time classes, but the interface to use it is a little different. + +Reflection is a abstraction of Java SE reflection classes. + +SQL generates sql Statements. + +Xml is used to generate xml output by Java classes. Web uses xml and creates html pages. diff --git a/pom.xml b/pom.xml index 7aa605e..5fe4ab9 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; + License as published by the Free Software Foundation; version 2.1 of the License only. This library is distributed in the hope that it will be useful, @@ -22,52 +22,148 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + + org.nanoboot.essential + nanoboot-parent + 0.1.0-SNAPSHOT + + org.nanoboot.powerframework power-framework - 1.0.0 - jar + 2.0.0-SNAPSHOT + pom Power Framework - A library with many possibilities + + Power Framework is a bundle of Java many purposes libraries + like working with texts, randomness, collections, json format, + time, database, files, desktop graphics and some others. + + + http://robertvokac/products/power-framework + 2016 + + power-core + power-text + power-random + power-utils + power-collections + + power-json + power-time + power-log + power-io + power-web + + power-wiki + power-bean + power-redmond + power-shark + power-sound + + power-stat + power-sql + power-db + power-persistence + power-svg + + power-view + power-xml + power-reflection + power-mail + power-blockchain + + power-security + + - UTF-8 + 2.0.0-SNAPSHOT true - 8 - - - - - - junit - junit - 4.12 - test - - - org.xerial - sqlite-jdbc - 3.39.3.0 - - - + + + Robert Vokac + robertvokac@nanoboot.org + + developer + project manager + + + + + org.jacoco + jacoco-maven-plugin + ${jacoco-maven-plugin.version} + + + + prepare-agent + + + + + report + test + + report + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + ${checkstyle.skip} + + org.apache.maven.plugins maven-compiler-plugin - ${javase.version} - ${javase.version} + + + org.projectlombok + lombok + ${lombok.version} + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + + + junit + junit + ${junit4.version} + test + + + + + + + org.projectlombok + lombok + ${lombok.version} + provided + + + diff --git a/power-ai/pom.xml b/power-ai/pom.xml new file mode 100644 index 0000000..b01ce82 --- /dev/null +++ b/power-ai/pom.xml @@ -0,0 +1,54 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-ai + jar + + Power AI + Artificial intelligence tools for the Power library + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + + + junit + junit + 4.12 + test + + + + diff --git a/power-ai/src/main/java/module-info.java b/power-ai/src/main/java/module-info.java new file mode 100644 index 0000000..c153b52 --- /dev/null +++ b/power-ai/src/main/java/module-info.java @@ -0,0 +1,29 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * @author Robert Vokac + * @since 0.0.0 + */ + +module powerframework.ai { + +} diff --git a/src/main/java/org/nanoboot/powerframework/utilities/.gitkeep b/power-ai/src/main/java/org/nanoboot/powerframework/ai/.gitkeep similarity index 100% rename from src/main/java/org/nanoboot/powerframework/utilities/.gitkeep rename to power-ai/src/main/java/org/nanoboot/powerframework/ai/.gitkeep diff --git a/src/main/resources/.gitkeep b/power-ai/src/main/resources/.gitkeep similarity index 100% rename from src/main/resources/.gitkeep rename to power-ai/src/main/resources/.gitkeep diff --git a/power-ai/src/test/java/org/nanoboot/powerframework/ai/.gitkeep b/power-ai/src/test/java/org/nanoboot/powerframework/ai/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-bean/pom.xml b/power-bean/pom.xml new file mode 100644 index 0000000..6412e70 --- /dev/null +++ b/power-bean/pom.xml @@ -0,0 +1,54 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-bean + jar + + Power Bean + Dependency functionality for the Power library + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + + + junit + junit + 4.12 + test + + + + diff --git a/power-bean/src/main/java/module-info.java b/power-bean/src/main/java/module-info.java new file mode 100644 index 0000000..7126f67 --- /dev/null +++ b/power-bean/src/main/java/module-info.java @@ -0,0 +1,29 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +module powerframework.bean { + +} diff --git a/power-bean/src/main/java/org/nanoboot/powerframework/bean/.gitkeep b/power-bean/src/main/java/org/nanoboot/powerframework/bean/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-bean/src/main/resources/.gitkeep b/power-bean/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-bean/src/test/java/org/nanoboot/powerframework/bean/.gitkeep b/power-bean/src/test/java/org/nanoboot/powerframework/bean/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-blockchain/pom.xml b/power-blockchain/pom.xml new file mode 100644 index 0000000..84f58c1 --- /dev/null +++ b/power-blockchain/pom.xml @@ -0,0 +1,122 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + org.nanoboot.powerframework + power-blockchain + jar + + Power Blockchain + Blockchain library + + + + + + org.apache.maven.plugins + maven-assembly-plugin + 3.3.0 + + + + org.nanoboot.powerframework.blockchain.orig.core.Main + + + + jar-with-dependencies + + + + + make-assembly + package + + single + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + org.nanoboot.powerframework.blockchain.orig.core.Main + + + + + + + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + org.nanoboot.powerframework + power-time + ${power.version} + + + org.nanoboot.powerframework + power-json + ${power.version} + + + org.nanoboot.powerframework + power-random + ${power.version} + + + org.nanoboot.powerframework + power-security + ${power.version} + + + + + junit + junit + 4.12 + test + + + org.projectlombok + lombok + 1.18.10 + compile + + + + diff --git a/power-blockchain/src/main/java/module-info.java b/power-blockchain/src/main/java/module-info.java new file mode 100644 index 0000000..0689fa1 --- /dev/null +++ b/power-blockchain/src/main/java/module-info.java @@ -0,0 +1,34 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +module powerframework.blockchain { + requires lombok; + requires powerframework.core; + requires powerframework.time; + requires powerframework.json; + requires powerframework.random; + requires powerframework.security; +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/.gitkeep b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/api/BlockDeserializer.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/api/BlockDeserializer.java new file mode 100644 index 0000000..97eee57 --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/api/BlockDeserializer.java @@ -0,0 +1,33 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.api; + +import org.nanoboot.powerframework.blockchain.core.Block; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public interface BlockDeserializer { + Block deserialize(String serializedBlock); +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/api/BlockSerializer.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/api/BlockSerializer.java new file mode 100644 index 0000000..8a7ba93 --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/api/BlockSerializer.java @@ -0,0 +1,33 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.api; + +import org.nanoboot.powerframework.blockchain.core.Block; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public interface BlockSerializer { + String serialize(Block block); +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/core/Block.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/core/Block.java new file mode 100644 index 0000000..8115ecd --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/core/Block.java @@ -0,0 +1,132 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.core; + +import org.nanoboot.powerframework.blockchain.api.BlockSerializer; +import org.nanoboot.powerframework.json.JsonObject; +import org.nanoboot.powerframework.json.JsonObjectSerializable; +import org.nanoboot.powerframework.security.hash.api.HashCalculator; +import org.nanoboot.powerframework.time.moment.UniversalDateTime; +import lombok.Getter; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Block implements JsonObjectSerializable { + private static final String BLOCKCHAIN_PROTOCOL = "blockchainProtocol"; + + private static final String HEIGHT = "height"; + + private static final String PREVIOUS_HASH = "previousHash"; + private static final String TIMESTAMP = "timestamp"; + private static final String DIFFICULTY = "difficulty"; + private static final String DATA = "data"; + private static final String NONCE = "nonce"; + + @Getter + private final BlockchainProtocol blockchainProtocol; + + @Getter + private final long height; + @Getter + private final String previousHash; + @Getter + private final String timeStamp; + @Getter + private final String difficultyTarget; + @Getter + private final byte[] data; + + @Getter + private long nonce; + + // + @Getter + private String hash = null; + + //Block Constructor. + public Block(BlockchainProtocol blockchainProtocol, + long height, + String previousHash, + String difficultyTarget, + byte[] data) { + this.blockchainProtocol=blockchainProtocol; + this.height = height; + this.previousHash = previousHash; + this.timeStamp = UniversalDateTime.now().toString(); + this.difficultyTarget = difficultyTarget; + this.data = data; + } + + //Calculate new hash based on blocks contents + public String calculateHash(HashCalculator hashCalculator, BlockSerializer blockSerializer) { + String serializedBlock = blockSerializer.serialize(this); + String calculatedhash = hashCalculator.hash(serializedBlock); + return calculatedhash; + } + + //Increases nonce value until hash target is reached. + public void mineBlock(HashCalculator hashCalculator, BlockSerializer blockSerializer) { + String target = this.difficultyTarget; + + for (long i = 0; i <= Long.MAX_VALUE; i++) { + this.nonce = i; + if (nonce == Integer.MAX_VALUE) { + throw new BlockChainException("Nonce was not found."); + } + if (nonce % 1000000 == 0) { + System.out.println("Nonce # " + nonce); + } + + + + String hash = calculateHash(hashCalculator, blockSerializer); + + if (hashCalculator.compareHexNumbers(hash, this.getDifficultyTarget()) <= 0) { + System.out.println("Found nonce: " + nonce + " A new block was just mined: " + getHash() + "\n" /*+ block.toJsonObject().toPrettyString()*/); + System.out.println("Block Mined!!! : " + hash); + break; + } + } + + } + + @Override + public JsonObject toJsonObject() { + + JsonObject jo = new JsonObject(); + + jo.add(BLOCKCHAIN_PROTOCOL, blockchainProtocol.toJsonObject()); + + jo.add(HEIGHT, height); + + jo.add(PREVIOUS_HASH, previousHash); + jo.add(TIMESTAMP, timeStamp); + jo.add(DIFFICULTY, difficultyTarget); + jo.add(DATA, new String(data)); + jo.add(NONCE, nonce); + + return jo; + } +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/core/BlockChainException.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/core/BlockChainException.java new file mode 100644 index 0000000..0fc92fb --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/core/BlockChainException.java @@ -0,0 +1,35 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.core; + +import org.nanoboot.powerframework.core.PowerException; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class BlockChainException extends PowerException { + public BlockChainException(String msg) { + super(msg); + } +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/core/BlockchainEngine.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/core/BlockchainEngine.java new file mode 100644 index 0000000..ba4b606 --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/core/BlockchainEngine.java @@ -0,0 +1,40 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.core; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +import java.util.ArrayList; +import java.util.List; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@AllArgsConstructor +public class BlockchainEngine { + @Getter + private final String protocolName; + private List blockchainEngineVersionList = new ArrayList<>(); +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/core/BlockchainEngineVersion.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/core/BlockchainEngineVersion.java new file mode 100644 index 0000000..05ab32d --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/core/BlockchainEngineVersion.java @@ -0,0 +1,54 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.core; + +import org.nanoboot.powerframework.blockchain.api.BlockSerializer; +import lombok.AllArgsConstructor; +import lombok.Getter; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@AllArgsConstructor +public class BlockchainEngineVersion { + @Getter + private final String version; + @Getter + private final String hashCalculatorName; + @Getter + private final String targetDifficulty; + @Getter + private final BlockSerializer blockSerializer; + @Getter + private final long validFromBlock; + @Getter + private final long validUntilBlock; + + public String getMayorVersion() { + return version.split(("\\."))[0]; + } + public String getMinorVersion() { + return version.split(("\\."))[1]; + } +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/core/BlockchainProtocol.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/core/BlockchainProtocol.java new file mode 100644 index 0000000..48814be --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/core/BlockchainProtocol.java @@ -0,0 +1,56 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.core; + +import org.nanoboot.powerframework.json.JsonObject; +import org.nanoboot.powerframework.json.JsonObjectSerializable; +import lombok.AllArgsConstructor; +import lombok.Getter; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@AllArgsConstructor +public class BlockchainProtocol implements JsonObjectSerializable { + private static final String PROTOCOL_NAME = "protocolName"; + private static final String PROTOCOL_MAYOR_VERSION = "protocolMayorVersion"; + private static final String PROTOCOL_MINOR_VERSION = "protocolMinorVersion"; + @Getter + private final String protocolName; + @Getter + private final int protocolMayorVersion; + @Getter + private final int protocolMinorVersion; + @Override + public JsonObject toJsonObject() { + + JsonObject jo = new JsonObject(); + + jo.add(PROTOCOL_NAME, protocolName); + jo.add(PROTOCOL_MAYOR_VERSION, protocolMayorVersion); + jo.add(PROTOCOL_MINOR_VERSION, protocolMinorVersion); + + return jo; + } +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/impl/JsonBlockSerializer.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/impl/JsonBlockSerializer.java new file mode 100644 index 0000000..23d0a42 --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/impl/JsonBlockSerializer.java @@ -0,0 +1,40 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.impl; + +import org.nanoboot.powerframework.blockchain.api.BlockSerializer; +import org.nanoboot.powerframework.blockchain.core.Block; +import org.nanoboot.powerframework.json.JsonObject; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class JsonBlockSerializer implements BlockSerializer { + + @Override + public String serialize(Block block) { + JsonObject jsonObject = block.toJsonObject(); + return jsonObject.toMinimalString(); + } +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/impl/StringSerializer.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/impl/StringSerializer.java new file mode 100644 index 0000000..5fe3ae6 --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/impl/StringSerializer.java @@ -0,0 +1,45 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.impl; + +import org.nanoboot.powerframework.blockchain.api.BlockSerializer; +import org.nanoboot.powerframework.blockchain.core.Block; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class StringSerializer implements BlockSerializer { + + public static final String SEPARATOR = "::"; + + @Override + public String serialize(Block block) { + return block.getBlockchainProtocol().toString() + SEPARATOR + + block.getHeight() + SEPARATOR + + block.getPreviousHash() + SEPARATOR + + block.getTimeStamp() + SEPARATOR + + block.getDifficultyTarget() + SEPARATOR + + new String(block.getData()) + SEPARATOR + + block.getNonce(); + } +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/api/BlockData.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/api/BlockData.java new file mode 100644 index 0000000..f619d87 --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/api/BlockData.java @@ -0,0 +1,31 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.orig.api; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public interface BlockData { + String convertToString(); +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/api/BlockDeserializer.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/api/BlockDeserializer.java new file mode 100644 index 0000000..3cda061 --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/api/BlockDeserializer.java @@ -0,0 +1,33 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.orig.api; + +import org.nanoboot.powerframework.blockchain.orig.base.Block; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public interface BlockDeserializer { + Block deserialize(String serializedBlock); +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/api/BlockMiner.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/api/BlockMiner.java new file mode 100644 index 0000000..24a1371 --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/api/BlockMiner.java @@ -0,0 +1,35 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.orig.api; + +import org.nanoboot.powerframework.blockchain.orig.base.Block; +import org.nanoboot.powerframework.blockchain.orig.base.BlockFragment; +import org.nanoboot.powerframework.blockchain.orig.base.BlockType; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public interface BlockMiner { + Block mine(BlockFragment blockFragment, BlockType blockType); +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/api/BlockSerializer.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/api/BlockSerializer.java new file mode 100644 index 0000000..fb9c75f --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/api/BlockSerializer.java @@ -0,0 +1,33 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.orig.api; + +import org.nanoboot.powerframework.blockchain.orig.base.Block; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public interface BlockSerializer { + String serialize(Block block); +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/api/BlockValidator.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/api/BlockValidator.java new file mode 100644 index 0000000..6eaad05 --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/api/BlockValidator.java @@ -0,0 +1,35 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.orig.api; + +import org.nanoboot.powerframework.blockchain.orig.base.Block; +import org.nanoboot.powerframework.blockchain.orig.base.BlockType; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public interface BlockValidator { + BlockType getBlockType(); + void validate(Block block); +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/base/Block.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/base/Block.java new file mode 100644 index 0000000..0a076ca --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/base/Block.java @@ -0,0 +1,117 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.orig.base; + +import org.nanoboot.powerframework.blockchain.orig.api.BlockData; +import org.nanoboot.powerframework.blockchain.core.BlockChainException; +import org.nanoboot.powerframework.json.JsonObject; +import org.nanoboot.powerframework.json.JsonObjectSerializable; +import lombok.Getter; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Block implements JsonObjectSerializable { + public static final String BLOCK_TYPE_ID = "blockTypeId"; + public static final String BLOCK_HEADER = "blockHeader"; + public static final String BLOCK_DATA = "blockData"; + public static final String NONCE = "nonce"; + + @Getter + private BlockHeader blockHeader; + + @Getter + private BlockData blockData; + + private long nonce; + + @Getter + private String hash; + @Getter + private boolean locked = false; + + @Getter + private BlockType internalBlockType; + + public Block(BlockHeader blockHeader, JsonObject additionBlockHeader, BlockData blockData) { + this.blockHeader = blockHeader; + + this.blockData = blockData; + } + + public void injectBlockType(BlockType blockType) { + this.internalBlockType = blockType; + } + + public String calculateHashTest(long nonce) { + this.nonce = nonce; + String hashedSerializedBlock = internalCalculateHash(); + this.nonce = 0;//todo + return hashedSerializedBlock; + } + + private String internalCalculateHash() { + if (nonce == 0) { + throw new BlockChainException("Nonce cannot be zero."); + } + if (locked) { + throw new BlockChainException("This block is already locked. Cannot set nonce and calculate nonce."); + } + + if (internalBlockType == null) { + throw new BlockChainException("internalBlockType was not injected."); + } + String serializedBlock = this.internalBlockType.getBlockSerializer().serialize(this); + + String hashedSerializedBlock = this.internalBlockType.getHashCalculator().hash(serializedBlock); + + //System.out.println("internalCalculateHash - hash for nonce " + nonce + " = " + hashedSerializedBlock); + return hashedSerializedBlock; + } + + public void lock(long nonce) { + this.nonce = nonce; + String hashedSerializedBlock = internalCalculateHash(); + this.hash = hashedSerializedBlock; + + this.locked = true; + } + + @Override + public JsonObject toJsonObject() { + if (nonce == 0) { + throw new BlockChainException("Nonce cannot be zero, if json object is created from this block instance."); + } + if (internalBlockType == null) { + throw new BlockChainException("internalBlockType was not injected."); + } + JsonObject jo = new JsonObject(); + jo.add(BLOCK_TYPE_ID, internalBlockType.getBlockTypeId()); + jo.add(BLOCK_HEADER, blockHeader.toJsonObject()); + + jo.add(BLOCK_DATA, blockData.convertToString()); + jo.add(NONCE, nonce); + return jo; + } +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/base/BlockChain.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/base/BlockChain.java new file mode 100644 index 0000000..4c0323e --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/base/BlockChain.java @@ -0,0 +1,100 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.orig.base; + +import org.nanoboot.powerframework.blockchain.core.BlockChainException; + +import java.util.ArrayList; +import java.util.List; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class BlockChain { + private String blockChainEngineName; + private List blocks = new ArrayList<>(); + + public int getTotalHeight() { + return blocks.size() - 1; + } + + public boolean isEmpty() { + return blocks.isEmpty(); + } + + public Block getGenesisBlock() { + if (isEmpty()) { + return null; + } + return getBlock(0); + } + + public Block getLastBlock() { + if (isEmpty()) { + return null; + } + return getBlock(blocks.size() - 1); + } + + public List getLastXBlocks(int xCount) { + List result = new ArrayList<>(); + + if (isEmpty()) { + return result; + } + if (xCount <= blocks.size()) { + for (Block b : blocks) { + result.add(b); + } + return result; + } + for (int i = blocks.size() - xCount; i <= (blocks.size() - 1); i++) { + result.add(blocks.get(i)); + } + return result; + } + + public void addBlock(Block block) { + if (!block.isLocked()) { + throw new BlockChainException("Block is not locked. It cannot be added"); + } + if (blocks.isEmpty() && block.getBlockHeader().getHeight() != 0) { + throw new BlockChainException("New block is a genesis block, but its height is not zero."); + } + Block lastBlock = getLastBlock(); + String previousBlockHash = lastBlock == null ? "0" : lastBlock.getHash(); + + if (!block.getBlockHeader().getPreviousHash().equals(previousBlockHash)) { + throw new BlockChainException("Block previous hash is not equal to the hash of the previous block. It cannot be added to the blockchain."); + } + blocks.add(block); + } + + public Block getBlock(int blockHeight) { + if (blockHeight >= blocks.size()) { + throw new BlockChainException("There is no block with height " + blockHeight); + } + return blocks.get(blockHeight); + } +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/base/BlockChainEngine.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/base/BlockChainEngine.java new file mode 100644 index 0000000..ffe7f3b --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/base/BlockChainEngine.java @@ -0,0 +1,55 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.orig.base; + +import org.nanoboot.powerframework.blockchain.core.BlockChainException; +import lombok.AllArgsConstructor; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@AllArgsConstructor +public abstract class BlockChainEngine { + private String blockChainEngineName; + protected BlockChain blockChain; + protected BlockTypeVersionList blockTypeVersionList; + + public void addData(String data) { + BlockFragment blockFragment = createNewBlockFragment(data); + BlockType blockType = blockTypeVersionList.findBlockType(blockFragment.getBlockHeader().getBlockTypeId()); + if (blockType == null) { + throw new BlockChainException("blockType " + blockFragment.getBlockHeader().getBlockTypeId() + " was not found."); + } + + Block block = blockType.getBlockMiner().mine(blockFragment, blockType); + addBlock(block); + } + + public abstract BlockFragment createNewBlockFragment(String data); + + public void addBlock(Block newBlock) { + blockChain.addBlock(newBlock); + } + +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/base/BlockFragment.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/base/BlockFragment.java new file mode 100644 index 0000000..0cedbf0 --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/base/BlockFragment.java @@ -0,0 +1,42 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.orig.base; + +import org.nanoboot.powerframework.blockchain.orig.api.BlockData; +import org.nanoboot.powerframework.json.JsonObject; +import lombok.AllArgsConstructor; +import lombok.Getter; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@AllArgsConstructor +public class BlockFragment { + @Getter + private BlockHeader blockHeader; + + @Getter + private BlockData blockData; + +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/base/BlockHeader.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/base/BlockHeader.java new file mode 100644 index 0000000..6272d74 --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/base/BlockHeader.java @@ -0,0 +1,60 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.orig.base; + +import org.nanoboot.powerframework.json.JsonObject; +import org.nanoboot.powerframework.json.JsonObjectSerializable; +import lombok.AllArgsConstructor; +import lombok.Getter; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@AllArgsConstructor +public class BlockHeader implements JsonObjectSerializable { + public static final String BLOCK_TYPE_ID = "blockTypeId"; + public static final String HEIGHT = "height"; + public static final String TIME_STAMP = "timeStamp"; + public static final String PREVIOUS_HASH = "previousHash"; + @Getter + private String blockTypeId; + @Getter + private int height; + @Getter + private long timeStamp; + @Getter + private String previousHash; + @Getter + private String difficulty; + + public JsonObject toJsonObject() { + JsonObject jo = new JsonObject(); + jo.add(BLOCK_TYPE_ID, blockTypeId); + jo.add(HEIGHT, height); + jo.add(TIME_STAMP, timeStamp); + jo.add(PREVIOUS_HASH, previousHash); + return jo; + } + +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/base/BlockType.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/base/BlockType.java new file mode 100644 index 0000000..7280eb3 --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/base/BlockType.java @@ -0,0 +1,55 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.orig.base; + +import org.nanoboot.powerframework.blockchain.orig.api.BlockDeserializer; +import org.nanoboot.powerframework.blockchain.orig.api.BlockMiner; +import org.nanoboot.powerframework.blockchain.orig.api.BlockSerializer; +import org.nanoboot.powerframework.security.hash.api.HashCalculator; +import lombok.AllArgsConstructor; +import lombok.Getter; +@AllArgsConstructor +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class BlockType { + @Getter + private String type; + @Getter + private int mayorVersion; + @Getter + private int minorVersion; + @Getter + private HashCalculator hashCalculator; + @Getter + private BlockSerializer blockSerializer; + @Getter + private BlockDeserializer blockDeserializer; + @Getter + BlockMiner blockMiner; + public String getBlockTypeId() { + return type + ":" + mayorVersion + ":" + minorVersion; + } +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/base/BlockTypeVersionList.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/base/BlockTypeVersionList.java new file mode 100644 index 0000000..ec6b8d8 --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/base/BlockTypeVersionList.java @@ -0,0 +1,47 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.orig.base; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class BlockTypeVersionList { + private Map blockTypes; + + public BlockTypeVersionList(List blockTypesList) { + blockTypes = new HashMap<>(); + for (BlockType bt : blockTypesList) { + blockTypes.put(bt.getBlockTypeId(), bt); + } + } + + public BlockType findBlockType(String blockTypeId) { + return blockTypes.get(blockTypeId); + } +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/cash/Transaction.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/cash/Transaction.java new file mode 100644 index 0000000..d794978 --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/cash/Transaction.java @@ -0,0 +1,29 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.orig.cash; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class Transaction { +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/cash/TransactionValidator.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/cash/TransactionValidator.java new file mode 100644 index 0000000..70e6ccf --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/cash/TransactionValidator.java @@ -0,0 +1,29 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.orig.cash; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class TransactionValidator { +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/cash/Wallet.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/cash/Wallet.java new file mode 100644 index 0000000..0f09071 --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/cash/Wallet.java @@ -0,0 +1,29 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.orig.cash; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class Wallet { +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/core/Main.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/core/Main.java new file mode 100644 index 0000000..d14916c --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/core/Main.java @@ -0,0 +1,48 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.orig.core; + +import org.nanoboot.powerframework.blockchain.orig.base.BlockChain; +import org.nanoboot.powerframework.blockchain.orig.impl.TestCash_BlockChainEngine; +import org.nanoboot.powerframework.random.generators.linearcongruent.combined.w5.W5RandomGenerator; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Main { + public static void main(String[] args) { +// HashCalculator.main(null); +// +// if(true) return; + BlockChain blockChain = new BlockChain(); + TestCash_BlockChainEngine bce = new TestCash_BlockChainEngine(blockChain); + bce.addData("ahoj"); + bce.addData("pavle"); + bce.addData("leo"); + for(int i =0;i<100000000;i++){ + bce.addData(W5RandomGenerator.getStaticInstance().nextText(8)); + } + + } +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/impl/JsonBlockSerializer.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/impl/JsonBlockSerializer.java new file mode 100644 index 0000000..5e6ae63 --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/impl/JsonBlockSerializer.java @@ -0,0 +1,41 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.orig.impl; + +import org.nanoboot.powerframework.blockchain.orig.api.BlockSerializer; +import org.nanoboot.powerframework.blockchain.orig.base.Block; +import org.nanoboot.powerframework.json.JsonObject; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class JsonBlockSerializer implements BlockSerializer { + + @Override + public String serialize(Block block) { + JsonObject jsonObject = block.toJsonObject(); + //System.out.println(jsonObject.toMinimalString()); + return jsonObject.toMinimalString(); + } +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/impl/SimpleBlockData.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/impl/SimpleBlockData.java new file mode 100644 index 0000000..53b1351 --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/impl/SimpleBlockData.java @@ -0,0 +1,40 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.orig.impl; + +import org.nanoboot.powerframework.blockchain.orig.api.BlockData; +import lombok.AllArgsConstructor; +import lombok.Getter; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +@AllArgsConstructor +public class SimpleBlockData implements BlockData { + @Getter + private final String string; + @Override + public String convertToString() { + return string; + } +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/impl/TestCash_1_0_Block.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/impl/TestCash_1_0_Block.java new file mode 100644 index 0000000..2090d02 --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/impl/TestCash_1_0_Block.java @@ -0,0 +1,36 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.orig.impl; + +import org.nanoboot.powerframework.blockchain.orig.api.BlockData; +import org.nanoboot.powerframework.blockchain.orig.base.BlockHeader; +import org.nanoboot.powerframework.blockchain.orig.base.Block; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class TestCash_1_0_Block extends Block { + public TestCash_1_0_Block(BlockHeader blockHeader, BlockData blockData) { + super(blockHeader, null, blockData); + } +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/impl/TestCash_1_0_BlockMiner.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/impl/TestCash_1_0_BlockMiner.java new file mode 100644 index 0000000..e0a132d --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/impl/TestCash_1_0_BlockMiner.java @@ -0,0 +1,95 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.orig.impl; + +import org.nanoboot.powerframework.blockchain.orig.api.BlockMiner; +import org.nanoboot.powerframework.blockchain.orig.base.Block; +import org.nanoboot.powerframework.blockchain.orig.base.BlockFragment; +import org.nanoboot.powerframework.blockchain.orig.base.BlockType; +import org.nanoboot.powerframework.blockchain.core.BlockChainException; +import org.nanoboot.powerframework.security.hash.api.HashCalculator; +import org.nanoboot.powerframework.time.duration.Duration; +import org.nanoboot.powerframework.time.duration.StopWatch; +import org.nanoboot.powerframework.time.utils.TimeUnit; + +import java.util.ArrayList; +import java.util.List; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class TestCash_1_0_BlockMiner implements BlockMiner { + public static List lastFiveBlockMiningTimesInMilliseconds = new ArrayList<>(); + + @Override + public Block mine(BlockFragment blockFragment, BlockType blockType) { + + TestCash_1_0_Block block = new TestCash_1_0_Block(blockFragment.getBlockHeader(), blockFragment.getBlockData()); + block.injectBlockType(blockType); + + ////System.out.println("Starting mining block # " + block.getBlockHeader().getHeight()); + //System.out.println("Note: One block should be mined in 1 minute, but the last time was " + countOfSecondsToMineLastBlock + " second(s)."); + //System.out.println("Starting mining block # " + block.getBlockHeader().getHeight()); + StopWatch sw = new StopWatch(); + + //System.out.println("start: " + UniversalDateTime.now().toString()); + sw.start(); + + ////System.out.println("Searching hash equal or less than " + block.getBlockHeader().getDifficulty()); + for (long nonce = 1; nonce <= Long.MAX_VALUE; nonce++) { + if (nonce == Integer.MAX_VALUE) { + throw new BlockChainException("Nonce was not found."); + } + if (nonce % 1000000 == 0) { + System.out.println("Nonce # " + nonce); + } + + + HashCalculator hashCalculator = block.getInternalBlockType().getHashCalculator(); + String hash = block.calculateHashTest(nonce); + //System.err.println("hashCalculator.compareHexNumbers("+hash+"+, block.getBlockHeader().getDifficulty()="+block.getBlockHeader().getDifficulty()+")="+hashCalculator.compareHexNumbers(hash, block.getBlockHeader().getDifficulty())); + if (hashCalculator.compareHexNumbers(hash, block.getBlockHeader().getDifficulty()) <= 0) { + + //System.err.println("hashCalculator.compareHexNumbers("+hash+"+, block.getBlockHeader().getDifficulty()="+block.getBlockHeader().getDifficulty()+")="+hashCalculator.compareHexNumbers(hash, block.getBlockHeader().getDifficulty())); + block.lock(nonce); + ////System.out.println("Found nonce: " + nonce + " A new block was just mined: " + block.getHash() + "\n" /*+ block.toJsonObject().toPrettyString()*/); + + break; + } + } + + //System.out.println("end: " + UniversalDateTime.now().toString()); + sw.stop(); + Duration lastDuration = sw.getCurrentDuration(); + if (lastFiveBlockMiningTimesInMilliseconds.size() == 1000) { + lastFiveBlockMiningTimesInMilliseconds.remove(0); + } + lastFiveBlockMiningTimesInMilliseconds.add((int) lastDuration.toTotal(TimeUnit.MILLISECOND)); + //countOfSecondsToMineLastBlock = (int) lastDuration.toTotal(TimeUnit.SECOND); + if (block.getBlockHeader().getHeight() % 100 == 0) + System.out.println("Mining block " + block.getBlockHeader().getHeight() + " + took " + lastDuration.toString() + " ."); + return block; + } + + +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/impl/TestCash_1_0_BlockType.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/impl/TestCash_1_0_BlockType.java new file mode 100644 index 0000000..284f671 --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/impl/TestCash_1_0_BlockType.java @@ -0,0 +1,39 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.orig.impl; + +import org.nanoboot.powerframework.blockchain.orig.base.BlockType; +import org.nanoboot.powerframework.security.hash.locator.HashCalculatorLocator; +import org.nanoboot.powerframework.security.hash.locator.HashImpl; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class TestCash_1_0_BlockType extends BlockType { +private static final String TYPE = "test_cash"; +private static final int MAYOR_VERSION = 1; +private static final int MINOR_VERSION = 0; + public TestCash_1_0_BlockType() { + super(TYPE, MAYOR_VERSION, MINOR_VERSION, HashCalculatorLocator.locate(HashImpl.SHA_256), new JsonBlockSerializer(), null, new TestCash_1_0_BlockMiner()); + } +} diff --git a/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/impl/TestCash_BlockChainEngine.java b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/impl/TestCash_BlockChainEngine.java new file mode 100644 index 0000000..5314529 --- /dev/null +++ b/power-blockchain/src/main/java/org/nanoboot/powerframework/blockchain/orig/impl/TestCash_BlockChainEngine.java @@ -0,0 +1,136 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.blockchain.orig.impl; + +import org.nanoboot.powerframework.blockchain.orig.base.*; +import org.nanoboot.powerframework.security.hash.api.HashCalculator; +import org.nanoboot.powerframework.time.duration.Duration; +import org.nanoboot.powerframework.time.moment.UniversalDateTime; +import org.nanoboot.powerframework.time.utils.TimeUnit; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.List; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class TestCash_BlockChainEngine extends BlockChainEngine { + + public static final String TEST_CASH = "TestCash"; + public static final int COUNT_OF_MILLISECONDS_TO_MINE_A_BLOCK = 10; + //public static final String DEFAULT_DIFFICULTY = "0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; + public static final String DEFAULT_DIFFICULTY = "00184f329993e8d38cd0a31969b54367b4fc5af6ed86d827c1343dbf8b66a4a5"; + + public static float DIFFICULTY_PERCENT_CHANGE = (float) 1; + + public TestCash_BlockChainEngine(BlockChain blockChain) { + super(TEST_CASH, blockChain, new BlockTypeVersionList(List.of(new TestCash_1_0_BlockType()))); + } + + @Override + public BlockFragment createNewBlockFragment(String data) { + Block lastBlock = blockChain.getLastBlock(); + int newBlockHeight = lastBlock == null ? 0 : lastBlock.getBlockHeader().getHeight() + 1; + long newTimeStamp = UniversalDateTime.now().toLong(); + String previousBlockHash = lastBlock == null ? "0" : lastBlock.getHash(); + String oldDifficulty = lastBlock == null ? DEFAULT_DIFFICULTY : lastBlock.getBlockHeader().getDifficulty(); + String newDifficulty = oldDifficulty; + + int newDifficultyPeriod = 1000; + if (lastBlock != null && newBlockHeight % newDifficultyPeriod == 0) { + + List lastBlocks = blockChain.getLastXBlocks(newDifficultyPeriod); + int lastBlocksCount = lastBlocks.size(); + Block blockStart = lastBlocks.get(0); + Block blockEnd = lastBlocks.get(lastBlocks.size() - 1); + long moment1 = blockStart.getBlockHeader().getTimeStamp(); + long moment2 = blockEnd.getBlockHeader().getTimeStamp(); + UniversalDateTime udt1 = new UniversalDateTime(moment1); + UniversalDateTime udt2 = new UniversalDateTime(moment2); + Duration duration = new org.nanoboot.powerframework.time.duration.Period(udt1, udt2).getDuration(); + duration.toTotal(TimeUnit.SECOND); + double averageCountOfMillisecondsToMineABlockForTenLastBlocks = (duration.toTotal(TimeUnit.SECOND) / (lastBlocksCount - 1)); + + int countX = 0; + int sum = 0; + for (Integer i : TestCash_1_0_BlockMiner.lastFiveBlockMiningTimesInMilliseconds) { + sum = sum + i; + countX = countX + 1; + } + System.out.println("sumInSeconds="+((double)sum)); + + averageCountOfMillisecondsToMineABlockForTenLastBlocks = ((((double) sum) / ((double) countX)) /*/ 1*/); + System.out.println("averageCountOfMillisecondsToMineABlockForTenLastBlocks=" + averageCountOfMillisecondsToMineABlockForTenLastBlocks); + boolean plus = false; + if(((int)Math.round(averageCountOfMillisecondsToMineABlockForTenLastBlocks))==COUNT_OF_MILLISECONDS_TO_MINE_A_BLOCK) { + DIFFICULTY_PERCENT_CHANGE=1f/16; + } else { + if(DIFFICULTY_PERCENT_CHANGE != (float) 1f/1f) { + DIFFICULTY_PERCENT_CHANGE = (float) 1f/1f; + } + } + if (averageCountOfMillisecondsToMineABlockForTenLastBlocks < COUNT_OF_MILLISECONDS_TO_MINE_A_BLOCK) { + plus = false; + System.out.println("Difficulty +++ increasing"); + + } + if (averageCountOfMillisecondsToMineABlockForTenLastBlocks > COUNT_OF_MILLISECONDS_TO_MINE_A_BLOCK) { + plus = true; + System.out.println("Difficulty --- decreasing"); + } +// if (DIFFICULTY_PERCENT_CHANGE >= 16) { +// DIFFICULTY_PERCENT_CHANGE = 4; +// } + + System.out.println("averageCountOfSecondsToMineABlockForTenLastBlocks=" + averageCountOfMillisecondsToMineABlockForTenLastBlocks); + if (averageCountOfMillisecondsToMineABlockForTenLastBlocks != COUNT_OF_MILLISECONDS_TO_MINE_A_BLOCK) { + //DIFFICULTY_PERCENT_CHANGE = DIFFICULTY_PERCENT_CHANGE * 2; + double realDifficultyPercentChange = DIFFICULTY_PERCENT_CHANGE; + double more = averageCountOfMillisecondsToMineABlockForTenLastBlocks > COUNT_OF_MILLISECONDS_TO_MINE_A_BLOCK ? averageCountOfMillisecondsToMineABlockForTenLastBlocks : COUNT_OF_MILLISECONDS_TO_MINE_A_BLOCK; + double less = averageCountOfMillisecondsToMineABlockForTenLastBlocks < COUNT_OF_MILLISECONDS_TO_MINE_A_BLOCK ? averageCountOfMillisecondsToMineABlockForTenLastBlocks : COUNT_OF_MILLISECONDS_TO_MINE_A_BLOCK; + + if ((less / more) < 0.5) { + realDifficultyPercentChange = 50; + } + double change = 1 + ((plus ? 1 : (-1)) * (realDifficultyPercentChange / 100)); +// if((double)(averageCountOfSecondsToMineABlockForTenLastBlocks) / (double)(COUNT_OF_SECONDS_TO_MINE_A_BLOCK)<0.9 || (double)(averageCountOfSecondsToMineABlockForTenLastBlocks) / (double)(COUNT_OF_SECONDS_TO_MINE_A_BLOCK)> 1.1){ +// change = 1 + ((plus ? 1 : (-1)) * (25f / 100)); +// } + System.out.println(" Changing to " + change); + BlockType blockType = blockTypeVersionList.findBlockType("test_cash:1:0"); + HashCalculator hashCalculator = blockType.getHashCalculator(); + String oldDifficultyAsDec = hashCalculator.convertHexStringToDecString(oldDifficulty); + System.out.println("oldDifficultyAsDec=" + oldDifficultyAsDec); + BigInteger bi = new BigDecimal(oldDifficultyAsDec).multiply(new BigDecimal(change)).toBigInteger(); + System.out.println("newDifficultyAsDec=" + bi.toString()); + newDifficulty = hashCalculator.convertDecStringToHexString(bi.toString()); + System.err.println("NEW_DIFFICULTY = " + newDifficulty); + } else { + //DIFFICULTY_PERCENT_CHANGE = DIFFICULTY_PERCENT_CHANGE / 2; + } + } + BlockHeader blockHeader = new BlockHeader("test_cash:1:0", newBlockHeight, newTimeStamp, previousBlockHash, newDifficulty); + return new BlockFragment(blockHeader, new SimpleBlockData(data)); + } +} diff --git a/power-blockchain/src/main/resources/.gitkeep b/power-blockchain/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-blockchain/src/test/java/org/nanoboot/powerframework/blockchain/.gitkeep b/power-blockchain/src/test/java/org/nanoboot/powerframework/blockchain/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-collections/pom.xml b/power-collections/pom.xml new file mode 100644 index 0000000..0534183 --- /dev/null +++ b/power-collections/pom.xml @@ -0,0 +1,73 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-collections + jar + + Power Collections + Collections functionality for the Power library + + + true + + + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + org.nanoboot.powerframework + power-random + ${power.version} + + + org.nanoboot.powerframework + power-utils + ${power.version} + + + org.projectlombok + lombok + + + + + junit + junit + 4.12 + test + + + + diff --git a/power-collections/src/main/java/module-info.java b/power-collections/src/main/java/module-info.java new file mode 100644 index 0000000..b35b49d --- /dev/null +++ b/power-collections/src/main/java/module-info.java @@ -0,0 +1,37 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +//TODO: collections should have methods returning this + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +module powerframework.collections { + exports org.nanoboot.powerframework.collections; + exports org.nanoboot.powerframework.collections.arrays; + requires powerframework.core; + requires powerframework.random; + requires powerframework.utils; + requires lombok; +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/BinaryTreeNode.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/BinaryTreeNode.java new file mode 100644 index 0000000..ceb3238 --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/BinaryTreeNode.java @@ -0,0 +1,176 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.Setter; +import org.nanoboot.powerframework.collections.internal.AbstractTreeNode; + +/** + * + * @param + * + * @author Robert Vokac + * @since 0.0.0 + */ +public final class BinaryTreeNode extends AbstractTreeNode { + /** + * Left node. + */ + @Getter + private BinaryTreeNode left = null; + /** + * Right node. + */ + @Getter + private BinaryTreeNode right = null; + /** + * Type of the node. + * + */ + @Getter + @Setter(AccessLevel.PACKAGE) + private BinaryTreeNodeType type = BinaryTreeNodeType.UNDEFINED; + /** + * + */ + public BinaryTreeNode() { + } + + /** + * + * @param valueIn the value + */ + public BinaryTreeNode(final T valueIn) { + this.setValue(valueIn); + } + + /** + * + * @param valueIn value + * @param leftIn left child + * @param rightIn right child + */ + public BinaryTreeNode( + final T valueIn, + final BinaryTreeNode leftIn, + final BinaryTreeNode rightIn) { + this(valueIn); + this.setLeft(leftIn); + this.setRight(rightIn); + } + + /** + * + * @param valueIn value + * @param typeIn type of node + * @param nodeIn node to add + */ + public BinaryTreeNode( + final T valueIn, + final BinaryTreeNodeType typeIn, + final BinaryTreeNode nodeIn) { + this(valueIn); + this.setNode(typeIn, nodeIn); + } + + + /** + * @param typeIn node type + * @return + */ + public BinaryTreeNode getNode( + final BinaryTreeNodeType typeIn) { + switch (typeIn) { + case LEFT: return getLeft(); + case RIGHT: return getRight(); + default: + String msg = "Unsupported " + + BinaryTreeNode.class.getName() + type; + throw new CollectionException(msg); + } + } + /** + * + * @param node left node to add + */ + public void setLeft(final BinaryTreeNode node) { + setNode(BinaryTreeNodeType.LEFT, node); + } + /** + * + * @param node left node to add + */ + public void setRight(final BinaryTreeNode node) { + setNode(BinaryTreeNodeType.RIGHT, node); + } + /** + * @param typeIn node type + * @param nodeIn node to set + * @return + */ + public void setNode( + final BinaryTreeNodeType typeIn, + final BinaryTreeNode nodeIn) { + switch (typeIn) { + case LEFT: this.left = nodeIn; break; + case RIGHT: this.right = nodeIn; break; + default: + String msg = "Unsupported " + + BinaryTreeNode.class.getName() + type; + throw new CollectionException(msg); + } + nodeIn.setParent(this); + } + /** + * + * @return true, if this node has left node, otherwise false + */ + public boolean hasLeft() { + return hasNode(BinaryTreeNodeType.LEFT); + } + /** + * + * @return true, if this node has right node, otherwise false + */ + public boolean hasRight() { + return hasNode(BinaryTreeNodeType.RIGHT); + } + /** + * @param typeIn node type + * @return + */ + public boolean hasNode( + final BinaryTreeNodeType typeIn) { + BinaryTreeNode node = getNode(typeIn); + return node != null; + } + /** + * @param type node type + * @return true, if this node has right node, otherwise false + */ + public boolean has(final BinaryTreeNodeType type) { + return getRight() != null; + } + + +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/BinaryTreeNodeType.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/BinaryTreeNodeType.java new file mode 100644 index 0000000..9145f52 --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/BinaryTreeNodeType.java @@ -0,0 +1,46 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public enum BinaryTreeNodeType { + /** + * Undefined node. + */ + UNDEFINED, + /** + * Root node. + */ + ROOT, + /** + * Left node. + */ + LEFT, + /** + * Right node. + */ + RIGHT; +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/CollectionException.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/CollectionException.java new file mode 100644 index 0000000..08c3267 --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/CollectionException.java @@ -0,0 +1,43 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import org.nanoboot.powerframework.core.PowerException; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class CollectionException extends PowerException { + + /** + * Constructor + * + * @param messageIn message describing this exception + */ + public CollectionException(final String messageIn) { + super(messageIn); + } + +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/DoubleLinkedList.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/DoubleLinkedList.java new file mode 100644 index 0000000..f224fc4 --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/DoubleLinkedList.java @@ -0,0 +1,319 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.Setter; +import org.nanoboot.powerframework.collections.internal.AbstractLinkedList; + +import java.util.Iterator; +import java.util.NoSuchElementException; + +/** + * Represents double linked list data structure + * TODO !!! + * + * @param The type of the values stored in this list. + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class DoubleLinkedList extends AbstractLinkedList + implements Iterable { +//https://www.javatpoint.com/doubly-linked-list +//https://www.studytonight.com/data-structures/doubly-linked-list +//https://www.geeksforgeeks.org/doubly-linked-list/ +//https://www.tutorialspoint.com/data_structures_algorithms/doubly_linked_list_algorithm.htm + + /** + * The reference to the first node of this list. + */ + @Getter(AccessLevel.PRIVATE) + @Setter(AccessLevel.PRIVATE) + private DoubleLinkedListNode firstNode = null; + /** + * The reference to the last node of this list. + */ + @Getter(AccessLevel.PRIVATE) + @Setter(AccessLevel.PRIVATE) + private DoubleLinkedListNode lastNode = null; + + /** + * Iterator. + * + * @param Node type + */ + private class DoubleLinkedListIterator + implements Iterator { + /** + * Current node. + */ + @Getter(AccessLevel.PRIVATE) + private DoubleLinkedListNode currentNode; + + /** + * @param node start node + */ + DoubleLinkedListIterator(final DoubleLinkedListNode node) { + this.currentNode = new DoubleLinkedListNode<>(null); + this.currentNode.setNext(node); + } + + @Override + public boolean hasNext() { + return currentNode.hasNext(); + } + + @Override + public E next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + this.currentNode = currentNode.getNext(); + return this.getCurrentNode().getValue(); + } + } + + /** + * Iterator. Iterates from end to start. + * + * @param Node type + */ + private class ReversDoubleLinkedListIterator + implements Iterator { + /** + * Current node. + */ + @Getter(AccessLevel.PRIVATE) + private DoubleLinkedListNode currentNode; + + /** + * @param lastNodeIn end node + */ + ReversDoubleLinkedListIterator( + final DoubleLinkedListNode lastNodeIn) { + this.currentNode = new DoubleLinkedListNode<>(null); + this.currentNode.setPrevious(lastNodeIn); + } + + @Override + public boolean hasNext() { + return currentNode.hasPrevious(); + } + + @Override + public E next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + this.currentNode = currentNode.getPrevious(); + return this.getCurrentNode().getValue(); + } + } + + /** + * @return iterator for this list + */ + @Override + public Iterator iterator() { + return new DoubleLinkedListIterator(this.firstNode); + } + + /** + * @return reverse iterator for this list + */ + public Iterator reverseIterator() { + return new ReversDoubleLinkedListIterator(this.firstNode); + } + + /** + * Deletes all elements of this linked list. + */ + public void clear() { + clearSize(); + firstNode = null; + lastNode = null; + } + + /** + * {@inheritDoc} + */ + @Override + public E addBeforeFirst(final E elementIn) { + DoubleLinkedListNode oldFirstNode = getFirstNode(); + DoubleLinkedListNode newFirstNode = + new DoubleLinkedListNode<>(elementIn); + DoubleLinkedListNode.link(newFirstNode, oldFirstNode); + setFirstNode(newFirstNode); + this.incrementSize(); + return elementIn; + + } + + /** + * {@inheritDoc} + */ + @Override + public E addAfterLast(final E elementIn) { + DoubleLinkedListNode oldLastNode = getLastNode(); + DoubleLinkedListNode newLastNode = + new DoubleLinkedListNode<>(elementIn); + + setLastNode(newLastNode); + + if (isEmpty()) { + setFirstNode(getLastNode()); + } else { + DoubleLinkedListNode.link(oldLastNode, newLastNode); + } + + this.incrementSize(); + + return elementIn; + } + + /** + * {@inheritDoc} + */ + @Override + public E removeFirst() { + if (isEmpty()) { + throw new NoSuchElementException(); + } + DoubleLinkedListNode oldFirstNode = getFirstNode(); + DoubleLinkedListNode newFirstNode = oldFirstNode.getNext(); + E element = oldFirstNode.getValue(); + if (size() == 1) { + clear(); + return element; + } + setFirstNode(newFirstNode); + this.incrementSize(); + + if (this.size() == 1) { + setLastNode(getFirstNode()); + } + newFirstNode.unlinkPrevious(); + return element; + } + + /** + * {@inheritDoc} + */ + @Override + public E removeLast() { + if (isEmpty()) { + throw new NoSuchElementException(); + } + E element = getLastNode().getValue(); + + if (this.size() == 1) { + clear(); + return element; + } + DoubleLinkedListNode beforeLastNode = getLastNode().getPrevious(); + beforeLastNode.unlinkNext(); + setLastNode(beforeLastNode); + this.decrementSize(); + + + return element; + } + + /** + * {@inheritDoc} + */ + @Override + public E getFirst() { + if (isEmpty()) { + throw new NoSuchElementException(); + } + return firstNode.getValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public E getLast() { + if (isEmpty()) { + throw new NoSuchElementException(); + } + return lastNode.getValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public E remove(final int index) { + DoubleLinkedListNode node = getNodeByIndex(index); + if (node.equals(getFirstNode())) { + return removeFirst(); + } + if (node.equals(getLastNode())) { + return removeLast(); + } + DoubleLinkedListNode beforeNode = node.getPrevious(); + DoubleLinkedListNode.link(beforeNode, node.getNext()); + return node.getValue(); + } + + private DoubleLinkedListNode getNodeByIndex(final int indexIn) { + if (isEmpty()) { + throw new NoSuchElementException(); + } + if (indexIn > (size() - 1)) { + throw new CollectionException( + "Index " + indexIn + " is out of bounds."); + } + int index = 0; + DoubleLinkedListNode node = getFirstNode(); + while (node != null) { + if (index == indexIn) { + return node; + } + node = node.getNext(); + index++; + } + return null; + } + /** + * Returns the element at the specified position in this list. + * + * @param index starting from 1 + * + * @return value + */ + public E get(final int index) { + return getNodeByIndex(index).getValue(); + } + /** + * {@inheritDoc} + */ + @Override + public E set(final int index, final E element) { + getNodeByIndex(index).setValue(element); + return element; + } +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/DoubleLinkedListNode.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/DoubleLinkedListNode.java new file mode 100644 index 0000000..2b6c003 --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/DoubleLinkedListNode.java @@ -0,0 +1,166 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import lombok.Getter; +import lombok.Setter; +import org.nanoboot.powerframework.collections.internal.AbstractLinkedListNode; + +/** + * Represents one node of linked list. + * + * It is used to store a value based on the T. + * + * These nodes are linked (forward direction only). + * + * @param The type of the value this node holds + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class DoubleLinkedListNode extends AbstractLinkedListNode { + + /** + * Adds the reference for the node2 to the node1. The node1 will be + * connected to the node2 + * + * @param node1 The node, which field next will be set to node2. + * @param node2 The node, which will be set as the next node of the node1 + */ + static void link(final DoubleLinkedListNode node1, + final DoubleLinkedListNode node2) { + if (node1 != null) { + node1.setNext(node2); + } + if (node2 != null) { + node2.setPrevious(node1); + } + } + /** + * Reference for the previous node. + */ + @Getter + @Setter + private DoubleLinkedListNode previous = null; + + /** + * Reference for the next node. + */ + @Getter + @Setter + private DoubleLinkedListNode next = null; + + /** + * Constructor + * + * Used to create node without key (Key is empty String), used in linked + * list, which does not need keys. + * + * @param valueIn the appropriate field key will be set by this value + */ + DoubleLinkedListNode(final E valueIn) { + this.setValue(valueIn); + } + + /** + * @param type type of the node to get + * @return node by type + */ + public DoubleLinkedListNode getNodeByType( + final DoubleLinkedListNodeReferenceType type) { + if (type.isPrevious()) { + return previous; + } else { + return next; + } + } + + /** + * @param type type of the node to get + * @param node to set + */ + public void setNodeByType( + final DoubleLinkedListNodeReferenceType type, + final DoubleLinkedListNode node) { + if (type.isPrevious()) { + setPrevious(node); + } else { + setNext(node); + } + } + + /** + * Return true if this node has next node, otherwise false. + * + * @return boolean value + */ + boolean hasPrevious() { + return has(DoubleLinkedListNodeReferenceType.PREVIOUS); + } + + /** + * Return true if this node has next node, otherwise false. + * + * @return boolean value + */ + boolean hasNext() { + return has(DoubleLinkedListNodeReferenceType.NEXT); + } + /** + * Return true if this node has node with this type, otherwise false. + * @param type type of the node to get + * @return boolean value + */ + boolean has(final DoubleLinkedListNodeReferenceType type) { + DoubleLinkedListNode node = getNodeByType(type); + return node != null; + } + + /** + * Removes the reference of the next node from this node. + */ + void unlinkAll() { + unlinkPrevious(); + unlinkNext(); + } + + /** + * Removes the reference of the next node from this node. + */ + void unlinkPrevious() { + unlink(DoubleLinkedListNodeReferenceType.PREVIOUS); + } + + /** + * Removes the reference of the next node from this node. + */ + void unlinkNext() { + unlink(DoubleLinkedListNodeReferenceType.NEXT); + } + + /** + * Unlinks node. + * @param type type of the node to unlink + */ + void unlink(final DoubleLinkedListNodeReferenceType type) { + setNodeByType(type, null); + } +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/DoubleLinkedListNodeReferenceType.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/DoubleLinkedListNodeReferenceType.java new file mode 100644 index 0000000..69c841f --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/DoubleLinkedListNodeReferenceType.java @@ -0,0 +1,64 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public enum DoubleLinkedListNodeReferenceType { + /** + * Previous node. + */ + PREVIOUS, + /** + * Next node. + */ + NEXT; + + /** + * Checks the type. + * @return true, if it the previous type, otherwise false. + */ + public boolean isPrevious() { + return this == PREVIOUS; + } + /** + * Checks the type. + * @return true, if it the next type, otherwise false. + */ + public boolean isNext() { + return this == NEXT; + } + /** + * Returns the opposite reference. + * @return opposite reference + */ + public DoubleLinkedListNodeReferenceType opposite() { + if (this.isPrevious()) { + return NEXT; + } else { + return PREVIOUS; + } + } +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/KeyValue.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/KeyValue.java new file mode 100644 index 0000000..4b05f61 --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/KeyValue.java @@ -0,0 +1,71 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.nanoboot.powerframework.utils.StringUtils; + +import java.util.Map; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@AllArgsConstructor +public class KeyValue implements Map.Entry { + /** + * Key used to identify this node, if node with this key is wanted. + */ + @Getter + private String key = StringUtils.EMPTY_STRING; + /** + * The value this node is holding. + */ + @Getter + private V value; + /** + * Setter for key. + * @param k key + * @return the new key + */ + public String setKey(final String k) { + this.key = k; + return this.key; + } + /** + * {@inheritDoc} + */ + @Override + public V setValue(final V v) { + this.value = v; + return this.value; + } + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return key + "=" + value; + } +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/PowerCollection.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/PowerCollection.java new file mode 100644 index 0000000..d1bd11b --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/PowerCollection.java @@ -0,0 +1,215 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import org.nanoboot.powerframework.core.PowerObject; + +import java.util.Collection; +import java.util.Iterator; +import java.util.NoSuchElementException; + +/** + * Represents map data structure. Values of type T are mapped to String and + * searched by this String. + * + * @author Robert Vokac + * @since 0.0.0 + * @param the type of items, this map will store. + */ +public class PowerCollection extends PowerObject + implements Collection { + + /** + * Constructor. + *

+ * Constructor description + * + * @param items elements + */ + public PowerCollection(final E... items) { + for (E e : items) { + add(e); + } + } + /** + * List, where are stored items of this map. + */ + private final SingleLinkedList list = new SingleLinkedList<>(); + /** + * {@inheritDoc} + */ + @Override + public int size() { + return list.size(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isEmpty() { + return list.isEmpty(); + } + /** + * {@inheritDoc} + */ + @Override + public boolean contains(final Object o) { + return list.contains(o); + } + + private class CollectionIterator implements Iterator { + + /** + * Internal list. + */ + private final SingleLinkedList list; + /** + * Current index. + */ + private int currentIndex = 0; + + CollectionIterator(final SingleLinkedList listIn) { + this.list = listIn; + } + @Override + public boolean hasNext() { + return currentIndex < list.size(); + } + + @Override + public E next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + E result = list.get(currentIndex); + currentIndex++; + return result; + } + } + /** + * {@inheritDoc} + */ + @Override + public Iterator iterator() { + return new CollectionIterator(this.list); + } + /** + * {@inheritDoc} + */ + @Override + public Object[] toArray() { + return this.list.toArray(); + } + /** + * {@inheritDoc} + */ + @Override + public T[] toArray(final T[] ts) { + return (T[]) this.list.toArray(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean add(final E e) { + return this.list.add(e); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean remove(final Object o) { + return this.list.remove(o); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean containsAll(final Collection collection) { + for (Object e : collection) { + if (!contains(e)) { + return false; + } + } + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean addAll(final Collection collection) { + for (E e : collection) { + this.add(e); + } + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean removeAll(final Collection collection) { + for (Object e: collection) { + collection.remove(e); + } + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean retainAll(final Collection collection) { + throw new UnsupportedOperationException(); + } + + /** + * {@inheritDoc} + */ + @Override + public void clear() { + this.list.clear(); + } + + /** + * Returns internal list. + * @return internal list + */ + protected SingleLinkedList getInternalList() { + return list; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return list.toString(); + } + protected final boolean throwUnsupportedOperationException() { + throw new UnsupportedOperationException(); + } +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/PowerList.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/PowerList.java new file mode 100644 index 0000000..7e3ca9a --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/PowerList.java @@ -0,0 +1,193 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class PowerList extends PowerCollection implements List { + /** + * Linked list, where are stored items of this queue. + */ + private final SingleLinkedList list = getInternalList(); + /** + * Constructor. + * + * Constructs an empty list. + */ + public PowerList() { + } + + /** + * Constructor. + * + * Constructor description + * + * @param items elements + */ + public PowerList(final E... items) { + super(items); + } + /** + * {@inheritDoc} + */ + @Override + public boolean addAll( + final int i, final Collection collection) { + return throwUnsupportedOperationException(); + } + /** + * {@inheritDoc} + */ + @Override + public E get(final int i) { + return list.get(i); + } + /** + * {@inheritDoc} + */ + @Override + public E set(final int i, final E e) { + list.set(i, e); + return e; + } + /** + * {@inheritDoc} + */ + @Override + public void add(final int i, final E e) { + throwUnsupportedOperationException(); + } + /** + * {@inheritDoc} + */ + @Override + public E remove(final int i) { + return list.remove(i); + } + /** + * {@inheritDoc} + */ + @Override + public int indexOf(final Object o) { + throwUnsupportedOperationException(); + return 0; + } + /** + * {@inheritDoc} + */ + @Override + public int lastIndexOf(final Object o) { + throwUnsupportedOperationException(); + return 0; + } + + private class PowerListIterator implements ListIterator { + /** + * Internal iterator. + */ + private final Iterator iterator; + + PowerListIterator(final Iterator iteratorIn) { + this.iterator = iteratorIn; + } + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public E next() { + return iterator.next(); + } + + @Override + public boolean hasPrevious() { + throwUnsupportedOperationException(); + return true; + } + + @Override + public E previous() { + throwUnsupportedOperationException(); + return null; + } + + @Override + public int nextIndex() { + throwUnsupportedOperationException(); + return 0; + } + + @Override + public int previousIndex() { + throwUnsupportedOperationException(); + return 0; + } + + @Override + public void remove() { + throwUnsupportedOperationException(); + + } + + @Override + public void set(final E e) { + throwUnsupportedOperationException(); + + } + + @Override + public void add(final E e) { + + } + } + /** + * {@inheritDoc} + */ + @Override + public ListIterator listIterator() { + return new PowerListIterator<>(this.iterator()); + } + /** + * {@inheritDoc} + */ + @Override + public ListIterator listIterator(final int i) { + throwUnsupportedOperationException(); + return null; + } + /** + * {@inheritDoc} + */ + @Override + public List subList(final int i, final int i1) { + throwUnsupportedOperationException(); + return null; + } +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/PowerMap.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/PowerMap.java new file mode 100644 index 0000000..575d28e --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/PowerMap.java @@ -0,0 +1,266 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import org.nanoboot.powerframework.core.PowerObject; +import org.nanoboot.powerframework.core.exceptions.NotYetImplementedException; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Set; + +/** + * Represents map data structure. Values of type T are mapped to String and + * searched by this String. + * + * @author Robert Vokac + * @since 0.0.0 + * @param the type of items, this map will store. + */ +public class PowerMap extends PowerObject implements Map { + + /** + * List, where are stored items of this map. + */ + private final SingleLinkedList> list = new SingleLinkedList<>(); + + /** + * {@inheritDoc} + */ + @Override + public int size() { + return list.size(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isEmpty() { + return list.isEmpty(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean containsKey(final Object o) { + for (KeyValue e : list) { + if (e.getKey().equals(o)) { + return true; + } + } + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean containsValue(final Object o) { + for (KeyValue e : list) { + if (e.getValue().equals(o)) { + return true; + } + } + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public T get(final Object o) { + for (KeyValue e : list) { + if (e.getKey().equals(o)) { + return e.getValue(); + } + } + throw new NoSuchElementException("There is no key " + o); + } + + /** + * {@inheritDoc} + */ + @Override + public T put(final String s, final T t) { + this.list.add(new KeyValue(s, t)); + return t; + } + /** + * Puts and return this. + * @param s key + * @param t value + * @return this + */ + public PowerMap putAndReturn(final String s, final T t) { + put(s, t); + return this; + } + + /** + * {@inheritDoc} + */ + @Override + public T remove(final Object o) { + for (KeyValue e : list) { + if (e.getKey().equals(o)) { + this.list.remove(e); + return e.getValue(); + } + } + throw new NoSuchElementException(); + } + + /** + * {@inheritDoc} + */ + @Override + public void putAll(final Map map) { + for (Entry entry : map.entrySet()) { + String key = entry.getKey(); + T value = entry.getValue(); + put(key, value); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void clear() { + this.list.clear(); + } + + /** + * {@inheritDoc} + */ + @Override + public Set keySet() { + Set set = new HashSet(); + for (Entry entry : this.entrySet()) { + String key = entry.getKey(); + set.add(key); + } + return set; + } + + /** + * {@inheritDoc} + */ + public List keyList() { + List list2 = new PowerList<>(); + for (KeyValue e : list) { + String key = e.getKey(); + list2.add(key); + } + return list2; + } + /** + * {@inheritDoc} + */ + @Override + public Collection values() { + throw new NotYetImplementedException("Not implemented."); + } + + /** + * {@inheritDoc} + */ + @Override + public Set> entrySet() { + Set> set = new HashSet<>(); + Iterator> iterator = this.list.iterator(); + while (iterator.hasNext()) { + set.add(iterator.next()); + } + return set; + } +//// + /** + * Iterator. + * @return iterator + */ + public Iterator> iterator() { + return new MapIterator(this.list); + } + + private class MapIterator implements Iterator> { + + /** + * Internal list. + */ + private final SingleLinkedList> list; + /** + * Current index. + */ + private int currentIndex = 0; + + MapIterator(final SingleLinkedList> listIn) { + this.list = listIn; + } + @Override + public boolean hasNext() { + return currentIndex < list.size(); + } + + @Override + public KeyValue next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + KeyValue result = list.get(currentIndex); + currentIndex++; + return result; + } + } + + /** + * Updates the dictionary entry with the given key to the given value. + * + * @param keyIn key to search + * @param valueIn value mapped to key will be updated to the valueIn + * + * @return this map + */ + public T replace( + final String keyIn, + final T valueIn) { + this.remove(keyIn); + this.put(keyIn, valueIn); + return valueIn; + } + + @Override + public final String toString() { + StringBuilder sb = new StringBuilder(); + for (KeyValue e: this.list) { + sb.append(e.getKey()).append("=").append(e.getValue()).append("\n"); + } + String result = sb.toString(); + return result.substring(0, result.length() - 1); + } + +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/PowerQueue.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/PowerQueue.java new file mode 100644 index 0000000..6b44167 --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/PowerQueue.java @@ -0,0 +1,87 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; +import java.util.Queue; + +/** + * Represents Queue- linear data structure. + * + * @author Robert Vokac + * @since 0.0.0 + * @param object + */ +public class PowerQueue extends PowerCollection implements Queue { + + /** + * Linked list, where are stored items of this queue. + */ + private final SingleLinkedList list = getInternalList(); + /** + * {@inheritDoc} + */ + @Override + public boolean offer(final E e) { + return add(e); + } + + /** + * {@inheritDoc} + */ + @Override + public E remove() { + return list.removeFirst(); + } + + /** + * {@inheritDoc} + */ + @Override + public E poll() { + return list.removeFirst(); + } + + /** + * {@inheritDoc} + */ + @Override + public E element() { + return list.getFirst(); + } + + /** + * {@inheritDoc} + */ + @Override + public E peek() { + return list.getFirst(); + } + + /** + * Adds and returns. + * @param item element to add + * @return this + */ + public PowerQueue addAndReturn(final E item) { + add(item); + return this; + } + +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/PowerSet.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/PowerSet.java new file mode 100644 index 0000000..709f03d --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/PowerSet.java @@ -0,0 +1,144 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import org.nanoboot.powerframework.collections.arrays.ObjectArray; +import org.nanoboot.powerframework.random.generators.RandomGenerator; + +import java.util.Iterator; +import java.util.NoSuchElementException; +import java.util.Set; + +/** + * Here goes the description of this class. + *

+ * Set is unordered collection of values and contains no duplicates. + * + * @param element type + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class PowerSet extends PowerCollection implements Set { + /** + * Linked list, where are stored items of this queue. + */ + private final SingleLinkedList list = getInternalList(); + + /** + * Constructor. + *

+ * Constructor description + * + * @param items elements + */ + public PowerSet(final E... items) { + super(items); + } + + /** + * {@inheritDoc} + */ + public boolean add(final E item) { + if (contains(item)) { + String msg = "Can't add item " + item + + ". This object is already stored in this set."; + throw new CollectionException(msg); + } + return this.list.add(item); + } + + /** + * Returns random element of this Set. + * + * @return value + */ + public E getRandom() { + int index = RandomGenerator.getDefaultImplStatic() + .nextInt(1, list.size()); + return list.get(index); + } + + /** + * @return iterator for this list + */ + @Override + public Iterator iterator() { + return new SetIterator(list); + } + + /** + * Iterator implementation. + */ + private class SetIterator implements Iterator { + + /** + * Internal list. + */ + private final SingleLinkedList list; + /** + * Indexes. + */ + private final SingleLinkedList indexes; + + SetIterator(final SingleLinkedList listIn) { + this.list = listIn; + this.indexes = new SingleLinkedList<>(); + + for (int i = 0; i < list.size(); i++) { + indexes.add(i); + } + } + + @Override + public boolean hasNext() { + return !indexes.isEmpty(); + } + + @Override + public E next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + int randomArrayListIndexesListIndex = RandomGenerator + .getDefaultImplStatic().nextInt(0, indexes.size() - 1); + int randomIndex = indexes.get(randomArrayListIndexesListIndex); + E element = list.get(randomIndex); + indexes.remove(randomArrayListIndexesListIndex); + return element; + } + } + + /** + * Creates object array. + * + * @return object array + */ + public final ObjectArray toObjectArray() { + ObjectArray objectArray = new ObjectArray<>(this.size()); + int index = 1; + for (E element : this) { + objectArray.set(element, index++); + } + return objectArray; + } + +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/PowerStack.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/PowerStack.java new file mode 100644 index 0000000..1a62acb --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/PowerStack.java @@ -0,0 +1,68 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +/** + * Represents Stack- linear data structure. + * + * @author Robert Vokac + * @since 0.0.0 + * @param object + */ +public class PowerStack extends PowerCollection implements StackI { + + /** + * Linked list, where are stored items of this queue. + */ + private final SingleLinkedList list = getInternalList(); + /** + * {@inheritDoc} + */ + @Override + public E push(final E item) { + list.addBeforeFirst(item); + return item; + } + + /** + * Pushes and returns. + * @param item element to push + * @return this + */ + public PowerStack pushAndReturn(final E item) { + push(item); + return this; + } + /** + * {@inheritDoc} + */ + @Override + public E pop() { + return list.removeFirst(); + } + /** + * {@inheritDoc} + */ + @Override + public E peek() { + return list.getFirst(); + } +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/Properties.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/Properties.java new file mode 100644 index 0000000..5a178bd --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/Properties.java @@ -0,0 +1,132 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import lombok.Getter; +import org.nanoboot.powerframework.core.PowerObject; +import org.nanoboot.powerframework.utils.annotations.InProgress; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +@InProgress +public class Properties extends PowerObject { + /** + * Constant #. + */ + private static final String COMMENT_START_CHARACTER = "#"; + /** + * Constant =. + */ + private static final String EQUAL = "="; + /** + * Constant 0. + */ + private static final int PROPERTYPOSITION = 0; + /** + * Constant 1. + */ + private static final int VALUEPOSITION = 1; + /** + * Map mapping properties and their values. + */ + @Getter + private PowerMap map = new PowerMap<>(); + + /** + * @param propertiesFileTextIn input text + */ + public Properties(final String propertiesFileTextIn) { + String[] rows = propertiesFileTextIn.split("\\r?\\n"); + for (String row : rows) { + if (!row.isEmpty() && !row.startsWith(COMMENT_START_CHARACTER)) { + String[] array = getArrayFromRowIfPossible(row); + String property = array[PROPERTYPOSITION]; + + if (array.length == 2) { + String value = array[VALUEPOSITION]; + map.put(property, value); + } + } + } + } + + /** + * Split row by first "=" occurrence. + * + * @param rowIn row + * @return null, if there is no "=" + */ + private String[] getArrayFromRowIfPossible(final String rowIn) { + return rowIn.split(EQUAL, 2); + } + + /** + * @param propertyIn property + * @return + */ + public String getProperty(final String propertyIn) { + return map.get(propertyIn); + } + + /** + * @param propertyIn property + * @param valueIn value + */ + public void setProperty(final String propertyIn, + final String valueIn) { + map.replace(propertyIn, valueIn); + } + + /** + * @param propertyIn property + * @return true, if the property is present, otherwise false + */ + public boolean hasProperty(final String propertyIn) { + return map.containsKey(propertyIn); + } + /** + * {@inheritDoc} + */ + @Override + public String toString() { + if (this.getMap().isEmpty()) { + return ""; + } + StringBuilder sb = new StringBuilder(); + + String commaSpace = ", "; + for (String key : this.getMap().keySet()) { + sb + .append(key) + .append(EQUAL) + .append(this.getMap().get(key)) + .append(commaSpace); + } + String result = sb.toString(); + return result.substring(0, result.length() - commaSpace.length()); + } + + +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/SingleLinkedList.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/SingleLinkedList.java new file mode 100644 index 0000000..46bdef3 --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/SingleLinkedList.java @@ -0,0 +1,442 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import lombok.AccessLevel; +import lombok.Getter; +import lombok.Setter; +import org.nanoboot.powerframework.collections.internal.AbstractLinkedList; +import org.nanoboot.powerframework.core.exceptions.NotYetImplementedException; + +import java.util.Collection; +import java.util.Iterator; +import java.util.NoSuchElementException; +/** + * Represents linked list data structure. + * + * @param The type of the values stored in this list. + * @author Robert Vokac + * @since 0.0.0 + */ +public class SingleLinkedList extends AbstractLinkedList + implements Collection { + /** + * The reference to the first node of this list. + */ + @Getter(AccessLevel.PRIVATE) + @Setter(AccessLevel.PRIVATE) + private SingleLinkedListNode firstNode = null; + /** + * The reference to the last node of this list. + */ + @Getter(AccessLevel.PRIVATE) + @Setter(AccessLevel.PRIVATE) + private SingleLinkedListNode lastNode = null; + + /** + * Iterator. + * + * @param Node type + */ + private static class SingleLinkedListIterator + implements Iterator { + /** + * Current node. + */ + @Getter(AccessLevel.PRIVATE) + private SingleLinkedListNode currentNode; + + /** + * @param node start node + */ + SingleLinkedListIterator(final SingleLinkedListNode node) { + this.currentNode = new SingleLinkedListNode<>(null); + this.currentNode.setNext(node); + } + + @Override + public boolean hasNext() { + return currentNode.hasNext(); + } + + @Override + public T next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + this.currentNode = currentNode.getNext(); + return this.getCurrentNode().getValue(); + } + } + /** + * Constructor + * + * Constructs an empty list. + */ + public SingleLinkedList() { + } + + /** + * Constructor. + * + * Constructor description + * + * @param items elements + */ + public SingleLinkedList(final E... items) { + addAll(items); + } + //// + /** + * Setter for name. + * + * @param items elements + */ + public void addAll(final E... items) { + for (E element : items) { + add(element); + } + } + //// + + /** + * {@inheritDoc} + */ + @Override + public boolean contains(final Object o) { + for (E e : this) { + if (e.hashCode() == o.hashCode()) { + return true; + } + } + return false; + } + /** + * {@inheritDoc} + */ + @Override + public final Iterator iterator() { + return new SingleLinkedListIterator(this.getFirstNode()); + } + /** + * {@inheritDoc} + */ + @Override + public Object[] toArray() { + Object[] array = new Object[this.size()]; + int index = 0; + for (E e : this) { + array[index] = e; + index++; + } + return array; + } + /** + * {@inheritDoc} + */ + @Override + public T1[] toArray(final T1[] t1s) { + throw new NotYetImplementedException("No detail"); + } + /** + * {@inheritDoc} + */ + @Override + public boolean add(final E e) { + this.addAfterLast(e); + return true; + } + /** + * {@inheritDoc} + */ + @Override + public boolean remove(final Object o) { + int index = 0; + SingleLinkedListNode nodeToRemove; + SingleLinkedListNode beforeNode; + for (E e : this) { + if (e.hashCode() == o.hashCode()) { + remove(index); + return true; + } + index++; + } + return false; + } + /** + * {@inheritDoc} + */ + @Override + public boolean containsAll(final Collection collection) { + if (collection.isEmpty()) { + return true; + } + for (Object e :collection) { + if (!this.contains(e)) { + return false; + } + } + return true; + } + /** + * {@inheritDoc} + */ + @Override + public boolean addAll(final Collection collection) { + for (E e : collection) { + this.add(e); + } + return true; + } + /** + * {@inheritDoc} + */ + @Override + public boolean removeAll(final Collection collection) { + for (Object e : collection) { + remove(e); + } + return true; + } + /** + * {@inheritDoc} + */ + @Override + public boolean retainAll(final Collection collection) { + throw new NotYetImplementedException("No detail"); + } + /** + * Clears this list. + * All elements will be removed. + */ + public void clear() { + clearSize(); + firstNode = null; + lastNode = null; + } + //// + /** + * Adds new element before first element. + * + * @param elementIn element + * @return this linked list + */ + public E addBeforeFirst( + final E elementIn) { + SingleLinkedListNode oldRootNode = getFirstNode(); + SingleLinkedListNode newRootNode = + new SingleLinkedListNode<>(elementIn); + SingleLinkedListNode.link(newRootNode, oldRootNode); + setFirstNode(newRootNode); + this.incrementSize(); + if (this.size() == 1) { + setLastNode(getFirstNode()); + } + return elementIn; + } + /** + * Adds new element after last element. + * + * @param elementIn element + * @return this linked list + */ + public E addAfterLast(final E elementIn) { + + SingleLinkedListNode oldLastNode = getLastNode(); + SingleLinkedListNode newNode; + newNode = new SingleLinkedListNode<>(elementIn); + + if (isEmpty()) { + setFirstNode(newNode); + } else { + SingleLinkedListNode.link(oldLastNode, newNode); + } + setLastNode(newNode); + this.incrementSize(); + + return elementIn; + } + + /** + * Removes first element. + * + * @return removed element + */ + public E removeFirst() { + if (isEmpty()) { + throw new NoSuchElementException(); + } + + SingleLinkedListNode oldFirstNode = getFirstNode(); + SingleLinkedListNode newFirstNode = oldFirstNode.getNext(); + E element = oldFirstNode.getValue(); + if (size() == 1) { + clear(); + return element; + } + setFirstNode(newFirstNode); + this.decrementSize(); + + if (this.size() == 1) { + setLastNode(getFirstNode()); + } + return element; + } + + /** + * Removes last element. + * + * @return removed element + */ + public E removeLast() { + if (isEmpty()) { + throw new NoSuchElementException(); + } + E element = getLastNode().getValue(); + + if (this.size() == 1) { + clear(); + } else { + SingleLinkedListNode tempNode = getFirstNode(); + while (tempNode.getNext() != getLastNode()) { + tempNode = tempNode.getNext(); + } + SingleLinkedListNode beforeLastNode = tempNode; + beforeLastNode.unlinkNext(); + setLastNode(beforeLastNode); + this.decrementSize(); + } + + return element; + } + + /** + * @return first element + */ + public E getFirst() { + if (isEmpty()) { + throw new NoSuchElementException(); + } + return getFirstNode().getValue(); + } + + /** + * @return last element + */ + public E getLast() { + if (isEmpty()) { + throw new NoSuchElementException(); + } + return getLastNode().getValue(); + } + + /** + * Removes the element at the specified position in this list. + * + * @param index index param + * @return the removed element + */ + public E remove(final int index) { + SingleLinkedListNode node = getNodeByIndex(index); + if (node.equals(getFirstNode())) { + return removeFirst(); + } + if (node.equals(getLastNode())) { + return removeLast(); + } + SingleLinkedListNode beforeNode = getNodeByIndex(index - 1); + beforeNode.setNext(node.getNext()); + decrementSize(); + return node.getValue(); + } + + /** + * Returns the element at the specified position in this list. + * + * @param index starting from 0 + * + * @return value + */ + public E get(final int index) { + return getNodeByIndex(index).getValue(); + } + + private SingleLinkedListNode getNodeByIndex(final int indexIn) { + if (isEmpty()) { + throw new NoSuchElementException(); + } + if (indexIn > (size() - 1)) { + throw new CollectionException( + "Index " + indexIn + " is out of bounds."); + } + int index = 0; + SingleLinkedListNode node = getFirstNode(); + while (node != null) { + if (index == indexIn) { + return node; + } + node = node.getNext(); + index++; + } + return null; + } + + /** + * Replaces the element at the specified position + * in this list with the specified element. + * + * @param index index param + * @param element element param + * @return the new value + */ + public E set(final int index, final E element) { + SingleLinkedListNode node = getNodeByIndex(index); + E originalValue = node.getValue(); + node.setValue(element); + return originalValue; + } + @Override + public final String toString() { + String commaSpace = ", "; + return toString(commaSpace); + } + + /** + * Creates a String representation of this list using the delimiter. + * @param delimiter String delimiter + * @return string representation of the list + */ + public final String toString(final String delimiter) { + if (isEmpty()) { + return ""; + } + StringBuilder sb = new StringBuilder(); + for (E e : this) { + sb.append(e); + if (!delimiter.isEmpty()) { + sb.append(delimiter); + } + } + String result = sb.toString(); + result = result.substring(0, result.length() - delimiter.length()); + return result; + } +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/SingleLinkedListNode.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/SingleLinkedListNode.java new file mode 100644 index 0000000..da253cc --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/SingleLinkedListNode.java @@ -0,0 +1,86 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import lombok.Getter; +import lombok.Setter; +import org.nanoboot.powerframework.collections.internal.AbstractLinkedListNode; + +/** + * Represents one node of linked list. + * + * It is used to store a value based on the T. + * + * These nodes are linked (forward direction only). + * + * @author Robert Vokac + * @since 0.0.0 + * @param The type of the value this node holds + */ +class SingleLinkedListNode extends AbstractLinkedListNode { + /** + * Adds the reference for the node2 to the node1. The node1 will be + * connected to the node2 + * + * @param node1 The node, which field next will be set to node2. + * @param node2 The node, which will be set as the next node of the node1 + */ + static void link( + final SingleLinkedListNode node1, + final SingleLinkedListNode node2) { + node1.setNext(node2); + } + + /** + * Reference for the next node. + */ + @Getter + @Setter + private SingleLinkedListNode next = null; + + /** + * Constructor. + * + * Used to create node without key (Key is empty String), used in linked + * list, which does not need keys. + * + * @param valueIn the appropriate field key will be set by this value + */ + SingleLinkedListNode(final E valueIn) { + this.setValue(valueIn); + } + /** + * Return true if this node has next node, otherwise false. + * + * @return boolean value + */ + boolean hasNext() { + return getNext() != null; + } + + /** + * Removes the reference of the next node from this node. + */ + void unlinkNext() { + setNext(null); + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/collections/DictionaryNode.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/StackI.java similarity index 58% rename from src/main/java/org/nanoboot/powerframework/collections/DictionaryNode.java rename to power-collections/src/main/java/org/nanoboot/powerframework/collections/StackI.java index bdb4c73..74ef4ef 100644 --- a/src/main/java/org/nanoboot/powerframework/collections/DictionaryNode.java +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/StackI.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -19,45 +19,36 @@ /////////////////////////////////////////////////////////////////////////////////////////////// package org.nanoboot.powerframework.collections; - /** - * Represents one dictionary entry. + * * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ -class DictionaryNode { +public interface StackI { - private String key; - private T element; - private DictionaryNode next = null; + /** + * Pushes new element. + * @param item element to add + * @return element to add + */ + E push(E item); - DictionaryNode(String key, T element) { - this.key = key; - this.element = element; - } - - T getElement() { - return element; - } - - void setElement(T element) { - this.element = element; - } - - DictionaryNode getNext() { - return next; - } - - void setNext(DictionaryNode next) { - this.next = next; - } - - String getKey() { - return key; - } - - void setKey(String key) { - this.key = key; - } + /** + * Pops element. + * Remove first element. + * @return element to remove + */ + E pop(); + /** + * Returns the top element of this stack without removing this element. + * @return the top element of this stack without removing this element + */ + E peek(); + /** + * Checks, if the stack is empty. + * @return true, if this stack is empty, otherwise false + */ + boolean isEmpty(); } diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/Table.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/Table.java new file mode 100644 index 0000000..45de7bf --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/Table.java @@ -0,0 +1,62 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import lombok.Getter; +import lombok.Setter; +import org.nanoboot.powerframework.core.PowerObject; +import org.nanoboot.powerframework.utils.annotations.ToRemove; + +/** + * Here goes the description of this class. + * + * @author Robert Vokac + * @since 0.0.0 + * + */ +@ToRemove +public class Table extends PowerObject { + /** + * Name of the table. + */ + @Getter + @Setter + private String name; + /** + * Constructor. + * + * Not meant to be instantiated. + */ + private Table() { + } + + /** + * Constructor. + * + * Constructor description + * + * @param nameIn name + */ + public Table(final String nameIn) { + this.setName(nameIn); + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/pseudorandom/Seed.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/Tree.java similarity index 61% rename from src/main/java/org/nanoboot/powerframework/pseudorandom/Seed.java rename to power-collections/src/main/java/org/nanoboot/powerframework/collections/Tree.java index 14f6fe2..e7e611e 100644 --- a/src/main/java/org/nanoboot/powerframework/pseudorandom/Seed.java +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/Tree.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,31 +18,39 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.pseudorandom; +package org.nanoboot.powerframework.collections; + + +import lombok.Getter; /** - * Represents seed. Uses linear congruential function. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @param element type + * + * @author Robert Vokac + * @since 0.0.0 */ -class Seed { +public class Tree { + /** + * Root. + */ + @Getter + private final TreeNode root; - private long currentSeed; - private static final int A = 16807; - private static final int C = 0; - private static final long M = 2147483647; + /** + * Constructor. + */ + public Tree() { + root = new TreeNode<>(); + root.setName("root"); - Seed(long seed) { - this.currentSeed = seed; + } + /** + * Constructor. + * @param rootIn root node + */ + public Tree(final TreeNode rootIn) { + this.root = rootIn; } - long getNextNumber() { - long number = ((A * currentSeed) + C) % M; - this.currentSeed = number; - return number; - } - - void jump() { - getNextNumber(); - } } diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/TreeNode.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/TreeNode.java new file mode 100644 index 0000000..5e9289a --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/TreeNode.java @@ -0,0 +1,105 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import lombok.Getter; +import lombok.Setter; +import org.nanoboot.powerframework.collections.internal.AbstractTreeNode; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + * @param + */ +public final class TreeNode extends AbstractTreeNode { + /** + * Children nodes. + */ + @Getter + @Setter + private PowerList> children = new PowerList<>(); + /** + * + */ + private boolean ableToHaveChildren = true; + + /** + * + */ + public TreeNode() { + } + + /** + * + * @param valueIn the value + */ + public TreeNode(final T valueIn) { + this.setValue(valueIn); + } + + /** + * + * @param valueIn value + * @param childIn child + */ + public TreeNode(final T valueIn, final TreeNode childIn) { + this.setValue(valueIn); + addChild(childIn); + } + + /** + * @param valueIn value + * @param childrenIn children + */ + public TreeNode(final T valueIn, final TreeNode... childrenIn) { + this.setValue(valueIn); + addChildren(childrenIn); + } + + /** + * + * @param childIn child to add + */ + public void addChild(final TreeNode childIn) { + getChildren().add(childIn); + childIn.setParent(this); + } + + /** + * + * @param childrenIn children to add + */ + public void addChildren(final TreeNode... childrenIn) { + for (TreeNode element : childrenIn) { + addChild(element); + } + } + /** + * + * @return true, if this node has some children, otherwise false + */ + public boolean hasChildren() { + return !getChildren().isEmpty(); + } + +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/arrays/Array.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/arrays/Array.java new file mode 100644 index 0000000..be7fc52 --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/arrays/Array.java @@ -0,0 +1,1264 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections.arrays; + +//ObjectArray>>> array3=new ObjectArray>>>( + +import java.util.*; + +/** + * @param if the ArrayType is not Object, this parameter is ignored. In + * this case use Object as parameter. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class Array implements Iterable { + + private static final String SPACEDOT = " ."; + private static final String UNKNOWN_ARRAY_TYPE = "Unknown array type "; + private static final String THE_ARRAY_DIMENSION_COUNT_IS = "The array dimension count is "; + private static final String BUT_SHOULD_1_2_3_OR_4 = ", but should 1, 2, 3 or 4"; + private static final String DOT = "."; + + private static final int CONSTANT_ONE = 1; + + private ArrayType arrayType; + + private int dimensionCount; + private int[] arrayLengths; + + private boolean[] booleanArray1; + private byte[] byteArray1; + private short[] shortArray1; + private int[] intArray1; + private long[] longArray1; + private float[] floatArray1; + private double[] doubleArray1; + private C[] objectArray1; + + private boolean[][] booleanArray2; + private byte[][] byteArray2; + private short[][] shortArray2; + private int[][] intArray2; + private long[][] longArray2; + private float[][] floatArray2; + private double[][] doubleArray2; + private C[][] objectArray2; + + private boolean[][][] booleanArray3; + private byte[][][] byteArray3; + private short[][][] shortArray3; + private int[][][] intArray3; + private long[][][] longArray3; + private float[][][] floatArray3; + private double[][][] doubleArray3; + private C[][][] objectArray3; + + private boolean[][][][] booleanArray4; + private byte[][][][] byteArray4; + private short[][][][] shortArray4; + private int[][][][] intArray4; + private long[][][][] longArray4; + private float[][][][] floatArray4; + private double[][][][] doubleArray4; + private C[][][][] objectArray4; + + /** + * Constructor + *

+ * Creates array. + * + * @param arrayTypeIn the type of this array + * @param arrayLengthsIn 1 to 4, length of the arrays + */ + public Array(ArrayType arrayTypeIn, int... arrayLengthsIn) { + this.arrayLengths = arrayLengthsIn; + this.dimensionCount = arrayLengths.length; + + int array1Length = dimensionCount >= 1 ? this.arrayLengths[0] : 0; + int array2Length = dimensionCount >= 2 ? this.arrayLengths[1] : 0; + int array3Length = dimensionCount >= 3 ? this.arrayLengths[2] : 0; + int array4Length = dimensionCount == 4 ? this.arrayLengths[3] : 0; + + throwRuntimeExceptionIfDimensionOutOfRange(); + this.arrayType = arrayTypeIn; + initArray(array1Length, array2Length, array3Length, array4Length); + } + + /** + * Constructor + * Creates array dynamically based on the parameters and their count. + * + * @param values values of array + */ + public Array(boolean... values) { + initDynamicInitialization(values.length, ArrayType.BOOLEAN); + this.booleanArray1 = values; + } + + /** + * Constructor + * Creates array dynamically based on the parameters and their count. + * + * @param values values of array + */ + public Array(byte... values) { + initDynamicInitialization(values.length, ArrayType.BYTE); + this.byteArray1 = values; + } + + /** + * Constructor + * Creates array dynamically based on the parameters and their count. + * + * @param values values of array + */ + public Array(short... values) { + initDynamicInitialization(values.length, ArrayType.SHORT); + this.shortArray1 = values; + } + + /** + * Constructor + * Creates array dynamically based on the parameters and their count. + * + * @param values values of array + */ + public Array(int... values) { + initDynamicInitialization(values.length, ArrayType.INT); + this.intArray1 = values; + } + + /** + * Constructor + * Creates array dynamically based on the parameters and their count. + * + * @param values values of array + */ + public Array(long... values) { + initDynamicInitialization(values.length, ArrayType.LONG); + this.longArray1 = values; + } + + /** + * Constructor + * Creates array dynamically based on the parameters and their count. + * + * @param values values of array + */ + public Array(float... values) { + initDynamicInitialization(values.length, ArrayType.FLOAT); + this.floatArray1 = values; + } + + /** + * Constructor + * Creates array dynamically based on the parameters and their count. + * + * @param values values of array + */ + public Array(double... values) { + initDynamicInitialization(values.length, ArrayType.DOUBLE); + this.doubleArray1 = values; + } + + /** + * Constructor + * Creates array dynamically based on the parameters and their count. + * + * @param values values of array + */ + public Array(C... values) { + initDynamicInitialization(values.length, ArrayType.OBJECT); + this.objectArray1 = values; + } + + private void initArray(int array1LengthIn, int array2LengthIn, int array3LengthIn, int array4LengthIn) throws ArrayException { + switch (arrayType) { + case BOOLEAN: + initBooleanArray(array1LengthIn, array2LengthIn, array3LengthIn, array4LengthIn); + break; + case BYTE: + initByteArray(array1LengthIn, array2LengthIn, array3LengthIn, array4LengthIn); + break; + case SHORT: + initShortArray(array1LengthIn, array2LengthIn, array3LengthIn, array4LengthIn); + break; + case INT: + initIntArray(array1LengthIn, array2LengthIn, array3LengthIn, array4LengthIn); + break; + case LONG: + initLongArray(array1LengthIn, array2LengthIn, array3LengthIn, array4LengthIn); + break; + case FLOAT: + initFloatArray(array1LengthIn, array2LengthIn, array3LengthIn, array4LengthIn); + break; + case DOUBLE: + initDoubleArray(array1LengthIn, array2LengthIn, array3LengthIn, array4LengthIn); + break; + case OBJECT: + initObjectArray(array1LengthIn, array2LengthIn, array3LengthIn, array4LengthIn); + break; + default: + throw new ArrayException(UNKNOWN_ARRAY_TYPE + arrayType + + SPACEDOT); + } + } + + private void initBooleanArray(int array1Length, int array2Length, int array3Length, int array4Length) { + switch (dimensionCount) { + case 1: + booleanArray1 = new boolean[array1Length]; + return; + case 2: + booleanArray2 = new boolean[array1Length][array2Length]; + return; + case 3: + booleanArray3 = new boolean[array1Length][array2Length][array3Length]; + return; + case 4: + booleanArray4 = new boolean[array1Length][array2Length][array3Length][array4Length]; + return; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + } + } + + private void initByteArray(int array1Length, int array2Length, int array3Length, int array4Length) { + switch (dimensionCount) { + case 1: + byteArray1 = new byte[array1Length]; + return; + case 2: + byteArray2 = new byte[array1Length][array2Length]; + return; + case 3: + byteArray3 = new byte[array1Length][array2Length][array3Length]; + return; + case 4: + byteArray4 = new byte[array1Length][array2Length][array3Length][array4Length]; + return; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + } + } + + private void initShortArray(int array1Length, int array2Length, int array3Length, int array4Length) { + switch (dimensionCount) { + case 1: + shortArray1 = new short[array1Length]; + return; + case 2: + shortArray2 = new short[array1Length][array2Length]; + return; + case 3: + shortArray3 = new short[array1Length][array2Length][array3Length]; + return; + case 4: + shortArray4 = new short[array1Length][array2Length][array3Length][array4Length]; + return; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + } + } + + private void initIntArray(int array1Length, int array2Length, int array3Length, int array4Length) { + switch (dimensionCount) { + case 1: + intArray1 = new int[array1Length]; + return; + case 2: + intArray2 = new int[array1Length][array2Length]; + return; + case 3: + intArray3 = new int[array1Length][array2Length][array3Length]; + return; + case 4: + intArray4 = new int[array1Length][array2Length][array3Length][array4Length]; + return; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + + } + } + + private void initLongArray(int array1Length, int array2Length, int array3Length, int array4Length) { + switch (dimensionCount) { + case 1: + longArray1 = new long[array1Length]; + return; + case 2: + longArray2 = new long[array1Length][array2Length]; + return; + case 3: + longArray3 = new long[array1Length][array2Length][array3Length]; + return; + case 4: + longArray4 = new long[array1Length][array2Length][array3Length][array4Length]; + return; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + } + } + + private void initFloatArray(int array1Length, int array2Length, int array3Length, int array4Length) { + switch (dimensionCount) { + case 1: + floatArray1 = new float[array1Length]; + return; + case 2: + floatArray2 = new float[array1Length][array2Length]; + return; + case 3: + floatArray3 = new float[array1Length][array2Length][array3Length]; + return; + case 4: + floatArray4 = new float[array1Length][array2Length][array3Length][array4Length]; + return; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + } + } + + private void initDoubleArray(int array1Length, int array2Length, int array3Length, int array4Length) { + switch (dimensionCount) { + case 1: + doubleArray1 = new double[array1Length]; + return; + case 2: + doubleArray2 = new double[array1Length][array2Length]; + return; + case 3: + doubleArray3 = new double[array1Length][array2Length][array3Length]; + return; + case 4: + doubleArray4 = new double[array1Length][array2Length][array3Length][array4Length]; + return; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + } + } + + private void initObjectArray(int array1Length, int array2Length, int array3Length, int array4Length) { + switch (dimensionCount) { + case 1: + objectArray1 = (C[]) new Object[array1Length]; + return; + case 2: + objectArray2 = (C[][]) new Object[array1Length][array2Length]; + return; + case 3: + objectArray3 = (C[][][]) new Object[array1Length][array2Length][array3Length]; + return; + case 4: + objectArray4 = (C[][][][]) new Object[array1Length][array2Length][array3Length][array4Length]; + return; + + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + } + } + + private void initDynamicInitialization(int arrayLength, ArrayType arrayTypeIn) { + this.arrayLengths = new int[]{arrayLength}; + this.dimensionCount = 1; + this.arrayType = arrayTypeIn; + } + + private void throwRuntimeExceptionIfDimensionOutOfRange() { + if (dimensionCount < 0 || dimensionCount > 4) { + throw new ArrayException(THE_ARRAY_DIMENSION_COUNT_IS + + dimensionCount + BUT_SHOULD_1_2_3_OR_4 + DOT); + } + } + + /** + * @return + */ + public ArrayType getArrayType() { + return arrayType; + } + + public int getDimensions() { + return dimensionCount; + } + + /** + * Getter for array value. + * + * @param index index of the array + * @return array value + */ + public C getObject(int... index) { + initSettingOrGetting(index, ArrayType.OBJECT); + + switch (index.length) { + case 1: + return this.objectArray1[index[0]]; + case 2: + return this.objectArray2[index[0]][index[1]]; + case 3: + return this.objectArray3[index[0]][index[1]][index[2]]; + case 4: + return this.objectArray4[index[0]][index[1]][index[2]][index[3]]; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + //It should never come here. + return null; + } + } + + /** + * Setter for object. + * + * @param object object to set + * @param index index of the array + */ + public void setObject(C object, int... index) { + initSettingOrGetting(index, ArrayType.OBJECT); + switch (index.length) { + case 1: + this.objectArray1[index[0]] = object; + return; + case 2: + this.objectArray2[index[0]][index[1]] = object; + return; + case 3: + this.objectArray3[index[0]][index[1]][index[2]] = object; + return; + case 4: + this.objectArray4[index[0]][index[1]][index[2]][index[3]] = object; + return; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + } + } + + /** + * Getter for array value. + * + * @param index index of the array + * @return array value + */ + public boolean getBoolean(int... index) { + initSettingOrGetting(index, ArrayType.OBJECT); + switch (index.length) { + case 1: + return this.booleanArray1[index[0]]; + case 2: + return this.booleanArray2[index[0]][index[1]]; + case 3: + return this.booleanArray3[index[0]][index[1]][index[2]]; + case 4: + return this.booleanArray4[index[0]][index[1]][index[2]][index[3]]; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + //It should never come here. + return false; + } + } + + /** + * Setter for value. + * + * @param value value to set + * @param index index of the array + */ + public void setBoolean(boolean value, int... index) { + initSettingOrGetting(index, ArrayType.BOOLEAN); + switch (index.length) { + case 1: + this.booleanArray1[index[0]] = value; + return; + case 2: + this.booleanArray2[index[0]][index[1]] = value; + return; + case 3: + this.booleanArray3[index[0]][index[1]][index[2]] = value; + return; + case 4: + this.booleanArray4[index[0]][index[1]][index[2]][index[3]] = value; + return; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + } + } + + /** + * Getter for array value. + * + * @param index index of the array + * @return array value + */ + public byte getByte(int... index) { + initSettingOrGetting(index, ArrayType.BOOLEAN); + switch (index.length) { + case 1: + return this.byteArray1[index[0]]; + case 2: + return this.byteArray2[index[0]][index[1]]; + case 3: + return this.byteArray3[index[0]][index[1]][index[2]]; + case 4: + return this.byteArray4[index[0]][index[1]][index[2]][index[3]]; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + //It should never come here. + return 0; + } + } + + /** + * Setter for value. + * + * @param value value to set + * @param index index of the array + */ + public void setByte(byte value, int... index) { + initSettingOrGetting(index, ArrayType.BYTE); + switch (index.length) { + case 1: + this.byteArray1[index[0]] = value; + return; + case 2: + this.byteArray2[index[0]][index[1]] = value; + return; + case 3: + this.byteArray3[index[0]][index[1]][index[2]] = value; + return; + case 4: + this.byteArray4[index[0]][index[1]][index[2]][index[3]] = value; + return; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + } + } + + /** + * Getter for array value. + * + * @param index index of the array + * @return array value + */ + public short getShort(int... index) { + initSettingOrGetting(index, ArrayType.SHORT); + switch (index.length) { + case 1: + return this.shortArray1[index[0]]; + case 2: + return this.shortArray2[index[0]][index[1]]; + case 3: + return this.shortArray3[index[0]][index[1]][index[2]]; + case 4: + return this.shortArray4[index[0]][index[1]][index[2]][index[3]]; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + //It should never come here. + return 0; + } + } + + /** + * Setter for value. + * + * @param value value to set + * @param index index of the array + */ + public void setShort(short value, int... index) { + initSettingOrGetting(index, ArrayType.SHORT); + switch (index.length) { + case 1: + this.shortArray1[index[0]] = value; + return; + case 2: + this.shortArray2[index[0]][index[1]] = value; + return; + case 3: + this.shortArray3[index[0]][index[1]][index[2]] = value; + return; + case 4: + this.shortArray4[index[0]][index[1]][index[2]][index[3]] = value; + return; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + } + } + + /** + * Getter for array value. + * + * @param index index of the array + * @return array value + */ + public int getInt(int... index) { + initSettingOrGetting(index, ArrayType.INT); + switch (index.length) { + case 1: + return this.intArray1[index[0]]; + case 2: + return this.intArray2[index[0]][index[1]]; + case 3: + return this.intArray3[index[0]][index[1]][index[2]]; + case 4: + return this.intArray4[index[0]][index[1]][index[2]][index[3]]; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + //It should never come here. + return 0; + } + } + + /** + * Setter for value. + * + * @param value value to set + * @param index index of the array + */ + public void setInt(int value, int... index) { + initSettingOrGetting(index, ArrayType.INT); + switch (index.length) { + case 1: + this.intArray1[index[0]] = value; + return; + case 2: + this.intArray2[index[0]][index[1]] = value; + return; + case 3: + this.intArray3[index[0]][index[1]][index[2]] = value; + return; + case 4: + this.intArray4[index[0]][index[1]][index[2]][index[3]] = value; + return; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + } + } + + /** + * Getter for array value. + * + * @param index index of the array + * @return array value + */ + public long getLong(int... index) { + initSettingOrGetting(index, ArrayType.LONG); + switch (index.length) { + case 1: + return this.longArray1[index[0]]; + case 2: + return this.longArray2[index[0]][index[1]]; + case 3: + return this.longArray3[index[0]][index[1]][index[2]]; + case 4: + return this.longArray4[index[0]][index[1]][index[2]][index[3]]; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + //It should never come here. + return 0; + } + } + + /** + * Setter for value. + * + * @param value value to set + * @param index index of the array + */ + public void setLong(long value, int... index) { + initSettingOrGetting(index, ArrayType.LONG); + switch (index.length) { + case 1: + this.longArray1[index[0]] = value; + return; + case 2: + this.longArray2[index[0]][index[1]] = value; + return; + case 3: + this.longArray3[index[0]][index[1]][index[2]] = value; + return; + case 4: + this.longArray4[index[0]][index[1]][index[2]][index[3]] = value; + return; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + } + } + + /** + * Getter for array value. + * + * @param index index of the array + * @return array value + */ + public float getFloat(int... index) { + throwExceptionIfOperationIsUnsupported(ArrayType.FLOAT); + initSettingOrGetting(index, ArrayType.FLOAT); + switch (index.length) { + case 1: + return this.floatArray1[index[0]]; + case 2: + return this.floatArray2[index[0]][index[1]]; + case 3: + return this.floatArray3[index[0]][index[1]][index[2]]; + case 4: + return this.floatArray4[index[0]][index[1]][index[2]][index[3]]; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + //It should never come here. + return 0; + } + } + + /** + * Setter for value. + * + * @param value value to set + * @param index index of the array + */ + public void setFloat(float value, int... index) { + throwExceptionIfOperationIsUnsupported(ArrayType.FLOAT); + initSettingOrGetting(index, ArrayType.FLOAT); + switch (index.length) { + case 1: + this.floatArray1[index[0]] = value; + return; + case 2: + this.floatArray2[index[0]][index[1]] = value; + return; + case 3: + this.floatArray3[index[0]][index[1]][index[2]] = value; + return; + case 4: + this.floatArray4[index[0]][index[1]][index[2]][index[3]] = value; + return; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + } + } + + /** + * Getter for array value. + * + * @param index index of the array + * @return array value + */ + public double getDouble(int... index) { + initSettingOrGetting(index, ArrayType.DOUBLE); + switch (index.length) { + case 1: + return this.doubleArray1[index[0]]; + case 2: + return this.doubleArray2[index[0]][index[1]]; + case 3: + return this.doubleArray3[index[0]][index[1]][index[2]]; + case 4: + return this.doubleArray4[index[0]][index[1]][index[2]][index[3]]; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + //It should never come here. + return 0; + } + } + + /** + * Setter for value. + * + * @param value value to set + * @param index index of the array + */ + public void setDouble(double value, int... index) { + initSettingOrGetting(index, ArrayType.DOUBLE); + switch (index.length) { + case 1: + this.doubleArray1[index[0]] = value; + return; + case 2: + this.doubleArray2[index[0]][index[1]] = value; + return; + case 3: + this.doubleArray3[index[0]][index[1]][index[2]] = value; + return; + case 4: + this.doubleArray4[index[0]][index[1]][index[2]][index[3]] = value; + return; + default: + throwRuntimeExceptionIfDimensionOutOfRange(); + } + } + + private void initSettingOrGetting(int[] indexIn, ArrayType arrayTypeIn) { + throwExceptionIfOperationIsUnsupported(arrayTypeIn); + throwExceptionIfIndexOutOfRange(indexIn); + convertOkayToJavaIndexArray(indexIn); + } + + private void throwExceptionIfOperationIsUnsupported(ArrayType arrayTypeIn) { + if (arrayTypeIn != this.arrayType) { + throw new ArrayException("This operation is not supported for the array type " + this.arrayType + "."); + } + } + + /** + * @param arrayTypeIn + * @param dimensionCountIn + */ + private void throwExceptionIfOperationIsUnsupported(ArrayType arrayTypeIn, int dimensionCountIn) { + if (arrayTypeIn != this.arrayType) { + throw new ArrayException("This operation is not supported for the array type " + this.arrayType + "."); + } + if (dimensionCountIn != this.dimensionCount) { + throw new ArrayException("This operation is not supported for the dimension count " + dimensionCount + "."); + } + } + + private void throwExceptionIfIndexOutOfRange(int... index) { + int startIndex = CONSTANT_ONE; + int endIndex; + if (index.length != this.getDimensions()) { + throw new ArrayException("Wrong count of indexes. It should be " + this.getDimensions() + ", but is " + index.length + "."); + } + for (int i = 0; i < this.dimensionCount; i++) { + endIndex = this.arrayLengths[i]; + if ((index[i] > endIndex) || (index[i] < startIndex)) { + throw new ArrayException("Index " + index[i] + " is out of range <" + startIndex + ";" + endIndex + "> for dimension " + (i + 1)); + } + } + } + + private void convertOkayToJavaIndexArray(int... index) { + for (int i = 0; i < index.length; i++) { + index[i] = convertOkayToJavaIndex(index[i]); + } + } + + private int convertOkayToJavaIndex(int index) { + return (index - CONSTANT_ONE); + } + + /** + * @return + */ + public int getLength() { + return this.arrayLengths[0]; + } + + /** + * Getter for the length of the array based on the dimension number. + * + * @param dimension 1 or 2 or 3 or 4 + * @return array length of the dimension + */ + public int getLength(int dimension) { + return this.arrayLengths[dimension - 1]; + } + + public boolean[] getBooleanArray1() { + throwExceptionIfOperationIsUnsupported(ArrayType.BOOLEAN, 1); + return booleanArray1; + } + + public void setBooleanArray1(boolean[] booleanArray1) { + throwExceptionIfOperationIsUnsupported(ArrayType.BOOLEAN); + this.booleanArray1 = booleanArray1; + } + + public byte[] getByteArray1() { + throwExceptionIfOperationIsUnsupported(ArrayType.BYTE, 1); + return byteArray1; + } + + public void setByteArray1(byte[] byteArray1) { + throwExceptionIfOperationIsUnsupported(ArrayType.BYTE); + this.byteArray1 = byteArray1; + } + + public short[] getShortArray1() { + throwExceptionIfOperationIsUnsupported(ArrayType.SHORT, 1); + return shortArray1; + } + + public void setShortArray1(short[] shortArray1) { + throwExceptionIfOperationIsUnsupported(ArrayType.SHORT); + this.shortArray1 = shortArray1; + } + + public int[] getIntArray1() { + throwExceptionIfOperationIsUnsupported(ArrayType.INT, 1); + return intArray1; + } + + public void setIntArray1(int[] intArray1) { + throwExceptionIfOperationIsUnsupported(ArrayType.INT); + this.intArray1 = intArray1; + } + + public long[] getLongArray1() { + throwExceptionIfOperationIsUnsupported(ArrayType.LONG, 1); + return longArray1; + } + + public void setLongArray1(long[] longArray1) { + throwExceptionIfOperationIsUnsupported(ArrayType.LONG); + this.longArray1 = longArray1; + } + + public float[] getFloatArray1() { + throwExceptionIfOperationIsUnsupported(ArrayType.FLOAT, 1); + return floatArray1; + } + + public void setFloatArray1(float[] floatArray1) { + throwExceptionIfOperationIsUnsupported(ArrayType.FLOAT); + this.floatArray1 = floatArray1; + } + + public double[] getDoubleArray1() { + throwExceptionIfOperationIsUnsupported(ArrayType.DOUBLE, 1); + return doubleArray1; + } + + public void setDoubleArray1(double[] doubleArray1) { + throwExceptionIfOperationIsUnsupported(ArrayType.DOUBLE); + this.doubleArray1 = doubleArray1; + } + + public C[] getObjectArray1() { + throwExceptionIfOperationIsUnsupported(ArrayType.OBJECT, 1); + return objectArray1; + } + + public void setObjectArray1(C[] objectArray1) { + throwExceptionIfOperationIsUnsupported(ArrayType.OBJECT); + this.objectArray1 = objectArray1; + } + + public boolean[][] getBooleanArray2() { + throwExceptionIfOperationIsUnsupported(ArrayType.BOOLEAN, 2); + return booleanArray2; + } + + public void setBooleanArray2(boolean[][] booleanArray2) { + throwExceptionIfOperationIsUnsupported(ArrayType.BOOLEAN); + this.booleanArray2 = booleanArray2; + } + + public byte[][] getByteArray2() { + throwExceptionIfOperationIsUnsupported(ArrayType.BYTE, 2); + return byteArray2; + } + + public void setByteArray2(byte[][] byteArray2) { + throwExceptionIfOperationIsUnsupported(ArrayType.BYTE); + this.byteArray2 = byteArray2; + } + + public short[][] getShortArray2() { + throwExceptionIfOperationIsUnsupported(ArrayType.SHORT, 2); + return shortArray2; + } + + public void setShortArray2(short[][] shortArray2) { + throwExceptionIfOperationIsUnsupported(ArrayType.SHORT); + this.shortArray2 = shortArray2; + } + + public int[][] getIntArray2() { + throwExceptionIfOperationIsUnsupported(ArrayType.INT, 2); + return intArray2; + } + + public void setIntArray2(int[][] intArray2) { + throwExceptionIfOperationIsUnsupported(ArrayType.INT); + this.intArray2 = intArray2; + } + + public long[][] getLongArray2() { + throwExceptionIfOperationIsUnsupported(ArrayType.LONG, 2); + return longArray2; + } + + public void setLongArray2(long[][] longArray2) { + throwExceptionIfOperationIsUnsupported(ArrayType.LONG); + this.longArray2 = longArray2; + } + + public float[][] getFloatArray2() { + throwExceptionIfOperationIsUnsupported(ArrayType.FLOAT, 2); + return floatArray2; + } + + public void setFloatArray2(float[][] floatArray2) { + throwExceptionIfOperationIsUnsupported(ArrayType.FLOAT); + this.floatArray2 = floatArray2; + } + + public double[][] getDoubleArray2() { + throwExceptionIfOperationIsUnsupported(ArrayType.DOUBLE, 2); + return doubleArray2; + } + + public void setDoubleArray2(double[][] doubleArray2) { + throwExceptionIfOperationIsUnsupported(ArrayType.SHORT); + this.doubleArray2 = doubleArray2; + } + + public C[][] getObjectArray2() { + throwExceptionIfOperationIsUnsupported(ArrayType.OBJECT, 2); + return objectArray2; + } + + public void setObjectArray2(C[][] objectArray2) { + throwExceptionIfOperationIsUnsupported(ArrayType.OBJECT); + this.objectArray2 = objectArray2; + } + + public boolean[][][] getBooleanArray3() { + throwExceptionIfOperationIsUnsupported(ArrayType.BOOLEAN, 3); + return booleanArray3; + } + + public void setBooleanArray3(boolean[][][] booleanArray3) { + throwExceptionIfOperationIsUnsupported(ArrayType.BOOLEAN); + this.booleanArray3 = booleanArray3; + } + + public byte[][][] getByteArray3() { + throwExceptionIfOperationIsUnsupported(ArrayType.BYTE, 3); + return byteArray3; + } + + public void setByteArray3(byte[][][] byteArray3) { + throwExceptionIfOperationIsUnsupported(ArrayType.BYTE); + this.byteArray3 = byteArray3; + } + + public short[][][] getShortArray3() { + throwExceptionIfOperationIsUnsupported(ArrayType.SHORT, 3); + return shortArray3; + } + + public void setShortArray3(short[][][] shortArray3) { + throwExceptionIfOperationIsUnsupported(ArrayType.SHORT); + this.shortArray3 = shortArray3; + } + + public int[][][] getIntArray3() { + throwExceptionIfOperationIsUnsupported(ArrayType.INT, 3); + return intArray3; + } + + public void setIntArray3(int[][][] intArray3) { + throwExceptionIfOperationIsUnsupported(ArrayType.INT); + this.intArray3 = intArray3; + } + + public long[][][] getLongArray3() { + throwExceptionIfOperationIsUnsupported(ArrayType.LONG, 3); + return longArray3; + } + + public void setLongArray3(long[][][] longArray3) { + throwExceptionIfOperationIsUnsupported(ArrayType.LONG); + this.longArray3 = longArray3; + } + + public float[][][] getFloatArray3() { + throwExceptionIfOperationIsUnsupported(ArrayType.FLOAT, 3); + return floatArray3; + } + + public void setFloatArray3(float[][][] floatArray3) { + throwExceptionIfOperationIsUnsupported(ArrayType.FLOAT); + this.floatArray3 = floatArray3; + } + + public double[][][] getDoubleArray3() { + throwExceptionIfOperationIsUnsupported(ArrayType.DOUBLE, 3); + return doubleArray3; + } + + public void setDoubleArray3(double[][][] doubleArray3) { + throwExceptionIfOperationIsUnsupported(ArrayType.DOUBLE); + this.doubleArray3 = doubleArray3; + } + + public C[][][] getObjectArray3() { + throwExceptionIfOperationIsUnsupported(ArrayType.OBJECT, 4); + return objectArray3; + } + + public void setObjectArray3(C[][][] objectArray3) { + throwExceptionIfOperationIsUnsupported(ArrayType.OBJECT); + this.objectArray3 = objectArray3; + } + + public boolean[][][][] getBooleanArray4() { + throwExceptionIfOperationIsUnsupported(ArrayType.BOOLEAN, 4); + return booleanArray4; + } + + public void setBooleanArray4(boolean[][][][] booleanArray4) { + throwExceptionIfOperationIsUnsupported(ArrayType.BOOLEAN); + this.booleanArray4 = booleanArray4; + } + + public byte[][][][] getByteArray4() { + throwExceptionIfOperationIsUnsupported(ArrayType.BYTE, 4); + return byteArray4; + } + + public void setByteArray4(byte[][][][] byteArray4) { + throwExceptionIfOperationIsUnsupported(ArrayType.BYTE); + this.byteArray4 = byteArray4; + } + + public short[][][][] getShortArray4() { + throwExceptionIfOperationIsUnsupported(ArrayType.SHORT, 4); + return shortArray4; + } + + public void setShortArray4(short[][][][] shortArray4) { + throwExceptionIfOperationIsUnsupported(ArrayType.SHORT); + this.shortArray4 = shortArray4; + } + + public int[][][][] getIntArray4() { + throwExceptionIfOperationIsUnsupported(ArrayType.INT, 4); + return intArray4; + } + + public void setIntArray4(int[][][][] intArray4) { + throwExceptionIfOperationIsUnsupported(ArrayType.INT); + this.intArray4 = intArray4; + } + + public long[][][][] getLongArray4() { + throwExceptionIfOperationIsUnsupported(ArrayType.LONG, 4); + return longArray4; + } + + public void setLongArray4(long[][][][] longArray4) { + throwExceptionIfOperationIsUnsupported(ArrayType.LONG); + this.longArray4 = longArray4; + } + + public float[][][][] getFloatArray4() { + throwExceptionIfOperationIsUnsupported(ArrayType.FLOAT, 4); + return floatArray4; + } + + public void setFloatArray4(float[][][][] floatArray4) { + throwExceptionIfOperationIsUnsupported(ArrayType.FLOAT); + this.floatArray4 = floatArray4; + } + + public double[][][][] getDoubleArray4() { + throwExceptionIfOperationIsUnsupported(ArrayType.DOUBLE, 4); + return doubleArray4; + } + + public void setDoubleArray4(double[][][][] doubleArray4) { + throwExceptionIfOperationIsUnsupported(ArrayType.DOUBLE); + this.doubleArray4 = doubleArray4; + } + + public C[][][][] getObjectArray4() { + throwExceptionIfOperationIsUnsupported(ArrayType.OBJECT, 4); + return objectArray4; + } + + public void setObjectArray4(C[][][][] objectArray4) { + throwExceptionIfOperationIsUnsupported(ArrayType.OBJECT); + this.objectArray4 = objectArray4; + } + + // @Override +// public Iterator iterator(Array array) { +// +// Iterator iterator; +// switch (this.arrayType) { +// case BOOLEAN: +// return new BooleanArrayIterator(array); +//// case BYTE: +//// return ByteArrayIterator(); +// } +// } +// +// private class BooleanArrayIterator implements Iterator { +// +// private Array array; +// int i = 0; +// +// BooleanArrayIterator(Array arrayIn) { +// this.array = arrayIn; +// } +// +// @Override +// public boolean hasNext() { +// return (i + 1) <= array.getLength(); +// } +// +// public Boolean next() { +// if(!hasNext()) { +// throw new ArrayException("There is no next element."); +// } +// return array.getBoolean(++i); +// } +// } +// +// + @java.lang.Override + public Iterator iterator() { + if (this.dimensionCount != 1) { + throw new ArrayException("For iterating is only supported for one-dimensional arrays."); + } + return new BooleanArrayIterator(this); + } + + class BooleanArrayIterator implements Iterator { + + private Array array; + private int index = 0; + + public BooleanArrayIterator(Array arrayIn) { + this.array = arrayIn; + } + + @Override + public boolean hasNext() { + return (index + 1) <= array.getLength(); + } + + @Override + public Boolean next() { + throwExceptionIfNoNextElement(); + return array.getBoolean(++index); + } + + private void throwExceptionIfNoNextElement() throws ArrayException { + if (!hasNext()) { + throw new ArrayException("There is no next element."); + } + } + } + +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/arrays/ArrayException.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/arrays/ArrayException.java new file mode 100644 index 0000000..5e5067a --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/arrays/ArrayException.java @@ -0,0 +1,38 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections.arrays; + +import org.nanoboot.powerframework.collections.CollectionException; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class ArrayException extends CollectionException { + + public ArrayException(String message) { + super(message); + } + +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/arrays/ArrayType.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/arrays/ArrayType.java new file mode 100644 index 0000000..2d4d1ec --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/arrays/ArrayType.java @@ -0,0 +1,43 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections.arrays; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public enum ArrayType { +//TODO CHAR- char array + + BOOLEAN, + BYTE, + CHAR, + SHORT, + INT, + LONG, + FLOAT, + DOUBLE, + OBJECT; + +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/arrays/ByteArray.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/arrays/ByteArray.java new file mode 100644 index 0000000..f384c89 --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/arrays/ByteArray.java @@ -0,0 +1,67 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections.arrays; + +/** + * There will be the choice to select the starting index:0 will be default + * (maybe), but 1 or something else will be possible. + * + * @param + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class ByteArray { + + private Array array; + + public ByteArray(int... lengthIn) { + array = new Array(ArrayType.INT, lengthIn); + } + + public ByteArray(byte... values) { + array = new Array(values); + } + + public static ByteArray ofValues(byte... values) { + ByteArray intArray = new ByteArray(values.length); + intArray.array = new Array(values); + return intArray; + } + + public int get(int... index) { + return array.getInt(index); + } + + public void set(int value, + int... index) { + array.setInt(value, index); + } + + /** + * @param dimension 1 or 2 or 3 or 4 + * @return + */ + public int getLength(int dimension) { + return this.array.getLength(dimension); + } + +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/arrays/IntArray.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/arrays/IntArray.java new file mode 100644 index 0000000..7f85427 --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/arrays/IntArray.java @@ -0,0 +1,100 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections.arrays; + +import java.util.Iterator; + +/** + * There will be the choice to select the starting index:0 will be default + * (maybe), but 1 or something else will be possible. + * + * @param + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class IntArray implements Iterable { + + private Array array; + + public IntArray(int... lengthIn) { + array = new Array(ArrayType.INT, lengthIn); + } + + public static IntArray ofValues(int... values) { + IntArray intArray = new IntArray(values.length); + intArray.array = new Array(values); + return intArray; + } + + public int get(int... index) { + return array.getInt(index); + } + + public void set(int value, + int... index) { + array.setInt(value, index); + } + + /** + * @param dimension 1 or 2 or 3 or 4 + * @return + */ + public int getLength(int dimension) { + return this.array.getLength(dimension); + } + + @java.lang.Override + public Iterator iterator() { + if (array.getDimensions() != 1) { + throw new ArrayException("For iterating is only supported for one-dimensional arrays."); + } + return new IntArrayIterator(array); + } + + class IntArrayIterator implements Iterator { + + private Array array; + private int index = 0; + + public IntArrayIterator(Array arrayIn) { + this.array = arrayIn; + } + + @Override + public boolean hasNext() { + return (index + 1) <= array.getLength(); + } + + @Override + public Integer next() { + throwExceptionIfNoNextElement(); + return array.getInt(++index); + } + + private void throwExceptionIfNoNextElement() throws ArrayException { + if (!hasNext()) { + throw new ArrayException("There is no next element."); + } + } + } + +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/arrays/ObjectArray.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/arrays/ObjectArray.java new file mode 100644 index 0000000..6adf437 --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/arrays/ObjectArray.java @@ -0,0 +1,75 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections.arrays; + +/** + * There will be the choice to select the starting index:0 will be default + * (maybe), but 1 or something else will be possible. + * + * @author Robert Vokac + * @since 0.0.0 + * @param + */ +public class ObjectArray { + + private Array array; + + public ObjectArray(int... lengthIn) { + array = new Array(ArrayType.OBJECT, lengthIn); + } + + public static ObjectArray ofValues(C... values) { + ObjectArray objectArray = new ObjectArray<>(values.length); + int index = 1; + for (C element : values) { + objectArray.set(element, index++); + } + return objectArray; + + } +// public ObjectArray(C... values) { +// array = new Array(values); +// } + + public C get(int... index) { + return array.getObject(index); + } + + public void set(C value, + int... index) { + array.setObject(value, index); + } + + /** + * @param dimension 1 or 2 or 3 or 4 + * @return + */ + public int getLength(int dimension) { + return this.array.getLength(dimension); + } + + /** + * @return + */ + public int getLength() { + return this.array.getLength(); + } +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/arrays/package-info.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/arrays/package-info.java new file mode 100644 index 0000000..9578ec8 --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/arrays/package-info.java @@ -0,0 +1,27 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * Classes for arrays (index starting from 1, not 0). + * + * @author Robert Vokac + * @since 0.0.0 + */ +package org.nanoboot.powerframework.collections.arrays; diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/buffer/CharBuffer.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/buffer/CharBuffer.java new file mode 100644 index 0000000..f5ddd0f --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/buffer/CharBuffer.java @@ -0,0 +1,64 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections.buffer; + +/** + * Here goes the description of this class. + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class CharBuffer { + + public int size() { + return 0; + } + + public void putAtTheEnd(char ch) { + + } + + public void putAtTheEnd(CharBuffer charBuffer) { + + } +@Deprecated + public void putCurrentCharAtTheEnd(CharBuffer charBuffer) { + + } + + public char get() { + return ' '; + } + + public char get(int position) { + return ' '; + } + + public void move(int move) { + + } + + public String toString() { + return ""; + } + +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/graphs/.gitkeep b/power-collections/src/main/java/org/nanoboot/powerframework/collections/graphs/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/internal/AbstractLinkedList.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/internal/AbstractLinkedList.java new file mode 100644 index 0000000..5e43c76 --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/internal/AbstractLinkedList.java @@ -0,0 +1,171 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections.internal; + +import org.nanoboot.powerframework.collections.arrays.ObjectArray; + +/** + * Represents linked list data structure. + * @param element type + * + * @author Robert Vokac + * @since 0.0.0 + */ +public abstract class AbstractLinkedList implements Iterable { + /** + * Size of this list. + */ + private int size = 0; + + /** + * Returns size of this list. + * @return size of this list + */ + public final int size() { + return this.size; + } + /** + * Checks, if this list is empty. + * @return true, if this list is empty, otherwise false + */ + public boolean isEmpty() { + return this.size() == 0; + } + /** + * Deletes all elements of this linked list. + */ + public abstract void clear(); + /** + * Increments the size of this list by one. + */ + protected void incrementSize() { + ++size; + } + + /** + * Decrements the size of this list by one. + */ + protected void decrementSize() { + --size; + } + + /** + * Sets the size to 0. + */ + protected void clearSize() { + size = 0; + } + /** + * Adds new element before first element. + * + * @param elementIn element + * @return this linked list + */ + public abstract E addBeforeFirst(E elementIn); + + /** + * Adds new element after last element. + * + * @param elementIn element + * @return this linked list + */ + public abstract E addAfterLast(E elementIn); + /** + * Removes first element. + * + * @return removed element + */ + public abstract E removeFirst(); + + /** + * Removes last element. + * + * @return removed element + */ + public abstract E removeLast(); + /** + * @return first element + */ + public abstract E getFirst(); + + /** + * @return last element + */ + public abstract E getLast(); + + /** + * Removes the element at the specified position in this list. + * + * @param index index param + * @return the removed element + */ + public abstract E remove(int index); + + /** + * Returns the element at the specified position in this list. + * + * @param index starting from 1 + * + * @return value + */ + public abstract E get(int index); + + /** + * Replaces the element at the specified position + * in this list with the specified element. + * + * @param index index param + * @param element element param + * @return the new value + */ + public abstract E set(int index, E element); + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + StringBuilder stringBuilder = new StringBuilder(); + int index = 0; + int lastIndex = this.size() - 1; + for (E element : this) { + stringBuilder.append(element.toString()); + if (index < lastIndex) { + stringBuilder.append(", "); + } + ++index; + } + return stringBuilder.toString(); + } + /** + * Converts this list to an ObjectArray. + * @return ObjectArray + */ + public ObjectArray toObjectArray() { + ObjectArray objectArray = new ObjectArray<>(this.size()); + int index = 1; + for (E element : this) { + objectArray.set(element, index++); + } + return objectArray; + } + +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/internal/AbstractLinkedListNode.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/internal/AbstractLinkedListNode.java new file mode 100644 index 0000000..eaceffb --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/internal/AbstractLinkedListNode.java @@ -0,0 +1,45 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections.internal; + +import lombok.Getter; +import lombok.Setter; + +/** + * Represents one node of linked list. + * + * It is used to store a value based on the T. + * + * These nodes are linked (forward direction only). + * + * @param The type of the value this node holds + * + * @author Robert Vokac + * @since 0.0.0 + */ +public abstract class AbstractLinkedListNode { + /** + * Value. + */ + @Getter + @Setter + private E value; +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/internal/AbstractTreeNode.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/internal/AbstractTreeNode.java new file mode 100644 index 0000000..b725def --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/internal/AbstractTreeNode.java @@ -0,0 +1,53 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections.internal; + +import lombok.Getter; +import lombok.Setter; + +/** + * + * @param + * + * @author Robert Vokac + * @since 0.0.0 + */ +public abstract class AbstractTreeNode { + /** + * Parent node. + */ + @Getter + @Setter + private AbstractTreeNode parent = null; + /** + * The value to be hold. + */ + @Getter + @Setter + private T value; + /** + * Name of the node. + */ + @Getter + @Setter + private String name; + +} diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/internal/package-info.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/internal/package-info.java new file mode 100644 index 0000000..68e5a61 --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/internal/package-info.java @@ -0,0 +1,27 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * Internal classes. + * + * @author Robert Vokac + * @since 0.0.0 + */ +package org.nanoboot.powerframework.collections.internal; diff --git a/power-collections/src/main/java/org/nanoboot/powerframework/collections/package-info.java b/power-collections/src/main/java/org/nanoboot/powerframework/collections/package-info.java new file mode 100644 index 0000000..477d484 --- /dev/null +++ b/power-collections/src/main/java/org/nanoboot/powerframework/collections/package-info.java @@ -0,0 +1,27 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * Collections used to store instances of classes. + * + * @author Robert Vokac + * @since 0.0.0 + */ +package org.nanoboot.powerframework.collections; diff --git a/power-collections/src/main/resources/.gitkeep b/power-collections/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-collections/src/test/java/org/nanoboot/powerframework/collections/PowerMapTest.java b/power-collections/src/test/java/org/nanoboot/powerframework/collections/PowerMapTest.java new file mode 100644 index 0000000..3a9b9a8 --- /dev/null +++ b/power-collections/src/test/java/org/nanoboot/powerframework/collections/PowerMapTest.java @@ -0,0 +1,412 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import java.util.*; + +import static org.junit.Assert.*; + +import org.junit.*; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class PowerMapTest { + + /** + * + */ + public PowerMapTest() { + } + + /** + * Test of size method, of class map. + */ + @Test + public void testsize() { + //arrange + PowerMap map = new PowerMap<>(); + int expectedValue = 0; + int returnedValue; + //act + returnedValue = map.size(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of size method, of class map. + */ + @Test + public void testsize2() { + //arrange + PowerMap map = new PowerMap<>(); + int expectedValue = 0; + int returnedValue; + //act + map.put("name", "John"); + map.put("surname", "Black"); + map.remove("name"); + map.remove("surname"); + returnedValue = map.size(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of size method, of class map. + */ + @Test + public void testsize3() { + //arrange + PowerMap map = new PowerMap<>(); + int expectedValue = 2; + int returnedValue; + //act + map.put("name", "John"); + map.put("surname", "Black"); + map.put("nick", "Johny"); + map.remove("surname"); + returnedValue = map.size(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of size method, of class map. + */ + @Test + public void testsize4() { + //arrange + PowerMap map = new PowerMap<>(); + int expectedValue = 1; + int returnedValue; + //act + map.put("surname", "Black"); + returnedValue = map.size(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isEmpty method, of class map. + */ + @Test + public void testIsEmpty() { + //arrange + PowerMap map = new PowerMap<>(); + boolean returnedValue; + //act + returnedValue = map.isEmpty(); + //assert + assertTrue(returnedValue); + } + + /** + * Test of isEmpty method, of class map. + */ + @Test + public void testIsEmpty2() { + //arrange + PowerMap map = new PowerMap<>(); + boolean returnedValue; + //act + map.put("name", "John"); + map.put("surname", "Black"); + map.remove("name"); + map.remove("surname"); + returnedValue = map.isEmpty(); + //assert + assertTrue(returnedValue); + } + + /** + * Test of isEmpty method, of class map. + */ + @Test + public void testIsEmpty3() { + //arrange + PowerMap map = new PowerMap<>(); + boolean returnedValue; + //act + map.put("name", "John"); + map.put("surname", "Black"); + map.put("nick", "Johny"); + map.remove("surname"); + returnedValue = map.isEmpty(); + //assert + assertFalse(returnedValue); + } + + /** + * Test of getValue method, of class map. + */ + @Test + public void testIsEmpty4() { + //arrange + PowerMap map = new PowerMap<>(); + boolean returnedValue; + //act + map.put("name", "John"); + map.put("surname", "Black"); + map.put("nick", "Johny"); + map.remove("name"); + returnedValue = map.isEmpty(); + //assert + assertFalse(returnedValue); + } + + /** + * Test of containsKey method, of class map. + */ + @Test + public void containsKeyKey() { + //arrange + PowerMap map = new PowerMap<>(); + boolean expectedValue = true; + boolean returnedValue; + //act + map.put("name", "John"); + map.put("surname", "Black"); + map.put("nick", "Johny"); + returnedValue = map.containsKey("surname"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of containsKey method, of class map. + */ + @Test + public void containsKey2() { + //arrange + PowerMap map = new PowerMap<>(); + boolean expectedValue = false; + boolean returnedValue; + //act + map.put("name", "John"); + map.put("surname", "Black"); + map.put("nick", "Johny"); + returnedValue = map.containsKey("job"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of containsKey method, of class map. + */ + @Test + public void containsKey3() { + //arrange + PowerMap map = new PowerMap<>(); + boolean expectedValue = true; + boolean returnedValue; + //act + map.put("name", "John"); + returnedValue = map.containsKey("name"); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of add method, of class map. + */ + @Test + public void testPut() { + //arrange + PowerMap map = new PowerMap<>(); + String expectedString = "Johny"; + String returnedString; + //act + map.put("name", "John"); + map.put("surname", "Black"); + map.put("nick", "Johny"); + map.remove("surname"); + returnedString = map.get("nick"); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of add method, of class map. + */ + @Test + public void testPut2() { + //arrang + PowerMap map = new PowerMap<>(); + String expectedString = "Johny"; + String returnedString; + //act + map.put("name", "John"); + map.put("surname", "Black"); + map.put("nick", "Johny"); + map.remove("name"); + returnedString = map.get("nick"); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of add method, of class map. + */ + @Test + public void testPut3() { + //arrange + PowerMap map = new PowerMap<>(); + String expectedString = "Black"; + String returnedString; + //act + map.put("name", "John"); + map.put("surname", "Black"); + map.put("nick", "Johny"); + map.remove("nick"); + returnedString = map.get("surname"); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of getValue method, of class map. + */ + @Test + public void testGet() { + //arrange + PowerMap map = new PowerMap<>(); + String expectedString = "Black"; + String returnedString; + //act + map.put("name", "John"); + map.put("surname", "Black"); + map.put("nick", "Johny"); + map.remove("name"); + returnedString = map.get("surname"); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of getValue method, of class map. + */ + @Test + public void testGet2() { + //arrange + PowerMap map = new PowerMap<>(); + String expectedString = "Johny"; + String returnedString; + //act + map.put("nick", "Johny"); + returnedString = map.get("nick"); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of updateValue method, of class map. + */ + @Test + public void testReplaceValue() { + //arrange + PowerMap map = new PowerMap<>(); + String expectedString = "Blue"; + String returnedString; + //act + map.put("name", "John"); + map.put("surname", "Black"); + map.put("nick", "Johny"); + map.replace("surname", "Blue"); + returnedString = map.get("surname"); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of remove method, of class map. + */ + @Test + public void testRemove() { + //arrange + boolean isExceptionThrown = false; + PowerMap map = new PowerMap<>(); + String expectedString = "Black"; + String returnedString; + map.put("name", "John"); + map.put("surname", "Black"); + map.put("nick", "Johny"); + map.remove("surname"); + //act + try { + returnedString = map.get("surname"); + } catch (NoSuchElementException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown NoSuchElementException"); + } + } + + /** + * Test of getKeyIterator method, of class map. + */ + @Test + public void testIterator() { + //arrange + PowerMap map = new PowerMap<>(); + Iterator> mapIterator; + String expectedString = "Johny"; + String returnedString; + String secondKey; + map.put("name", "John"); + map.put("surname", "Black"); + map.put("nick", "Johny"); + map.remove("surname"); + mapIterator = map.iterator(); + //act + mapIterator.next(); + secondKey = mapIterator.next().getKey(); + returnedString = map.get(secondKey); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of toString method, of class map. + */ + @Test + public void testToString() { + //arrange + PowerMap map = new PowerMap<>(); + String expectedString = "name=John\nsurname=Black\nnick=Johny"; + String returnedString; + //act + map.put("name", "John"); + map.put("surname", "Black"); + map.put("nick", "Johny"); + returnedString = map.toString(); + //assert + assertEquals(expectedString, returnedString); + } + +} diff --git a/power-collections/src/test/java/org/nanoboot/powerframework/collections/PropertiesTest.java b/power-collections/src/test/java/org/nanoboot/powerframework/collections/PropertiesTest.java new file mode 100644 index 0000000..e8f7201 --- /dev/null +++ b/power-collections/src/test/java/org/nanoboot/powerframework/collections/PropertiesTest.java @@ -0,0 +1,120 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import static org.junit.Assert.*; +import org.junit.*; + +import java.util.NoSuchElementException; + +import static org.junit.Assert.assertEquals; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class PropertiesTest { + private Properties properties; + + @Before + public void setup() { + properties=new Properties(PROPERTIES_FILE_TEXT_IN); + } + public static final String PROPERTIES_FILE_TEXT_IN = "#Fri Jan 17 22:37:45 MYT 2014\n" + + "dbpassword=password\n" + + "database=localhost\n" + + "dbuser=mkyong"; + @Test + public void getProperty() { + //prepare + //execute + //assert + assertEquals(properties.getProperty("dbpassword"), "password"); + assertEquals(properties.getProperty("database"), "localhost"); + assertEquals(properties.getProperty("dbuser"), "mkyong"); + try { + properties.getProperty("abc"); + throw new AssertionError("NoSuchElementException expected, but not thrown."); + } catch (NoSuchElementException e) { + + } + } + + @Test + public void setProperty() { + //prepare + //execute + properties.setProperty("dbpassword", "newPassword"); + //assert + assertEquals(properties.getProperty("dbpassword"), "newPassword"); + assertEquals(properties.getProperty("database"), "localhost"); + assertEquals(properties.getProperty("dbuser"), "mkyong"); + try { + properties.getProperty("abc"); + throw new AssertionError("NoSuchElementException expected, but not thrown."); + } catch (NoSuchElementException e) { + + } + + } + + @Test + public void hasProperty() { + + //prepare + //execute + properties.setProperty("dbpassword", "newPassword"); + //assert + assertTrue(properties.hasProperty("dbpassword")); + assertTrue(properties.hasProperty("database")); + assertTrue(properties.hasProperty("dbuser")); + try { + properties.getProperty("abc"); + throw new AssertionError("NoSuchElementException expected, but not thrown."); + } catch (NoSuchElementException e) { + + } + } + + @Test + public void testToString() { + //prepare + String returned; + //execute + returned = properties.toString(); + //assert + assertTrue(returned.contains("dbpassword=password")); + assertTrue(returned.contains("database=localhost")); + assertTrue(returned.contains("dbuser=mkyong")); + assertTrue(returned.contains(", ")); + } + + @Test + public void getMap() { + PowerMap map = properties.getMap(); + assertNotNull(map); + assertTrue(map.containsKey("dbpassword")); + assertTrue(map.containsKey("database")); + assertTrue(map.containsKey("dbuser")); + } +} diff --git a/src/test/java/org/nanoboot/powerframework/collections/QueueTest.java b/power-collections/src/test/java/org/nanoboot/powerframework/collections/QueueTest.java similarity index 54% rename from src/test/java/org/nanoboot/powerframework/collections/QueueTest.java rename to power-collections/src/test/java/org/nanoboot/powerframework/collections/QueueTest.java index c9ab36c..6f45e23 100644 --- a/src/test/java/org/nanoboot/powerframework/collections/QueueTest.java +++ b/power-collections/src/test/java/org/nanoboot/powerframework/collections/QueueTest.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -20,14 +20,19 @@ package org.nanoboot.powerframework.collections; -import org.nanoboot.powerframework.PowerRuntimeException; -import org.junit.Test; +import java.util.*; + import static org.junit.Assert.*; +import org.junit.*; + /** + * * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ + public class QueueTest { /** @@ -37,102 +42,102 @@ public class QueueTest { } /** - * Test of getCountOfItems method, of class Queue. + * Test of size method, of class Queue. */ @Test - public void testGetCountOfItems() { + public void testsize() { //arrange - Queue queue = new Queue<>(); + PowerQueue queue = new PowerQueue<>(); int expectedCountOfItems = 0; int returnedCountOfItems; //act - returnedCountOfItems = queue.getCountOfItems(); + returnedCountOfItems = queue.size(); //assert assertEquals(expectedCountOfItems, returnedCountOfItems); } /** - * Test of getCountOfItems method, of class Queue. + * Test of size method, of class Queue. */ @Test - public void testGetCountOfItems2() { + public void testsize2() { //arrange - Queue queue = new Queue<>(); + PowerQueue queue = new PowerQueue<>(); int expectedCountOfItems = 0; int returnedCountOfItems; //act - queue.enqueue("John"); - queue.dequeue(); - returnedCountOfItems = queue.getCountOfItems(); + queue.add("John"); + queue.poll(); + returnedCountOfItems = queue.size(); //assert assertEquals(expectedCountOfItems, returnedCountOfItems); } /** - * Test of getCountOfItems method, of class Queue. + * Test of size method, of class Queue. */ @Test - public void testGetCountOfItems3() { + public void testsize3() { //arrange - Queue queue = new Queue<>(); + PowerQueue queue = new PowerQueue<>(); int expectedCountOfItems = 0; int returnedCountOfItems; //act - queue.enqueue("John"); - queue.dequeue(); - queue.enqueue("Jack").enqueue("Anne").enqueue("Charlie"); + queue.add("John"); + queue.poll(); + queue.addAndReturn("Jack").addAndReturn("Anne").addAndReturn("Charlie"); - queue.dequeue(); - queue.dequeue(); - queue.dequeue(); - queue.enqueue("Jane"); - queue.dequeue(); - returnedCountOfItems = queue.getCountOfItems(); + queue.poll(); + queue.poll(); + queue.poll(); + queue.add("Jane"); + queue.poll(); + returnedCountOfItems = queue.size(); //assert assertEquals(expectedCountOfItems, returnedCountOfItems); } /** - * Test of getCountOfItems method, of class Queue. + * Test of size method, of class Queue. */ @Test - public void testGetCountOfItems4() { + public void testsize4() { //arrange - Queue queue = new Queue<>(); + PowerQueue queue = new PowerQueue<>(); int expectedCountOfItems = 1; int returnedCountOfItems; //act - queue.enqueue("John"); - queue.dequeue(); - queue.enqueue("Jack").enqueue("Anne").enqueue("Charlie"); + queue.add("John"); + queue.poll(); + queue.addAndReturn("Jack").addAndReturn("Anne").addAndReturn("Charlie"); - queue.dequeue(); - queue.dequeue(); - queue.enqueue("Jane"); - queue.dequeue(); - returnedCountOfItems = queue.getCountOfItems(); + queue.poll(); + queue.poll(); + queue.add("Jane"); + queue.poll(); + returnedCountOfItems = queue.size(); //assert assertEquals(expectedCountOfItems, returnedCountOfItems); } /** - * Test of getCountOfItems method, of class Queue. + * Test of size method, of class Queue. */ @Test - public void testGetCountOfItems5() { + public void testsize5() { //arrange - Queue queue = new Queue<>(); + PowerQueue queue = new PowerQueue<>(); int expectedCountOfItems = 3; int returnedCountOfItems; //act - queue.enqueue("John"); - queue.dequeue(); - queue.enqueue("Jack").enqueue("Anne").enqueue("Charlie").enqueue("Susan"); + queue.add("John"); + queue.poll(); + queue.addAndReturn("Jack").addAndReturn("Anne").addAndReturn("Charlie").addAndReturn("Susan"); - queue.dequeue(); - queue.enqueue("Jane"); - queue.dequeue(); - returnedCountOfItems = queue.getCountOfItems(); + queue.poll(); + queue.add("Jane"); + queue.poll(); + returnedCountOfItems = queue.size(); //assert assertEquals(expectedCountOfItems, returnedCountOfItems); } @@ -143,7 +148,7 @@ public class QueueTest { @Test public void testIsEmpty() { //arrange - Queue queue = new Queue<>(); + PowerQueue queue = new PowerQueue<>(); boolean expectedValue = true; boolean returnedValue; //act @@ -158,19 +163,19 @@ public class QueueTest { @Test public void testIsEmpty2() { //arrange - Queue queue = new Queue<>(); + PowerQueue queue = new PowerQueue<>(); boolean expectedValue = true; boolean returnedValue; //act - queue.enqueue("John").enqueue("Jack").enqueue("Anne").enqueue("Charlie"); + queue.addAndReturn("John").addAndReturn("Jack").addAndReturn("Anne").addAndReturn("Charlie"); - queue.dequeue(); - queue.dequeue(); - queue.dequeue(); - queue.dequeue(); + queue.poll(); + queue.poll(); + queue.poll(); + queue.poll(); - queue.enqueue("Jane"); - queue.dequeue(); + queue.add("Jane"); + queue.poll(); returnedValue = queue.isEmpty(); //assert assertEquals(expectedValue, returnedValue); @@ -182,18 +187,18 @@ public class QueueTest { @Test public void testIsEmpty3() { //arrange - Queue queue = new Queue<>(); + PowerQueue queue = new PowerQueue<>(); boolean expectedValue = false; boolean returnedValue; //act - queue.enqueue("John").enqueue("Jack").enqueue("Anne").enqueue("Charlie"); + queue.addAndReturn("John").addAndReturn("Jack").addAndReturn("Anne").addAndReturn("Charlie"); - queue.dequeue(); - queue.dequeue(); - queue.dequeue(); + queue.poll(); + queue.poll(); + queue.poll(); - queue.enqueue("Jane"); - queue.dequeue(); + queue.add("Jane"); + queue.poll(); returnedValue = queue.isEmpty(); //assert assertEquals(expectedValue, returnedValue); @@ -205,17 +210,17 @@ public class QueueTest { @Test public void testIsEmpty4() { //arrange - Queue queue = new Queue<>(); + PowerQueue queue = new PowerQueue<>(); boolean expectedValue = false; boolean returnedValue; //act - queue.enqueue("John").enqueue("Jack").enqueue("Anne").enqueue("Charlie"); + queue.addAndReturn("John").addAndReturn("Jack").addAndReturn("Anne").addAndReturn("Charlie"); - queue.dequeue(); - queue.dequeue(); + queue.poll(); + queue.poll(); - queue.enqueue("Jane"); - queue.dequeue(); + queue.add("Jane"); + queue.poll(); returnedValue = queue.isEmpty(); //assert assertEquals(expectedValue, returnedValue); @@ -227,12 +232,12 @@ public class QueueTest { @Test public void testEnqueue() { //arrange - Queue queue = new Queue<>(); + PowerQueue queue = new PowerQueue<>(); String expectedString = "John"; String returnedString; //act - queue.enqueue("John"); - returnedString = queue.dequeue(); + queue.add("John"); + returnedString = queue.poll(); //assert assertEquals(expectedString, returnedString); } @@ -243,12 +248,12 @@ public class QueueTest { @Test public void testDequeue() { //arrange - Queue queue = new Queue<>(); + PowerQueue queue = new PowerQueue<>(); String expectedString = "Alice"; String returnedString; //act - queue.enqueue("Alice").enqueue("Jane"); - returnedString = queue.dequeue(); + queue.addAndReturn("Alice").addAndReturn("Jane"); + returnedString = queue.poll(); //assert assertEquals(expectedString, returnedString); } @@ -257,33 +262,50 @@ public class QueueTest { * Test of dequeue method, of class Queue. */ @Test - public void testDequeue_ThereShouldBeThrownPowerRuntimeException() { + public void testDequeue_ThereShouldBeThrownOkayRuntimeException() { //arrange boolean isExceptionThrown = false; - Queue queue = new Queue<>(); + PowerQueue queue = new PowerQueue<>(); //act try { - queue.dequeue(); - } catch (PowerRuntimeException e) { + queue.poll(); + } catch (NoSuchElementException e) { isExceptionThrown = true; } //assert if (!isExceptionThrown) { - fail("There should be thrown PowerRuntimeException"); + fail("There should be thrown OkayRuntimeException"); } } + /** + * Test of peek method, of class Stack. + */ + @Test + public void testClear() { + //arrange + PowerQueue queue = new PowerQueue<>(); + boolean returnedValue; + //act + queue.addAndReturn("John").addAndReturn("Jack").addAndReturn("Anne").addAndReturn("Charlie").addAndReturn("Alice").addAndReturn("Dennis"); + + queue.clear(); + returnedValue = queue.isEmpty(); + //assert + assertTrue(returnedValue); + } + /** * Test of toString method, of class Queue. */ @Test public void testToString() { //arrange - Queue queue = new Queue<>(); - String expectedString = "Alice, Jane, "; + PowerQueue queue = new PowerQueue<>(); + String expectedString = "Alice, Jane"; String returnedString; //act - queue.enqueue("Alice").enqueue("Jane"); + queue.addAndReturn("Alice").addAndReturn("Jane"); returnedString = queue.toString(); //assert assertEquals(expectedString, returnedString); diff --git a/power-collections/src/test/java/org/nanoboot/powerframework/collections/SingleLinkedListNodeTest.java b/power-collections/src/test/java/org/nanoboot/powerframework/collections/SingleLinkedListNodeTest.java new file mode 100644 index 0000000..d2765ec --- /dev/null +++ b/power-collections/src/test/java/org/nanoboot/powerframework/collections/SingleLinkedListNodeTest.java @@ -0,0 +1,164 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import static org.junit.Assert.*; + +import org.junit.*; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class SingleLinkedListNodeTest { + + /** + * Test of link method, of class Node. + */ + @Test + public void link() { + //arrange + SingleLinkedListNode node1 = new SingleLinkedListNode<>("John"); + SingleLinkedListNode node2 = new SingleLinkedListNode<>("Black"); + String expectedString = "Black"; + String returnedString; + //act + SingleLinkedListNode.link(node1, node2); + SingleLinkedListNode returned = node1.getNext(); + returnedString = returned.getValue(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of getValue method, of class Node. + */ + @Test + public void getValue() { + //arrange + SingleLinkedListNode node = new SingleLinkedListNode<>("John"); + String expectedString = "John"; + String returnedString; + //act + returnedString = node.getValue(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of setValue method, of class Node. + */ + @Test + public void setValue() { + //arrange + SingleLinkedListNode node = new SingleLinkedListNode<>("John"); + String expectedString = "Jack"; + String returnedString; + //act + node.setValue("Jack"); + returnedString = node.getValue(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of getNext method, of class Node. + */ + @Test + public void getNext() { + //arrange + SingleLinkedListNode node1 = new SingleLinkedListNode<>("John"); + SingleLinkedListNode node2 = new SingleLinkedListNode<>("Black"); + String expectedString = "Black"; + String returnedString; + //act + node1.setNext(node2); + SingleLinkedListNode returnedmapNode = node1.getNext(); + returnedString = returnedmapNode.getValue(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of setNext method, of class Node. + */ + @Test + public void setNext() { + //arrange + SingleLinkedListNode node1 = new SingleLinkedListNode<>("John"); + SingleLinkedListNode node2 = new SingleLinkedListNode<>("White"); + String expectedString = "White"; + String returnedString; + //act + node1.setNext(node2); + SingleLinkedListNode returned = node1.getNext(); + returnedString = returned.getValue(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of hasNext method, of class Node. + */ + @Test + public void hasNext() { + //arrange + SingleLinkedListNode node1 = new SingleLinkedListNode<>("John"); + //act + + //assert + assertFalse(node1.hasNext()); + } + + /** + * Test of hasNext method, of class Node. + */ + @Test + public void hasNext2() { + //arrange + SingleLinkedListNode node1 = new SingleLinkedListNode<>("John"); + SingleLinkedListNode node2 = new SingleLinkedListNode<>("White"); + //act + node1.setNext(node2); + //assert + assertTrue(node1.hasNext()); + } + + /** + * Test of unlinkNext method, of class Node. + */ + @Test + public void unlinkNext() { + //arrange + SingleLinkedListNode node1 = new SingleLinkedListNode<>("John"); + SingleLinkedListNode node2 = new SingleLinkedListNode<>("White"); + //act + assertFalse(node1.hasNext()); + node1.setNext(node2); + assertTrue(node1.hasNext()); + node1.unlinkNext(); + //assert + assertFalse(node1.hasNext()); + } + +} diff --git a/power-collections/src/test/java/org/nanoboot/powerframework/collections/SingleLinkedListTest.java b/power-collections/src/test/java/org/nanoboot/powerframework/collections/SingleLinkedListTest.java new file mode 100644 index 0000000..ed59308 --- /dev/null +++ b/power-collections/src/test/java/org/nanoboot/powerframework/collections/SingleLinkedListTest.java @@ -0,0 +1,782 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.collections; + +import java.util.*; + +import static org.junit.Assert.*; + +import org.nanoboot.powerframework.core.exceptions.NotYetImplementedException; +import org.junit.*; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class SingleLinkedListTest { + @Test + public void addAll_EVarArg() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + + //act + linkedList + .addAll("a", "b", "c", "d", "e"); + //assert + assertEquals(5, linkedList.size()); + assertEquals("a, b, c, d, e", linkedList.toString()); + assertEquals("a", linkedList.get(0)); + assertEquals("b", linkedList.get(1)); + assertEquals("c", linkedList.get(2)); + assertEquals("d", linkedList.get(3)); + assertEquals("e", linkedList.get(4)); + } + + @Test + public void contains() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + + //act + linkedList + .addAll("a", "b", "c", "d", "e"); + //assert + assertTrue(linkedList.contains("a")); + assertTrue(linkedList.contains("b")); + assertTrue(linkedList.contains("c")); + assertTrue(linkedList.contains("d")); + assertTrue(linkedList.contains("e")); + assertFalse(linkedList.contains("f")); + } + + @Test + public void iterator() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + StringBuilder sb = new StringBuilder(); + String expected = "12345"; + String returned; + for (int i = 1; i <= 5; i++) { + linkedList.add(String.valueOf(i)); + } + //act + for (String e : linkedList) { + sb.append(e); + } + returned = sb.toString(); + //assert + assertEquals(expected, returned); + } + + @Test + public void toArray_ObjectArray() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + StringBuilder sb = new StringBuilder(); + String expected = "12345"; + String returned; + Object[] array; + for (int i = 1; i <= 5; i++) { + linkedList.add(String.valueOf(i)); + } + //act + array = linkedList.toArray(); + for (Object o : array) { + sb.append(o); + } + returned = sb.toString(); + //assert + assertEquals(5, array.length); + assertEquals(expected, returned); + } + + @Test(expected = NotYetImplementedException.class) + public void toArray_genericArray() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + + for (int i = 1; i <= 5; i++) { + linkedList.add(String.valueOf(i)); + } + //act + linkedList.toArray(new Object[]{}); + //assert + } + + @Test + public void add() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + //act + //assert + linkedList.add("a"); + assertEquals(1, linkedList.size()); + assertEquals("a", linkedList.toString()); + linkedList.add("b"); + assertEquals(2, linkedList.size()); + assertEquals("a, b", linkedList.toString()); + linkedList.add("c"); + assertEquals(3, linkedList.size()); + assertEquals("a, b, c", linkedList.toString()); + } + + @Test + public void remove_Object() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + //act + linkedList.add("a"); + linkedList.add("b"); + linkedList.add("c"); + //assert + //abc + assertEquals(3, linkedList.size()); + linkedList.remove("b"); + //ac + assertEquals(2, linkedList.size()); + assertFalse(linkedList.contains("b")); + linkedList.add("d"); + //acd + assertEquals(3, linkedList.size()); + assertTrue(linkedList.contains("d")); + linkedList.remove("a"); + //cd + assertEquals(2, linkedList.size()); + assertFalse(linkedList.contains("a")); + linkedList.remove("d"); + //c + assertEquals(1, linkedList.size()); + assertFalse(linkedList.contains("d")); + assertTrue(linkedList.contains("c")); + linkedList.remove("c"); + assertEquals(0, linkedList.size()); + assertFalse(linkedList.contains("c")); + // + assertEquals("", linkedList.toString()); + } + + @Test + public void containsAll() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + //act + linkedList.add("a"); + linkedList.add("b"); + linkedList.add("c"); + //assert + assertTrue(linkedList.containsAll(new SingleLinkedList<>("a", "b", "c"))); + assertTrue(linkedList.containsAll(new SingleLinkedList<>("b", "c"))); + assertTrue(linkedList.containsAll(new SingleLinkedList<>("a", "c"))); + assertTrue(linkedList.containsAll(new SingleLinkedList<>("a", "b"))); + assertTrue(linkedList.containsAll(new SingleLinkedList<>("a"))); + assertTrue(linkedList.containsAll(new SingleLinkedList<>("b"))); + assertTrue(linkedList.containsAll(new SingleLinkedList<>("c"))); + assertFalse(linkedList.containsAll(new SingleLinkedList<>("a", "b", "c", "d"))); + assertFalse(linkedList.containsAll(new SingleLinkedList<>("b", "c", "d"))); + assertFalse(linkedList.containsAll(new SingleLinkedList<>("a", "c", "d"))); + assertFalse(linkedList.containsAll(new SingleLinkedList<>("a", "b", "d"))); + assertFalse(linkedList.containsAll(new SingleLinkedList<>("a", "d"))); + assertFalse(linkedList.containsAll(new SingleLinkedList<>("b", "d"))); + assertFalse(linkedList.containsAll(new SingleLinkedList<>("c", "d"))); + assertTrue(linkedList.containsAll(new SingleLinkedList<>())); + } + + @Test + public void testAddAll_collection() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + //act + linkedList.addAll(new SingleLinkedList<>("a", "b", "c")); + //assert + assertEquals(3, linkedList.size()); + assertEquals("a, b, c", linkedList.toString()); + } + + @Test + public void removeAll() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + //act + linkedList.addAll(new SingleLinkedList<>("a", "b", "c")); + linkedList.removeAll(new SingleLinkedList<>("a", "c")); + //assert + assertEquals(1, linkedList.size()); + assertEquals("b", linkedList.toString()); + linkedList.removeAll(new SingleLinkedList<>("b")); + assertEquals(0, linkedList.size()); + assertEquals("", linkedList.toString()); + } + + @Test(expected = NotYetImplementedException.class) + public void retainAll() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + //act + linkedList.addAll(new SingleLinkedList<>("a", "b", "c")); + linkedList.retainAll(new SingleLinkedList<>("a", "c")); + //assert + } + + @Test + public void clear() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + //act + linkedList.addAll(new SingleLinkedList<>("a", "b", "c")); + //assert + assertEquals(3, linkedList.size()); + linkedList.clear(); + assertEquals(0, linkedList.size()); + assertEquals("", linkedList.toString()); + linkedList.add("d"); + assertEquals(1, linkedList.size()); + assertEquals("d", linkedList.toString()); + linkedList.add("e"); + assertEquals(2, linkedList.size()); + assertEquals("d, e", linkedList.toString()); + linkedList.clear(); + assertEquals(0, linkedList.size()); + assertEquals("", linkedList.toString()); + } + + // + @Test + public void addBeforeFirst() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + + //act + + //assert + linkedList.addBeforeFirst("a"); + assertEquals(1, linkedList.size()); + assertEquals("a", linkedList.toString()); + linkedList.addBeforeFirst("b"); + assertEquals(2, linkedList.size()); + assertEquals("b, a", linkedList.toString()); + linkedList.addBeforeFirst("c"); + assertEquals(3, linkedList.size()); + assertEquals("c, b, a", linkedList.toString()); + } + + @Test + public void addAfterLast() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + + //act + + //assert + linkedList.addAfterLast("a"); + assertEquals(1, linkedList.size()); + assertEquals("a", linkedList.toString()); + linkedList.addAfterLast("b"); + assertEquals(2, linkedList.size()); + assertEquals("a, b", linkedList.toString()); + linkedList.addAfterLast("c"); + assertEquals(3, linkedList.size()); + assertEquals("a, b, c", linkedList.toString()); + } + + @Test + public void removeFirst() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + String expectedString = "AnneJohnGeorgeKate"; + String returnedString; + linkedList.addAfterLast("Jack") + ; + linkedList.addAfterLast("Anne") + ; + linkedList.addAfterLast("John") + ; + linkedList.addAfterLast("George") + ; + linkedList.addAfterLast("Kate"); + //act + linkedList.removeFirst(); + StringBuilder stringBuilder = new StringBuilder(); + for (String element : linkedList) { + stringBuilder.append(element); + } + returnedString = stringBuilder.toString(); + //assert + assertEquals(expectedString, returnedString); + linkedList.removeFirst(); + assertEquals(3, linkedList.size()); + assertEquals("John, George, Kate", linkedList.toString()); + } + + @Test + public void removeLast() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + String expectedString = "JackAnneJohnGeorge"; + String returnedString; + linkedList.addAfterLast("Jack") + ; + linkedList.addAfterLast("Anne") + ; + linkedList.addAfterLast("John") + ; + linkedList.addAfterLast("George") + ; + linkedList.addAfterLast("Kate"); + //act + linkedList.removeLast(); + StringBuilder stringBuilder = new StringBuilder(); + for (String element : linkedList) { + stringBuilder.append(element); + } + returnedString = stringBuilder.toString(); + //assert + assertEquals(expectedString, returnedString); + linkedList.removeLast(); + + assertEquals(3, linkedList.size()); + assertEquals("Jack, Anne, John", linkedList.toString()); + } + + @Test + public void getFirst() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + String expectedString = "Jack"; + String returnedString; + linkedList.addAfterLast("Jack"); + linkedList.addAfterLast("Anne"); + linkedList.addAfterLast("John"); + linkedList.addAfterLast("George"); + linkedList.addAfterLast("Kate"); + //act + returnedString = linkedList.getFirst(); + //assert + assertEquals(expectedString, returnedString); + linkedList.removeFirst(); + assertEquals("Anne", linkedList.getFirst()); + assertEquals("Anne, John, George, Kate", linkedList.toString()); + } + + @Test + public void getLast() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + String expectedString = "George"; + String returnedString; + linkedList.addAfterLast("Jack"); + linkedList.addAfterLast("Anne"); + linkedList.addAfterLast("John"); + linkedList.addAfterLast("George"); + linkedList.addAfterLast("Kate"); + //act + linkedList.addAfterLast("Mike"); + linkedList.addBeforeFirst("William"); + linkedList.removeFirst(); + linkedList.removeLast(); + linkedList.removeFirst(); + linkedList.addAfterLast("Earl"); + linkedList.removeLast(); + linkedList.removeFirst(); + linkedList.removeLast(); + + returnedString = linkedList.getLast(); + //assert + assertEquals(expectedString, returnedString); + } + + @Test + public void remove_int() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + //act + //assert + linkedList.add("a"); + linkedList.add("b"); + linkedList.add("c"); + //abc + assertEquals(3, linkedList.size()); + linkedList.remove(1); + assertEquals("a, c", linkedList.toString()); + //ac + assertEquals(2, linkedList.size()); + assertFalse(linkedList.contains("b")); + linkedList.add("d"); + assertEquals("a, c, d", linkedList.toString()); + //acd + assertEquals(3, linkedList.size()); + assertTrue(linkedList.contains("d")); + linkedList.remove(0); + //cd + assertEquals(2, linkedList.size()); + assertFalse(linkedList.contains("a")); + linkedList.remove(1); + //c + assertEquals(1, linkedList.size()); + assertFalse(linkedList.contains("d")); + assertTrue(linkedList.contains("c")); + linkedList.remove(0); + assertEquals(0, linkedList.size()); + assertFalse(linkedList.contains("c")); + // + assertEquals("", linkedList.toString()); + } + + @Test + public void get() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.addAfterLast("Jack"); + linkedList.addAfterLast("Anne"); + linkedList.addAfterLast("John"); + linkedList.addAfterLast("George"); + linkedList.addAfterLast("Kate"); + //act + + //assert + assertEquals("Jack", linkedList.get(0)); + assertEquals("Anne", linkedList.get(1)); + assertEquals("John", linkedList.get(2)); + assertEquals("George", linkedList.get(3)); + assertEquals("Kate", linkedList.get(4)); + } + + @Test(expected = NoSuchElementException.class) + public void get2() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + //act + + //assert + assertEquals("Jack", linkedList.get(0)); + + } + + @Test(expected = CollectionException.class) + public void get3() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.addAfterLast("Jack"); + linkedList.addAfterLast("Anne"); + linkedList.addAfterLast("John"); + linkedList.addAfterLast("Kate"); + //act + linkedList.get(4); + //assert + } + + @Test + public void set() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.addAfterLast("a"); + linkedList.addAfterLast("b"); + linkedList.addAfterLast("c"); + linkedList.addAfterLast("d"); + linkedList.addAfterLast("e"); + //act + + //assert + assertEquals("abcde", linkedList.toString("")); + linkedList.set(2, "f"); + assertEquals("abfde", linkedList.toString("")); + linkedList.set(3, "g"); + assertEquals("abfge", linkedList.toString("")); + linkedList.set(0, "h"); + assertEquals("hbfge", linkedList.toString("")); + linkedList.set(3, "i"); + assertEquals("hbfie", linkedList.toString("")); + linkedList.set(1, "j"); + assertEquals("hjfie", linkedList.toString("")); + } + + /** + * Test of toString method, of class LinkedList. + */ + @Test + public void testToString() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + String expectedString = "Jack, Anne, John, George, Kate"; + String returnedString; + linkedList.addAfterLast("Jack"); + linkedList.addAfterLast("Anne"); + linkedList.addAfterLast("John"); + linkedList.addAfterLast("George"); + linkedList.addAfterLast("Kate"); + //act + returnedString = linkedList.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + /** + * Test of toString method, of class LinkedList. + */ + @Test + public void testToString_2() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + String expectedString = ""; + String returnedString; + //act + returnedString = linkedList.toString(); + //assert + assertEquals(expectedString, returnedString); + } + + ////// + + /** + * Test of getsize method, of class LinkedList. + */ + @Test + public void size_justCreatedInstanceShouldHaveCountZero() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + int expectedCountOfItems = 0; + int returnedCountOfItems; + //act + returnedCountOfItems = linkedList.size(); + //assert + assertEquals(expectedCountOfItems, returnedCountOfItems); + } + + /** + * Test of getsize method, of class LinkedList. + */ + @Test + public void size_shouldHaveCountFive() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + int expectedCountOfItems = 5; + int returnedCountOfItems; + + linkedList.addAfterLast("Jack"); + linkedList.addAfterLast("Anne"); + linkedList.addAfterLast("John"); + linkedList.addAfterLast("George"); + linkedList.addAfterLast("Kate"); + //act + returnedCountOfItems = linkedList.size(); + //assert + assertEquals(expectedCountOfItems, returnedCountOfItems); + } + + /** + * Test of getsize method, of class LinkedList. + */ + @Test + public void size_shouldHaveCountFourAfterFirstRemoved() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + int expectedCountOfItems = 4; + int returnedCountOfItems; + + linkedList.addAfterLast("Jack"); + linkedList.addAfterLast("Anne"); + linkedList.addAfterLast("John"); + linkedList.addAfterLast("George"); + linkedList.addAfterLast("Kate"); + //act + linkedList.removeFirst(); + returnedCountOfItems = linkedList.size(); + //assert + assertEquals(expectedCountOfItems, returnedCountOfItems); + } + + /** + * Test of getsize method, of class LinkedList. + */ + @Test + public void size_shouldHaveCountThreeAfterTwoFirstRemoved() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + int expectedCountOfItems = 3; + int returnedCountOfItems; + + linkedList.addAfterLast("Jack"); + linkedList.addAfterLast("Anne"); + linkedList.addAfterLast("John"); + linkedList.addAfterLast("George"); + linkedList.addAfterLast("Kate"); + //act + linkedList.removeFirst(); + linkedList.removeFirst(); + returnedCountOfItems = linkedList.size(); + //assert + assertEquals(expectedCountOfItems, returnedCountOfItems); + } + + /** + * Test of getsize method, of class LinkedList. + */ + @Test + public void size_shouldHaveCountFourAfterLastRemoved() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + int expectedCountOfItems = 4; + linkedList.addAfterLast("Jack"); + linkedList.addAfterLast("Anne"); + linkedList.addAfterLast("John"); + linkedList.addAfterLast("George"); + linkedList.addAfterLast("Kate"); + //act + linkedList.removeLast(); + //assert + assertEquals(expectedCountOfItems, linkedList.size()); + } + + /** + * Test of getsize method, of class LinkedList. + */ + @Test + public void size_shouldHaveCountThreeAfterLastTwoRemoved() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + int expectedCountOfItems = 3; + linkedList.addAfterLast("Jack"); + linkedList.addAfterLast("Anne"); + linkedList.addAfterLast("John"); + linkedList.addAfterLast("George"); + linkedList.addAfterLast("Kate"); + //act + linkedList.removeLast(); + linkedList.removeLast(); + //assert + assertEquals(expectedCountOfItems, linkedList.size()); + } + + /** + * Test of getsize method, of class LinkedList. + */ + @Test + public void size_shouldHaveCountSixAfterAddedBeforeFirst() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + int expectedCountOfItems = 6; + linkedList.addAfterLast("Jack"); + linkedList.addAfterLast("Anne"); + linkedList.addAfterLast("John"); + linkedList.addAfterLast("George"); + linkedList.addAfterLast("Kate"); + ; + linkedList.addBeforeFirst("Mike"); + //assert + assertEquals(expectedCountOfItems, linkedList.size()); + } + + /** + * Test of getsize method, of class LinkedList. + */ + @Test + public void size_shouldHaveCountSixAfterAddedAfterLast() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + int expectedCountOfItems = 6; + linkedList.addAfterLast("Jack"); + linkedList.addAfterLast("Anne"); + linkedList.addAfterLast("John"); + linkedList.addAfterLast("George"); + linkedList.addAfterLast("Kate"); + //act + linkedList.addAfterLast("Mike"); + //assert + assertEquals(expectedCountOfItems, linkedList.size()); + } + + /** + * Test of isEmpty method, of class LinkedList. + */ + @Test + public void isEmpty_justCreatedInstanceShouldBeEmpty() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + boolean returnedValue; + //act + returnedValue = linkedList.isEmpty(); + //assert + assertTrue(returnedValue); + } + + /** + * Test of isEmpty method, of class LinkedList. + */ + @Test + public void isEmpty_linkedListShouldHaveFiveItemsAndShouldNotBeEmpty() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.addAfterLast("Jack"); + linkedList.addAfterLast("Anne"); + linkedList.addAfterLast("John"); + linkedList.addAfterLast("George"); + linkedList.addAfterLast("Kate"); + //act + //assert + assertFalse(linkedList.isEmpty()); + } + + /** + * Test of addBeforeFirst method, of class LinkedList. + */ + @Test + public void isEmpty_countWasFive_fiveItemsWasRemoved_shouldBeEmpty_1() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.addAfterLast("Jack"); + linkedList.addAfterLast("Anne"); + linkedList.addAfterLast("John"); + linkedList.addAfterLast("George"); + linkedList.addAfterLast("Kate"); + //act + linkedList.removeFirst(); + linkedList.removeLast(); + linkedList.removeLast(); + linkedList.removeFirst(); + linkedList.removeLast(); + //assert + assertTrue(linkedList.isEmpty()); + } + + /** + * Test of addBeforeFirst method, of class LinkedList. + */ + @Test + public void isEmpty_countWasFive_fiveItemsWasRemoved_shouldBeEmpty_2() { + //arrange + SingleLinkedList linkedList = new SingleLinkedList<>(); + linkedList.addAfterLast("Jack"); + linkedList.addAfterLast("Anne"); + linkedList.addAfterLast("John"); + linkedList.addAfterLast("George"); + linkedList.addAfterLast("Kate"); + //act + linkedList.removeFirst(); + linkedList.removeLast(); + linkedList.removeLast(); + linkedList.removeFirst(); + linkedList.removeFirst(); + //assert + assertTrue(linkedList.isEmpty()); + } + +} diff --git a/src/test/java/org/nanoboot/powerframework/collections/StackTest.java b/power-collections/src/test/java/org/nanoboot/powerframework/collections/StackTest.java similarity index 59% rename from src/test/java/org/nanoboot/powerframework/collections/StackTest.java rename to power-collections/src/test/java/org/nanoboot/powerframework/collections/StackTest.java index 827cbf6..65131ca 100644 --- a/src/test/java/org/nanoboot/powerframework/collections/StackTest.java +++ b/power-collections/src/test/java/org/nanoboot/powerframework/collections/StackTest.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -20,14 +20,18 @@ package org.nanoboot.powerframework.collections; -import org.nanoboot.powerframework.PowerRuntimeException; -import org.junit.Test; +import java.util.*; + import static org.junit.Assert.*; +import org.junit.*; + /** * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ + public class StackTest { /** @@ -37,102 +41,102 @@ public class StackTest { } /** - * Test of getCountOfItems method, of class Stack. + * Test of size method, of class Stack. */ @Test - public void testGetCountOfItems() { + public void testsize() { //arrange - Stack stack = new Stack<>(); + PowerStack stack = new PowerStack<>(); int expectedCountOfItems = 0; int returnedCountOfItems; //act - returnedCountOfItems = stack.getCountOfItems(); + returnedCountOfItems = stack.size(); //assert assertEquals(expectedCountOfItems, returnedCountOfItems); } /** - * Test of getCountOfItems method, of class Stack. + * Test of size method, of class Stack. */ @Test - public void testGetCountOfItems2() { + public void testsize2() { //arrange - Stack stack = new Stack<>(); + PowerStack stack = new PowerStack<>(); int expectedCountOfItems = 0; int returnedCountOfItems; //act - stack.push("John"); + stack.pushAndReturn("John"); stack.pop(); - returnedCountOfItems = stack.getCountOfItems(); + returnedCountOfItems = stack.size(); //assert assertEquals(expectedCountOfItems, returnedCountOfItems); } /** - * Test of getCountOfItems method, of class Stack. + * Test of size method, of class Stack. */ @Test - public void testGetCountOfItems3() { + public void testsize3() { //arrange - Stack stack = new Stack<>(); + PowerStack stack = new PowerStack<>(); int expectedCountOfItems = 0; int returnedCountOfItems; //act - stack.push("John"); + stack.pushAndReturn("John"); stack.pop(); - stack.push("Jack").push("Anne").push("Charlie"); + stack.pushAndReturn("Jack").pushAndReturn("Anne").pushAndReturn("Charlie"); stack.pop(); stack.pop(); stack.pop(); - stack.push("Jane"); + stack.pushAndReturn("Jane"); stack.pop(); - returnedCountOfItems = stack.getCountOfItems(); + returnedCountOfItems = stack.size(); //assert assertEquals(expectedCountOfItems, returnedCountOfItems); } /** - * Test of getCountOfItems method, of class Stack. + * Test of size method, of class Stack. */ @Test - public void testGetCountOfItems4() { + public void testsize4() { //arrange - Stack stack = new Stack<>(); + PowerStack stack = new PowerStack<>(); int expectedCountOfItems = 1; int returnedCountOfItems; //act - stack.push("John"); + stack.pushAndReturn("John"); stack.pop(); - stack.push("Jack").push("Anne").push("Charlie"); + stack.pushAndReturn("Jack").pushAndReturn("Anne").pushAndReturn("Charlie"); stack.pop(); stack.pop(); - stack.push("Jane"); + stack.pushAndReturn("Jane"); stack.pop(); - returnedCountOfItems = stack.getCountOfItems(); + returnedCountOfItems = stack.size(); //assert assertEquals(expectedCountOfItems, returnedCountOfItems); } /** - * Test of getCountOfItems method, of class Stack. + * Test of size method, of class Stack. */ @Test - public void testGetCountOfItems5() { + public void testsize5() { //arrange - Stack stack = new Stack<>(); + PowerStack stack = new PowerStack<>(); int expectedCountOfItems = 3; int returnedCountOfItems; //act - stack.push("John"); + stack.pushAndReturn("John"); stack.pop(); - stack.push("Jack").push("Anne").push("Charlie").push("Susan"); + stack.pushAndReturn("Jack").pushAndReturn("Anne").pushAndReturn("Charlie").pushAndReturn("Susan"); stack.pop(); - stack.push("Jane"); + stack.pushAndReturn("Jane"); stack.pop(); - returnedCountOfItems = stack.getCountOfItems(); + returnedCountOfItems = stack.size(); //assert assertEquals(expectedCountOfItems, returnedCountOfItems); } @@ -143,7 +147,7 @@ public class StackTest { @Test public void testIsEmpty() { //arrange - Stack stack = new Stack<>(); + PowerStack stack = new PowerStack<>(); boolean expectedValue = true; boolean returnedValue; //act @@ -158,18 +162,18 @@ public class StackTest { @Test public void testIsEmpty2() { //arrange - Stack stack = new Stack<>(); + PowerStack stack = new PowerStack<>(); boolean expectedValue = true; boolean returnedValue; //act - stack.push("John").push("Jack").push("Anne").push("Charlie"); + stack.pushAndReturn("John").pushAndReturn("Jack").pushAndReturn("Anne").pushAndReturn("Charlie"); stack.pop(); stack.pop(); stack.pop(); stack.pop(); - stack.push("Jane"); + stack.pushAndReturn("Jane"); stack.pop(); returnedValue = stack.isEmpty(); //assert @@ -182,17 +186,17 @@ public class StackTest { @Test public void testIsEmpty3() { //arrange - Stack stack = new Stack<>(); + PowerStack stack = new PowerStack<>(); boolean expectedValue = false; boolean returnedValue; //act - stack.push("John").push("Jack").push("Anne").push("Charlie"); + stack.pushAndReturn("John").pushAndReturn("Jack").pushAndReturn("Anne").pushAndReturn("Charlie"); stack.pop(); stack.pop(); stack.pop(); - stack.push("Jane"); + stack.pushAndReturn("Jane"); stack.pop(); returnedValue = stack.isEmpty(); //assert @@ -205,16 +209,16 @@ public class StackTest { @Test public void testIsEmpty4() { //arrange - Stack stack = new Stack<>(); + PowerStack stack = new PowerStack<>(); boolean expectedValue = false; boolean returnedValue; //act - stack.push("John").push("Jack").push("Anne").push("Charlie"); + stack.pushAndReturn("John").pushAndReturn("Jack").pushAndReturn("Anne").pushAndReturn("Charlie"); stack.pop(); stack.pop(); - stack.push("Jane"); + stack.pushAndReturn("Jane"); stack.pop(); returnedValue = stack.isEmpty(); //assert @@ -225,18 +229,18 @@ public class StackTest { * Test of push method, of class Stack. */ @Test - public void testPush() { + public void testpushAndReturn() { //arrange - Stack stack = new Stack<>(); + PowerStack stack = new PowerStack<>(); String expectedString = "Jack"; String returnedString; //act - stack.push("John").push("Jack").push("Anne").push("Charlie"); + stack.pushAndReturn("John").pushAndReturn("Jack").pushAndReturn("Anne").pushAndReturn("Charlie"); stack.pop(); stack.pop(); - stack.push("Jane"); + stack.pushAndReturn("Jane"); stack.pop(); returnedString = stack.pop(); //assert @@ -249,32 +253,53 @@ public class StackTest { @Test public void testPop() { //arrange - Stack stack = new Stack<>(); + PowerStack stack = new PowerStack<>(); String expectedString = "Dennis"; String returnedString; //act - stack.push("John").push("Jack").push("Anne").push("Charlie").push("Alice").push("Dennis"); + stack.pushAndReturn("John").pushAndReturn("Jack").pushAndReturn("Anne").pushAndReturn("Charlie").pushAndReturn("Alice").pushAndReturn("Dennis"); - stack.push("Jane"); + stack.pushAndReturn("Jane"); stack.pop(); returnedString = stack.pop(); //assert assertEquals(expectedString, returnedString); } + /** + * Test of pop method, of class Stack. + */ + @Test + public void testPop2() { + + //arrange + boolean isExceptionThrown = false; + PowerStack stack = new PowerStack<>(); + //act + try { + stack.pop(); + } catch (NoSuchElementException e) { + isExceptionThrown = true; + } + //assert + if (!isExceptionThrown) { + fail("There should be thrown NoSuchElementException"); + } + } + /** * Test of peek method, of class Stack. */ @Test public void testPeek() { //arrange - Stack stack = new Stack<>(); + PowerStack stack = new PowerStack<>(); String expectedString = "Dennis"; String returnedString; //act - stack.push("John").push("Jack").push("Anne").push("Charlie").push("Alice").push("Dennis"); + stack.pushAndReturn("John").pushAndReturn("Jack").pushAndReturn("Anne").pushAndReturn("Charlie").pushAndReturn("Alice").pushAndReturn("Dennis"); - stack.push("Jane"); + stack.pushAndReturn("Jane"); stack.pop(); returnedString = stack.peek(); //assert @@ -287,38 +312,34 @@ public class StackTest { @Test public void testPeek2() { //arrange - Stack stack = new Stack<>(); + PowerStack stack = new PowerStack<>(); int expectedValue = 6; int returnedValue; //act - stack.push("John").push("Jack").push("Anne").push("Charlie").push("Alice").push("Dennis"); + stack.pushAndReturn("John").pushAndReturn("Jack").pushAndReturn("Anne").pushAndReturn("Charlie").pushAndReturn("Alice").pushAndReturn("Dennis"); - stack.push("Jane"); + stack.pushAndReturn("Jane"); stack.pop(); - returnedValue = stack.getCountOfItems(); + returnedValue = stack.size(); //assert assertEquals(expectedValue, returnedValue); } /** - * Test of pop method, of class Stack. + * Test of peek method, of class Stack. */ @Test - public void testPop2() { - + public void testClear() { //arrange - boolean isExceptionThrown = false; - Stack stack = new Stack<>(); + PowerStack stack = new PowerStack<>(); + boolean returnedValue; //act - try { - stack.pop(); - } catch (PowerRuntimeException e) { - isExceptionThrown = true; - } + stack.pushAndReturn("John").pushAndReturn("Jack").pushAndReturn("Anne").pushAndReturn("Charlie").pushAndReturn("Alice").pushAndReturn("Dennis"); + + stack.clear(); + returnedValue = stack.isEmpty(); //assert - if (!isExceptionThrown) { - fail("There should be thrown PowerRuntimeException"); - } + assertTrue(returnedValue); } /** @@ -327,11 +348,11 @@ public class StackTest { @Test public void testToString() { //arrange - Stack stack = new Stack<>(); - String expectedString = "Jane, Alice, "; + PowerStack stack = new PowerStack<>(); + String expectedString = "Jane, Alice"; String returnedString; //act - stack.push("Alice").push("Jane"); + stack.pushAndReturn("Alice").pushAndReturn("Jane"); returnedString = stack.toString(); //assert assertEquals(expectedString, returnedString); diff --git a/power-core/pom.xml b/power-core/pom.xml new file mode 100644 index 0000000..4f2c94d --- /dev/null +++ b/power-core/pom.xml @@ -0,0 +1,57 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-core + jar + + Power Core + Core functionality for the Power library + + + false + + + + + src/main/resources + true + + + + + + + + + org.projectlombok + lombok + + + diff --git a/power-core/src/lombok.config b/power-core/src/lombok.config new file mode 100644 index 0000000..f202d30 --- /dev/null +++ b/power-core/src/lombok.config @@ -0,0 +1,4 @@ +# tells Lombok that this is the root directory and that it shouldn’t search parent directories for more configuration files +config.stopBubbling = true +# tells Lombok to add @lombok.Generated annotation to all generated methods +lombok.addLombokGeneratedAnnotation = true \ No newline at end of file diff --git a/power-core/src/main/java/module-info.java b/power-core/src/main/java/module-info.java new file mode 100644 index 0000000..d82457b --- /dev/null +++ b/power-core/src/main/java/module-info.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +module powerframework.core { + requires lombok; + exports org.nanoboot.powerframework.core; + exports org.nanoboot.powerframework.core.exceptions; + exports org.nanoboot.powerframework.core.version; +} diff --git a/power-core/src/main/java/org/nanoboot/powerframework/core/CoreException.java b/power-core/src/main/java/org/nanoboot/powerframework/core/CoreException.java new file mode 100644 index 0000000..47c87ed --- /dev/null +++ b/power-core/src/main/java/org/nanoboot/powerframework/core/CoreException.java @@ -0,0 +1,41 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.core; + +/** + * Exception class for classes in core package. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class CoreException extends PowerException { + + /** + * Constructor with message. + * + * @param message message describing the reason, + * why this exception was thrown. + */ + public CoreException(final String message) { + super(message); + } + +} diff --git a/power-core/src/main/java/org/nanoboot/powerframework/core/PowerException.java b/power-core/src/main/java/org/nanoboot/powerframework/core/PowerException.java new file mode 100644 index 0000000..3519951 --- /dev/null +++ b/power-core/src/main/java/org/nanoboot/powerframework/core/PowerException.java @@ -0,0 +1,55 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.core; + +/** + * Exception for Power library. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class PowerException extends RuntimeException { + + /** + * Constructor without message. + */ + public PowerException() { + this("No detail."); + } + + /** + * Constructor with message. + * + * @param message Message describing, what happened + */ + public PowerException(final String message) { + super(message); + } + + /** + * Constructor with exception. + * + * @param exception another exception, which was thrown + */ + public PowerException(final Exception exception) { + this(exception.toString()); + } +} diff --git a/power-core/src/main/java/org/nanoboot/powerframework/core/PowerFramework.java b/power-core/src/main/java/org/nanoboot/powerframework/core/PowerFramework.java new file mode 100644 index 0000000..4897589 --- /dev/null +++ b/power-core/src/main/java/org/nanoboot/powerframework/core/PowerFramework.java @@ -0,0 +1,75 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.core; + +import org.nanoboot.powerframework.core.version.Version; +import org.nanoboot.powerframework.core.version.VersionType; + +/** + * Power is the core class of the Power library. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public final class PowerFramework { + + /** + * Current mayor number. + */ + private static final int MAJOR_NUMBER = 1; + /** + * Current minor number. + */ + private static final int MINOR_NUMBER = 0; + /** + * Current patch number. + */ + private static final int PATCH_NUMBER = 0; + /** + * Current version of the Power framework. + */ + private static Version version = + new Version( + MAJOR_NUMBER, + MINOR_NUMBER, + PATCH_NUMBER, + VersionType.SNAPSHOT, + 0); + /** + * Returns the version number of Power library. + * + * @return the version number of Power library + */ + public static String getVersion() { + return version.toString(); + } + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private PowerFramework() { + //Not meant to be instantiated. + //NOSONAR + } + +} diff --git a/power-core/src/main/java/org/nanoboot/powerframework/core/PowerObject.java b/power-core/src/main/java/org/nanoboot/powerframework/core/PowerObject.java new file mode 100644 index 0000000..5afb534 --- /dev/null +++ b/power-core/src/main/java/org/nanoboot/powerframework/core/PowerObject.java @@ -0,0 +1,50 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.core; + +import lombok.Getter; + +/** + * Base Power object. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class PowerObject { + /** + * Next id. + */ + private static long nextPowerObjectId = 0; + /** + * Id. + */ + @Getter + private final long powerObjectId; + + /** + *Constructor. + */ + public PowerObject() { + this.powerObjectId = nextPowerObjectId; + nextPowerObjectId++; + } + +} diff --git a/power-core/src/main/java/org/nanoboot/powerframework/core/exceptions/NotYetImplementedException.java b/power-core/src/main/java/org/nanoboot/powerframework/core/exceptions/NotYetImplementedException.java new file mode 100644 index 0000000..967b0b5 --- /dev/null +++ b/power-core/src/main/java/org/nanoboot/powerframework/core/exceptions/NotYetImplementedException.java @@ -0,0 +1,43 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.core.exceptions; + +import org.nanoboot.powerframework.core.PowerException; + +/** + * Exception happening in case, something is called, but not implemented yet. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class NotYetImplementedException extends PowerException { + + /** + * Constructor with message. + * + * @param message message describing the reason, + * why this exception was thrown. + */ + public NotYetImplementedException(final String message) { + super(message); + } + +} diff --git a/power-core/src/main/java/org/nanoboot/powerframework/core/exceptions/UnsupportedMethodException.java b/power-core/src/main/java/org/nanoboot/powerframework/core/exceptions/UnsupportedMethodException.java new file mode 100644 index 0000000..2ba0364 --- /dev/null +++ b/power-core/src/main/java/org/nanoboot/powerframework/core/exceptions/UnsupportedMethodException.java @@ -0,0 +1,45 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.core.exceptions; + +import org.nanoboot.powerframework.core.PowerException; + +/** + * Exception happening in case, something is called, + * but not implemented and not supported now and + * not intended to be supported in future. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class UnsupportedMethodException extends PowerException { + + /** + * Constructor with message. + * + * @param message message describing the reason, + * why this exception was thrown. + */ + public UnsupportedMethodException(final String message) { + super(message); + } + +} diff --git a/power-core/src/main/java/org/nanoboot/powerframework/core/exceptions/package-info.java b/power-core/src/main/java/org/nanoboot/powerframework/core/exceptions/package-info.java new file mode 100644 index 0000000..84a6fce --- /dev/null +++ b/power-core/src/main/java/org/nanoboot/powerframework/core/exceptions/package-info.java @@ -0,0 +1,27 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * Some common exceptions. + * + * @author Robert Vokac + * @since 0.0.0 + */ +package org.nanoboot.powerframework.core.exceptions; diff --git a/power-core/src/main/java/org/nanoboot/powerframework/core/package-info.java b/power-core/src/main/java/org/nanoboot/powerframework/core/package-info.java new file mode 100644 index 0000000..c1c7cbb --- /dev/null +++ b/power-core/src/main/java/org/nanoboot/powerframework/core/package-info.java @@ -0,0 +1,29 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * Core Power classes. + * + * @author Robert Vokac + * @since 0.0.0 + */ + + +package org.nanoboot.powerframework.core; diff --git a/power-core/src/main/java/org/nanoboot/powerframework/core/version/Version.java b/power-core/src/main/java/org/nanoboot/powerframework/core/version/Version.java new file mode 100644 index 0000000..16c4ac5 --- /dev/null +++ b/power-core/src/main/java/org/nanoboot/powerframework/core/version/Version.java @@ -0,0 +1,341 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.core.version; +import org.nanoboot.powerframework.core.CoreException; +import lombok.Data; +/* +Examples: + 1.2.0.1 instead of 1.1.2-a1 + 1.2.1.2 instead of 1.1.2-b2 (beta with some bug fixes) + 1.2.2.3 instead of 1.1.2-rc3 (release candidate) + 1.2.3.0 instead of 1.1.2-r (commercial distribution) + 1.2.3.5 instead of 1.1.2-r5 (commercial distribution with many bug fixes) + 1.2.3.5 instead of 1.1.2-SNAPSHOT + */ + +/** + * Version object representing a version of a software. + * @author Robert Vokac + * @since 0.0.0 + */ +@Data +public final class Version implements Comparable { + /** + * Dot "." separator. + */ + public static final String DOT_SEPARATOR = "."; + /** + * Dash "-" separator. + */ + public static final String DASH_SEPARATOR = "-"; + /** + * Internal constant "Version array length must be". + * It is used, if one of the possible exception happens. + */ + private static final String WRONG_ARRAY_LENGTH_EXC_MSG = + "Version array length must be "; + /** + * Constant "VERSION_TYPE_INDEX". + */ + public static final int VERSION_TYPE_INDEX = 3; + /** + * major number. + */ + private int majorNumber; + /** + * minor number. + */ + private int minorNumber; + /** + * patch number. + */ + private int patchNumber; + /** + * Version type. + */ + private VersionType versionType; + + /** + * special number. + * If version type is STANDARD or SNAPSHOT, the special number must be 0. + */ + private int specialNumber; + /** + * Constructor. + */ + public Version() { + //Default constructor to keep the no argument constructor. + this.versionType = VersionType.STANDARD; + } + + /** + * Constructor. + * Version type is STANDARD in this constructor. + * Special number is 0 in this constructor. + * @param majorNumberArg mayor number + * @param minorNumberArg minor number + * @param patchNumberArg patch number + */ + public Version(final int majorNumberArg, + final int minorNumberArg, + final int patchNumberArg) { + this(majorNumberArg, minorNumberArg, + patchNumberArg, VersionType.STANDARD); + } + /** + * Constructor. + * Special number is 0 in this constructor. + * @param majorNumberArg mayor number + * @param minorNumberArg minor number + * @param patchNumberArg patch number + * @param versionTypeArg version type + */ + public Version(final int majorNumberArg, + final int minorNumberArg, + final int patchNumberArg, + final VersionType versionTypeArg) { + this.majorNumber = majorNumberArg; + this.minorNumber = minorNumberArg; + this.patchNumber = patchNumberArg; + this.versionType = versionTypeArg; + this.specialNumber = 0; + } + /** + * Constructor. + * @param majorNumberArg mayor number + * @param minorNumberArg minor number + * @param patchNumberArg patch number + * @param versionTypeArg version type + * @param specialNumberArg special number + */ + public Version(final int majorNumberArg, + final int minorNumberArg, + final int patchNumberArg, + final VersionType versionTypeArg, + final int specialNumberArg) { + this.majorNumber = majorNumberArg; + this.minorNumber = minorNumberArg; + this.patchNumber = patchNumberArg; + this.versionType = versionTypeArg; + this.specialNumber = specialNumberArg; + } + + /** + * Constructor. + * @param versionAsString version as string + */ + public Version(final String versionAsString) { + String normalized = toNormalizedString(versionAsString); + + String[] versionArray = normalized.split("\\" + DOT_SEPARATOR); + final int expectedVersionArrayLength = 5; + if (versionArray.length != expectedVersionArrayLength) { + String msg = WRONG_ARRAY_LENGTH_EXC_MSG + expectedVersionArrayLength + + ", but it is " + versionArray.length; + throw new CoreException(msg); + } + String mayorStr = versionArray[VersionNumberType.MAJOR.getIndex()]; + this.majorNumber = Integer.valueOf(mayorStr); + String minorStr = versionArray[VersionNumberType.MINOR.getIndex()]; + this.minorNumber = Integer.valueOf(minorStr); + String patchStr = versionArray[VersionNumberType.PATCH.getIndex()]; + this.patchNumber = Integer.valueOf(patchStr); + this.versionType = VersionType.of(versionArray[VERSION_TYPE_INDEX]); + String specialStr = versionArray[VersionNumberType.SPECIAL.getIndex()]; + this.specialNumber = Integer.valueOf(specialStr); + checkIsValid(); + } + + /** + * Creates normalized string representation. + * @param versionAsString classic version String + * @return normalized string + */ + private String toNormalizedString(final String versionAsString) { + String normalized = versionAsString; + if (normalized.contains("-")) { //not standard + normalized = normalized.replace(DASH_SEPARATOR, DOT_SEPARATOR); + if (normalized.endsWith(VersionType.SNAPSHOT.getValue())) { + normalized = normalized + 0; + } + } else { + //note: is STANDARD + normalized = normalized + DOT_SEPARATOR + + VersionType.STANDARD.getValue() + + 0; + } + //replace the values + for (VersionType vt : VersionType.values()) { + boolean skipLoop = normalized + .contains(VersionType.STANDARD.getValue()) + && vt != VersionType.STANDARD; + if (skipLoop) { + //continue needed to avoid transforming standard to sta.nda.rd + continue; + } + String value = vt.getValue(); + if (normalized.contains(value)) { + this.versionType = vt; + normalized = normalized.replace(value, value + DOT_SEPARATOR); + } + } + return normalized; + } + + /** + * Creates a String representation of the instance. + * @return version as text + */ + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(majorNumber); + sb.append(DOT_SEPARATOR); + sb.append(minorNumber); + sb.append(DOT_SEPARATOR); + sb.append(patchNumber); + if (getVersionType() != VersionType.STANDARD) { + sb.append(DASH_SEPARATOR); + sb.append(getVersionType().getValue()); + if (getVersionType() != VersionType.SNAPSHOT) { + sb.append(this.getSpecialNumber()); + } + } + return sb.toString(); + } + + /** + * Loads version value. + * @param versionNumberType version sub type + * @return sub version number. + */ + public int getValue(final VersionNumberType versionNumberType) { + switch (versionNumberType) { + case MAJOR: return majorNumber; + case MINOR: return minorNumber; + case PATCH: return patchNumber; + case SPECIAL: return specialNumber; + default: throw new UnsupportedOperationException( + versionNumberType.toString()); + } + } + /** + * Loads version value. + * @param versionNumberType version sub type + * @param value version value + */ + public void setValue(final VersionNumberType versionNumberType, + final int value) { + switch (versionNumberType) { + case MAJOR: this.majorNumber = value; break; + case MINOR: this.minorNumber = value; break; + case PATCH: this.patchNumber = value; break; + case SPECIAL: this.specialNumber = value; break; + default: throw new UnsupportedOperationException( + versionNumberType.toString()); + } + } + + /** + * Increments a sub version. + * @param versionNumberType version sub type to be incremented. + */ + public void increment(final VersionNumberType versionNumberType) { + if (!getVersionType().isStandard()) { + String msg = + "This operation is not supported for version number type " + + versionNumberType; + throw new UnsupportedOperationException(msg); + } + int currentValue = getValue(versionNumberType); + int incrementedValue = currentValue + 1; + setValue(versionNumberType, incrementedValue); + switch (versionNumberType) { + case MAJOR: this.minorNumber = 0; this.patchNumber = 0; break; + case MINOR: this.patchNumber = 0; break; + case PATCH: /*nothing to do*/ break; + default: throw new UnsupportedOperationException( + versionNumberType.toString()); + } + } + /** + * Checks, if the version instance is valid. + * @throws CoreException thrown, if Version instance is not valid. + */ + public void checkIsValid() { + if (!validate()) { + String msg = "Version instance is not valid and cannot be created."; + throw new CoreException(msg); + } + } + /** + * Validates this version instance. + * @return true, if this version instance is valid, otherwise false. + */ + public boolean validate() { + boolean isStandard = this.getVersionType().isStandard(); + boolean isSnapshot = this.getVersionType().isSnapshot(); + if (isStandard || isSnapshot) { + if (specialNumber != 0) { + return false; + } + } else { + if (specialNumber <= 0) { + return false; + } + } + if (majorNumber < 0) { + return false; + } + if (minorNumber < 0) { + return false; + } + if (patchNumber < 0) { //NOSONAR + return false; + } + return true; + } + /** + * Creates exact copy of this version as a new instance. + * @return version instance + */ + public Version getCopy() { + return new Version(toString()); + } + + @Override + public int compareTo(final Version o) { + Version v1 = this; + Version v2 = o; + Integer mayor1 = v1.getMajorNumber(); + Integer mayor2 = v2.getMajorNumber(); + Integer minor1 = v1.getMinorNumber(); + Integer minor2 = v2.getMinorNumber(); + Integer patch1 = v1.getPatchNumber(); + Integer patch2 = v2.getPatchNumber(); + if (mayor1 != mayor2) { + return mayor1.compareTo(mayor2); + } + if (minor1 != minor2) { + return minor1.compareTo(minor2); + } + return patch1.compareTo(patch2); + } +} diff --git a/power-core/src/main/java/org/nanoboot/powerframework/core/version/VersionNumberType.java b/power-core/src/main/java/org/nanoboot/powerframework/core/version/VersionNumberType.java new file mode 100644 index 0000000..8cb548b --- /dev/null +++ b/power-core/src/main/java/org/nanoboot/powerframework/core/version/VersionNumberType.java @@ -0,0 +1,66 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.core.version; + +import lombok.Getter; + +/** + * Version subtype. + * @author Robert Vokac + * @since 0.0.0 + */ +public enum VersionNumberType { + /** + * Major version is used for big changes or not backward compatible changes. + */ + MAJOR(0), + /** + * Minor version is used for small changes. + */ + MINOR(1), + /** + * Patch version is used for bug fixed and not for new features. + */ + PATCH(2), + //Note: Index 3 is reserved for version type value. + /** + * Special version is used for some version types. + */ + SPECIAL(4), + /** + * Enumeration only for special purposes. + */ + UNKNOWN(100); + + /** + * Index of the version number type. + */ + @Getter + private final int index; + + /** + * Constructor. + * @param indexArg index of the version number type + */ + VersionNumberType(final int indexArg) { + this.index = indexArg; + } +} diff --git a/power-core/src/main/java/org/nanoboot/powerframework/core/version/VersionType.java b/power-core/src/main/java/org/nanoboot/powerframework/core/version/VersionType.java new file mode 100644 index 0000000..f5812e1 --- /dev/null +++ b/power-core/src/main/java/org/nanoboot/powerframework/core/version/VersionType.java @@ -0,0 +1,127 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.core.version; + +import lombok.Getter; + +/** + * Version type. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public enum VersionType { + /** + * Snapshot version. + * + * Description: Development version, which may not be stable. + */ + SNAPSHOT("SNAPSHOT"), + /** + * Alpha version. + * + * Description: alpha version. + */ + ALPHA("a"), + /** + * Beta version. + * + * Description: beta version. + */ + BETA("b"), + /** + * Release candidate version. + * + * Description: release candidate version. + */ + RELEASE_CANDIDATE("rc"), + /** + * Standard version. + * + * Description: standard version, which should be stable. + */ + STANDARD("standard"); + + /** + * Value of the version type. + */ + @Getter + private final String value; + + /** + * Constructor. + * @param valueArg of version type. + */ + VersionType(final String valueArg) { + this.value = valueArg; + } + + /** + * Returns version type of value string. + * @param string value as string + * @return version type + */ + public static VersionType of(final String string) { + for (VersionType e : VersionType.values()) { + if (string.equals(e.getValue())) { + return e; + } + } + String msg = "Found no VersionType with value " + string; + throw new UnsupportedOperationException(msg); + } + + /** + * Checks, the version type is SNAPSHOT. + * @return true, it the condition is true, otherwise false + */ + public boolean isSnapshot() { + return this == SNAPSHOT; + } + /** + * Checks, the version type is ALPHA. + * @return true, it the condition is true, otherwise false + */ + public boolean isAlpha() { + return this == ALPHA; + } + /** + * Checks, the version type is BETA. + * @return true, it the condition is true, otherwise false + */ + public boolean isBeta() { + return this == BETA; + } + /** + * Checks, the version type is RELEASE_CANDIDATE. + * @return true, it the condition is true, otherwise false + */ + public boolean isReleaseCandidate() { + return this == RELEASE_CANDIDATE; + } + /** + * Checks, the version type is STANDARD. + * @return true, it the condition is true, otherwise false + */ + public boolean isStandard() { + return this == STANDARD; + } +} diff --git a/power-core/src/main/java/org/nanoboot/powerframework/core/version/package-info.java b/power-core/src/main/java/org/nanoboot/powerframework/core/version/package-info.java new file mode 100644 index 0000000..bc20640 --- /dev/null +++ b/power-core/src/main/java/org/nanoboot/powerframework/core/version/package-info.java @@ -0,0 +1,27 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * Version classes. + * + * @author Robert Vokac + * @since 0.0.0 + */ +package org.nanoboot.powerframework.core.version; diff --git a/power-core/src/main/resources/.gitkeep b/power-core/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-core/src/main/resources/version.properties b/power-core/src/main/resources/version.properties new file mode 100644 index 0000000..410af8c --- /dev/null +++ b/power-core/src/main/resources/version.properties @@ -0,0 +1 @@ +version = ${project.version} diff --git a/power-core/src/test/java/org/nanoboot/powerframework/core/CoreExceptionTest.java b/power-core/src/test/java/org/nanoboot/powerframework/core/CoreExceptionTest.java new file mode 100644 index 0000000..87e7a14 --- /dev/null +++ b/power-core/src/test/java/org/nanoboot/powerframework/core/CoreExceptionTest.java @@ -0,0 +1,40 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.core; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class CoreExceptionTest { + + @Test + public void constructor_String() { + assertEquals("An error", new CoreException("An error").getMessage()); + } + +} diff --git a/power-core/src/test/java/org/nanoboot/powerframework/core/PowerExceptionTest.java b/power-core/src/test/java/org/nanoboot/powerframework/core/PowerExceptionTest.java new file mode 100644 index 0000000..1d0f436 --- /dev/null +++ b/power-core/src/test/java/org/nanoboot/powerframework/core/PowerExceptionTest.java @@ -0,0 +1,50 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.core; + +import org.junit.Test; + +import static org.junit.Assert.*; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class PowerExceptionTest { + + @Test + public void constructor() { + assertEquals("No detail.", new PowerException().getMessage()); + } + + @Test + public void constructor_String() { + assertEquals("An error", new PowerException("An error").getMessage()); + } + + @Test + public void constructor_Exception() { + RuntimeException e = new RuntimeException("abc"); + assertEquals(e.toString(), new PowerException(e).getMessage()); + } + +} diff --git a/power-core/src/test/java/org/nanoboot/powerframework/core/PowerFrameworkTest.java b/power-core/src/test/java/org/nanoboot/powerframework/core/PowerFrameworkTest.java new file mode 100644 index 0000000..311b33c --- /dev/null +++ b/power-core/src/test/java/org/nanoboot/powerframework/core/PowerFrameworkTest.java @@ -0,0 +1,38 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.core; + +import org.junit.Test; + +import static org.junit.Assert.*; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class PowerFrameworkTest { + + @Test + public void getVersion() { + assertNotNull(PowerFramework.getVersion()); + } +} diff --git a/power-core/src/test/java/org/nanoboot/powerframework/core/PowerObjectTest.java b/power-core/src/test/java/org/nanoboot/powerframework/core/PowerObjectTest.java new file mode 100644 index 0000000..d021de6 --- /dev/null +++ b/power-core/src/test/java/org/nanoboot/powerframework/core/PowerObjectTest.java @@ -0,0 +1,38 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.core; + +import org.junit.Test; + +import static org.junit.Assert.*; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class PowerObjectTest { + + @Test + public void getPowerObjectId() { + assertNotNull(new PowerObject().getPowerObjectId()); + } +} diff --git a/power-core/src/test/java/org/nanoboot/powerframework/core/exceptions/NotYetImplementedExceptionTest.java b/power-core/src/test/java/org/nanoboot/powerframework/core/exceptions/NotYetImplementedExceptionTest.java new file mode 100644 index 0000000..7d47dbf --- /dev/null +++ b/power-core/src/test/java/org/nanoboot/powerframework/core/exceptions/NotYetImplementedExceptionTest.java @@ -0,0 +1,39 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.core.exceptions; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class NotYetImplementedExceptionTest { + + @Test + public void constructor_String() { + assertEquals("An error", new NotYetImplementedException("An error").getMessage()); + } + +} diff --git a/power-core/src/test/java/org/nanoboot/powerframework/core/exceptions/UnsupportedMethodExceptionTest.java b/power-core/src/test/java/org/nanoboot/powerframework/core/exceptions/UnsupportedMethodExceptionTest.java new file mode 100644 index 0000000..6029500 --- /dev/null +++ b/power-core/src/test/java/org/nanoboot/powerframework/core/exceptions/UnsupportedMethodExceptionTest.java @@ -0,0 +1,40 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.core.exceptions; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class UnsupportedMethodExceptionTest { + + @Test + public void constructor_String() { + assertEquals("An error", new UnsupportedMethodException("An error").getMessage()); + } + + +} diff --git a/power-core/src/test/java/org/nanoboot/powerframework/core/version/VersionNumberTypeTest.java b/power-core/src/test/java/org/nanoboot/powerframework/core/version/VersionNumberTypeTest.java new file mode 100644 index 0000000..5f88c06 --- /dev/null +++ b/power-core/src/test/java/org/nanoboot/powerframework/core/version/VersionNumberTypeTest.java @@ -0,0 +1,38 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.core.version; + +import org.junit.Test; + +import static org.junit.Assert.*; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class VersionNumberTypeTest { + @Test + public void constructor() { + assertEquals(0, VersionNumberType.MAJOR.getIndex()); + } + +} diff --git a/power-core/src/test/java/org/nanoboot/powerframework/core/version/VersionTest.java b/power-core/src/test/java/org/nanoboot/powerframework/core/version/VersionTest.java new file mode 100644 index 0000000..0170946 --- /dev/null +++ b/power-core/src/test/java/org/nanoboot/powerframework/core/version/VersionTest.java @@ -0,0 +1,293 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.core.version; + +import org.nanoboot.powerframework.core.CoreException; +import org.junit.Ignore; +import org.junit.Test; + +import static org.nanoboot.powerframework.core.version.VersionNumberType.*; +import static org.junit.Assert.*; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class VersionTest { + + @Test + public void Version_noArg() { + Version version = new Version(); + assertEquals(0, version.getMajorNumber()); + assertEquals(0, version.getMinorNumber()); + assertEquals(0, version.getPatchNumber()); + assertEquals(VersionType.STANDARD, version.getVersionType()); + assertEquals(0, version.getSpecialNumber()); + } + + @Test + public void Version_int_int_int() { + Version version = new Version(1, 2, 3); + assertEquals(1, version.getMajorNumber()); + assertEquals(2, version.getMinorNumber()); + assertEquals(3, version.getPatchNumber()); + assertEquals(VersionType.STANDARD, version.getVersionType()); + assertEquals(0, version.getSpecialNumber()); + } + + @Test + public void Version_int_int_int_versionType() { + Version version = new Version(1, 2, 3, VersionType.SNAPSHOT); + assertEquals(1, version.getMajorNumber()); + assertEquals(2, version.getMinorNumber()); + assertEquals(3, version.getPatchNumber()); + assertEquals(VersionType.SNAPSHOT, version.getVersionType()); + assertEquals(0, version.getSpecialNumber()); + } + + @Test + public void Version_int_int_int_versionType_int() { + Version version = new Version(1, 2, 3, VersionType.BETA, 4); + assertEquals(1, version.getMajorNumber()); + assertEquals(2, version.getMinorNumber()); + assertEquals(3, version.getPatchNumber()); + assertEquals(VersionType.BETA, version.getVersionType()); + assertEquals(4, version.getSpecialNumber()); + } + + @Test + public void Version_String() { + Version version; + // + version = new Version("1.2.3-SNAPSHOT"); + assertEquals(1, version.getMajorNumber()); + assertEquals(2, version.getMinorNumber()); + assertEquals(3, version.getPatchNumber()); + assertEquals(VersionType.SNAPSHOT, version.getVersionType()); + assertEquals(0, version.getSpecialNumber()); + // + version = new Version("1.2.3-a5"); + assertEquals(1, version.getMajorNumber()); + assertEquals(2, version.getMinorNumber()); + assertEquals(3, version.getPatchNumber()); + assertEquals(VersionType.ALPHA, version.getVersionType()); + assertEquals(5, version.getSpecialNumber()); + // + version = new Version("1.2.3-b5"); + assertEquals(1, version.getMajorNumber()); + assertEquals(2, version.getMinorNumber()); + assertEquals(3, version.getPatchNumber()); + assertEquals(VersionType.BETA, version.getVersionType()); + assertEquals(5, version.getSpecialNumber()); + // + version = new Version("1.2.3-rc5"); + assertEquals(1, version.getMajorNumber()); + assertEquals(2, version.getMinorNumber()); + assertEquals(3, version.getPatchNumber()); + assertEquals(VersionType.RELEASE_CANDIDATE, version.getVersionType()); + assertEquals(5, version.getSpecialNumber()); + // + version = new Version("1.2.3"); + assertEquals(1, version.getMajorNumber()); + assertEquals(2, version.getMinorNumber()); + assertEquals(3, version.getPatchNumber()); + assertEquals(VersionType.STANDARD, version.getVersionType()); + assertEquals(0, version.getSpecialNumber()); + } + + @Test(expected = CoreException.class) + public void Version_Strin__exc() { + new Version("1.3.4.5"); + } + + @Test + public void testToString() { + Version version; + version = new Version("4.5.6-b7"); + assertEquals(7, version.getSpecialNumber()); + assertEquals("4.5.6-b7", version.toString()); + version = new Version("4.5.6"); + assertEquals("4.5.6", version.toString()); + version = new Version("4.5.6-SNAPSHOT"); + assertEquals("4.5.6-SNAPSHOT", version.toString()); + } + + @Test + public void getValue() { + Version version = new Version(1, 2, 3, VersionType.RELEASE_CANDIDATE, 6); + assertEquals(1, version.getValue(MAJOR)); + assertEquals(2, version.getValue(MINOR)); + assertEquals(3, version.getValue(PATCH)); + assertEquals(6, version.getValue(SPECIAL)); + } + + @Test + public void setValue() { + Version version = new Version(); + version.setValue(MAJOR, 1); + version.setValue(MINOR, 2); + version.setValue(PATCH, 3); + version.setValue(SPECIAL, 6); + // + assertEquals(1, version.getMajorNumber()); + assertEquals(2, version.getMinorNumber()); + assertEquals(3, version.getPatchNumber()); + assertEquals(6, version.getSpecialNumber()); + } + + @Test(expected = UnsupportedOperationException.class) + public void getValue_Exc() { + Version version = new Version(1, 2, 3, VersionType.RELEASE_CANDIDATE, 6); + version.getValue(VersionNumberType.UNKNOWN); + } + + @Test(expected = UnsupportedOperationException.class) + public void setValue_Exc() { + Version version = new Version(); + version.setValue(VersionNumberType.UNKNOWN, 1); + } + + @Test(expected = UnsupportedOperationException.class) + public void increment() { + Version version = new Version(); + version.setVersionType(VersionType.BETA); + version.setSpecialNumber(4); + version.increment(MAJOR); + } + + @Test() + public void increment2() { + Version version; + // + version = new Version(); + version.increment(MAJOR); + assertEquals("1.0.0", version.toString()); + // + version = new Version(); + version.increment(MINOR); + assertEquals("0.1.0", version.toString()); + // + version = new Version(); + version.increment(PATCH); + assertEquals("0.0.1", version.toString()); + } + + @Test(expected = UnsupportedOperationException.class) + public void increment3() { + Version version = new Version(); + version.increment(SPECIAL); + } + + @Test + public void validate() { + assertFalse(new Version(1, 2, 3, VersionType.STANDARD, 1).validate()); + assertFalse(new Version(1, 2, 3, VersionType.SNAPSHOT, 1).validate()); + assertFalse(new Version(1, 2, 3, VersionType.ALPHA, 0).validate()); + assertFalse(new Version(1, 2, 3, VersionType.BETA, 0).validate()); + assertFalse(new Version(1, 2, 3, VersionType.RELEASE_CANDIDATE, 0).validate()); + assertFalse(new Version(1, 2, 3, VersionType.ALPHA, -1).validate()); + assertFalse(new Version(1, 2, 3, VersionType.BETA, -1).validate()); + assertFalse(new Version(1, 2, 3, VersionType.RELEASE_CANDIDATE, -1).validate()); + assertFalse(new Version(-1, 2, 3).validate()); + assertFalse(new Version(1, -2, 3).validate()); + assertFalse(new Version(1, 2, -3).validate()); + assertTrue(new Version(1, 2, 3).validate()); + } + + @Test(expected = CoreException.class) + public void checkIsValid() { + new Version(1, 2, -3, VersionType.STANDARD, 1).checkIsValid(); + } + + @Test + public void getCopy() { + assertEquals("4.5.6-b8", new Version("4.5.6-b8").getCopy().toString()); + } + + /** + * Test of compareTo method, of class Version. + */ + @Test + public void testCompareTo() { + System.out.println("compareTo"); + //prepare + Version v0_0_0 = new Version("0.0.0"); + Version v0_0_1 = new Version("0.0.1"); + Version v0_0_2 = new Version("0.0.2"); + Version v0_1_0 = new Version("0.1.0"); + Version v0_1_1 = new Version("0.1.1"); + Version v0_1_2 = new Version("0.1.2"); + Version v1_0_0 = new Version("1.0.0"); + Version v1_0_1 = new Version("1.0.1"); + Version v1_0_2 = new Version("1.0.2"); + Version v2_0_0 = new Version("2.0.0"); + Version v2_0_1 = new Version("2.0.1"); + Version v2_0_2 = new Version("2.0.2"); + Version[] versions = new Version[]{ + v0_0_0, + v0_0_1, + v0_0_2, + v0_1_0, + v0_1_1, + v0_1_2, + v1_0_0, + v1_0_1, + v1_0_2, + v2_0_0, + v2_0_1, + v2_0_2 + }; + int vmin = 0; + int vmax = versions.length - 1; + //execute + //assert + for (Version v : versions) { + assertEquals(0, v.compareTo(v)); + } + for (int i = vmin; i <= vmax; i++) { + Version current = versions[i]; + Version previous = i == vmin ? null : versions[i - 1]; + Version next = i == vmax ? null : versions[i + 1]; + String msg = String.format( + "current = %s, previous = %s, next = %s", + current.toString(), + (previous == null ? null :previous.toString()), + (next == null ? null :next.toString()) + ); + //System.out.println(msg); + if (previous != null) { + assertEquals("Assertion failed: current > previous : " + msg, 1, current.compareTo(previous)); + } + if (next != null) { + assertEquals("Assertion failed: next > current : " + msg, 1, next.compareTo(current)); + } + // + if (previous != null) { + assertEquals("Assertion failed: previous < current : " + msg, -1, previous.compareTo(current)); + } + if (next != null) { + assertEquals("Assertion failed: current < next : " + msg, -1, current.compareTo(next)); + } + + } + } +} diff --git a/power-core/src/test/java/org/nanoboot/powerframework/core/version/VersionTypeTest.java b/power-core/src/test/java/org/nanoboot/powerframework/core/version/VersionTypeTest.java new file mode 100644 index 0000000..8c0f520 --- /dev/null +++ b/power-core/src/test/java/org/nanoboot/powerframework/core/version/VersionTypeTest.java @@ -0,0 +1,91 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.core.version; + +import org.junit.Test; + +import static org.junit.Assert.*; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class VersionTypeTest { + + @Test + public void of() { + assertEquals(VersionType.SNAPSHOT, VersionType.of("SNAPSHOT")); + assertEquals(VersionType.ALPHA, VersionType.of("a")); + assertEquals(VersionType.BETA, VersionType.of("b")); + assertEquals(VersionType.RELEASE_CANDIDATE, VersionType.of("rc")); + assertEquals(VersionType.STANDARD, VersionType.of("standard")); + } + @Test(expected = UnsupportedOperationException.class) + public void of2() { + VersionType.of("nonsense text"); + } + + @Test + public void isSnapshot() { + assertTrue(VersionType.SNAPSHOT.isSnapshot()); + assertFalse(VersionType.ALPHA.isSnapshot()); + assertFalse(VersionType.BETA.isSnapshot()); + assertFalse(VersionType.RELEASE_CANDIDATE.isSnapshot()); + assertFalse(VersionType.STANDARD.isSnapshot()); + } + + @Test + public void isAlpha() { + assertFalse(VersionType.SNAPSHOT.isAlpha()); + assertTrue(VersionType.ALPHA.isAlpha()); + assertFalse(VersionType.BETA.isAlpha()); + assertFalse(VersionType.RELEASE_CANDIDATE.isAlpha()); + assertFalse(VersionType.STANDARD.isAlpha()); + } + + @Test + public void isBeta() { + assertFalse(VersionType.SNAPSHOT.isBeta()); + assertFalse(VersionType.ALPHA.isBeta()); + assertTrue(VersionType.BETA.isBeta()); + assertFalse(VersionType.RELEASE_CANDIDATE.isBeta()); + assertFalse(VersionType.STANDARD.isBeta()); + } + + @Test + public void isReleaseCandidate() { + assertFalse(VersionType.SNAPSHOT.isReleaseCandidate()); + assertFalse(VersionType.ALPHA.isReleaseCandidate()); + assertFalse(VersionType.BETA.isReleaseCandidate()); + assertTrue(VersionType.RELEASE_CANDIDATE.isReleaseCandidate()); + assertFalse(VersionType.STANDARD.isReleaseCandidate()); + } + + @Test + public void isStandard() { + assertFalse(VersionType.SNAPSHOT.isStandard()); + assertFalse(VersionType.ALPHA.isStandard()); + assertFalse(VersionType.BETA.isStandard()); + assertFalse(VersionType.RELEASE_CANDIDATE.isStandard()); + assertTrue(VersionType.STANDARD.isStandard()); + } +} diff --git a/power-db/pom.xml b/power-db/pom.xml new file mode 100644 index 0000000..a4d88dd --- /dev/null +++ b/power-db/pom.xml @@ -0,0 +1,75 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-db + jar + + Power DB + DB functionality for the Power library + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + org.nanoboot.powerframework + power-collections + ${power.version} + + + org.nanoboot.powerframework + power-json + ${power.version} + + + org.nanoboot.powerframework + power-time + ${power.version} + + + + + junit + junit + 4.12 + test + + + org.xerial + sqlite-jdbc + 3.28.0 + provided + + + + diff --git a/power-db/src/main/java/module-info.java b/power-db/src/main/java/module-info.java new file mode 100644 index 0000000..4f9a833 --- /dev/null +++ b/power-db/src/main/java/module-info.java @@ -0,0 +1,35 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +module powerframework.db { + exports org.nanoboot.powerframework.db.manager; + requires powerframework.core; + requires java.sql; + requires powerframework.json; + requires powerframework.time; + requires powerframework.utils; + requires powerframework.collections; +} diff --git a/power-db/src/main/java/org/nanoboot/powerframework/db/engines/AbstractSqlEngine.java b/power-db/src/main/java/org/nanoboot/powerframework/db/engines/AbstractSqlEngine.java new file mode 100644 index 0000000..ce4d141 --- /dev/null +++ b/power-db/src/main/java/org/nanoboot/powerframework/db/engines/AbstractSqlEngine.java @@ -0,0 +1,61 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.db.engines; + +import org.nanoboot.powerframework.core.PowerObject; + +/** + * Here goes the description of this class. + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class AbstractSqlEngine extends PowerObject { + + /** + * Field description + */ + private String name; + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private AbstractSqlEngine() { + } + + /** + * Constructor + * + * Constructor description + * + * @param nameIn + */ + public AbstractSqlEngine(String nameIn) { + this.name = nameIn; + } + + + + +} diff --git a/power-db/src/main/java/org/nanoboot/powerframework/db/engines/sqlite/.gitkeep b/power-db/src/main/java/org/nanoboot/powerframework/db/engines/sqlite/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/org/nanoboot/powerframework/database/SqlCommandQueue.java b/power-db/src/main/java/org/nanoboot/powerframework/db/manager/CommandStore.java similarity index 65% rename from src/main/java/org/nanoboot/powerframework/database/SqlCommandQueue.java rename to power-db/src/main/java/org/nanoboot/powerframework/db/manager/CommandStore.java index e9e3a3d..e7b2963 100644 --- a/src/main/java/org/nanoboot/powerframework/database/SqlCommandQueue.java +++ b/power-db/src/main/java/org/nanoboot/powerframework/db/manager/CommandStore.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,18 +18,30 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.database; +package org.nanoboot.powerframework.db.manager; -import org.nanoboot.powerframework.collections.Queue; +import org.nanoboot.powerframework.collections.PowerQueue; /** * Used to execute more sql commands at once to achieve better performance. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ -public class SqlCommandQueue { +public class CommandStore { - private final Queue queue = new Queue<>(); + private final PowerQueue queue = new PowerQueue<>(); + + public CommandStore() { + + } + + public CommandStore(String sqlCommands) { + String[] commandsArray = sqlCommands.split(";"); + for (String part : commandsArray) { + add(part); + } + } /** * Adds sql command. @@ -37,14 +49,14 @@ public class SqlCommandQueue { * @param command */ public void add(String command) { - this.queue.enqueue(command); + this.queue.add(command); } - String loadNextCommand() { - return this.queue.dequeue(); + String getNextCommand() { + return this.queue.poll(); } - boolean isThereANextCommand() { + boolean hasNextCommand() { return !this.queue.isEmpty(); } diff --git a/power-db/src/main/java/org/nanoboot/powerframework/db/manager/Database.java b/power-db/src/main/java/org/nanoboot/powerframework/db/manager/Database.java new file mode 100644 index 0000000..dbada95 --- /dev/null +++ b/power-db/src/main/java/org/nanoboot/powerframework/db/manager/Database.java @@ -0,0 +1,515 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.db.manager; + +import java.io.*; +import java.sql.*; +import java.util.ArrayList; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.nanoboot.powerframework.json.JsonArray; +import org.nanoboot.powerframework.json.JsonObject; +import org.nanoboot.powerframework.core.PowerException; +import org.nanoboot.powerframework.time.moment.UniversalDateTime; +import static org.nanoboot.powerframework.utils.StringUtils.EMPTY_STRING; + +/** + * Represents connection to a database. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class Database { + + private Connection connection = null; + private Statement statement = null; + private final String databaseName; + + private final String jdbcUrl; + + private static final String DOT_SQLITE = ".sqlite"; + + Database(String databaseName) { + this.databaseName = databaseName; + StringBuilder stringBuilder = new StringBuilder().append("jdbc:sqlite:"); + if(!databaseName.equals(EMPTY_STRING)) { + stringBuilder.append(databaseName).append(DOT_SQLITE).toString(); + } + this.jdbcUrl = stringBuilder.toString(); + } + + public UniversalDateTime backup() { + UniversalDateTime universalDateTime = UniversalDateTime.now(); + String dateTimeString = universalDateTime.toString().replace(":", " "); + File databaseFile = new File("." + File.separator + databaseName + DOT_SQLITE); + + File backupDatabaseFile = new File("." + File.separator + databaseFile.getName() + "." + dateTimeString + "." + "sqlitebackup"); + try { + copyFileUsingStream(databaseFile, backupDatabaseFile); + } catch (IOException ex) { + Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); + } + return universalDateTime; + } + + private static void copyFileUsingStream(File source, File dest) throws IOException { + InputStream is = null; + OutputStream os = null; + try { + is = new FileInputStream(source); + os = new FileOutputStream(dest); + byte[] buffer = new byte[1024]; + int length; + while ((length = is.read(buffer)) > 0) { + os.write(buffer, 0, length); + } + } finally { + is.close(); + os.close(); + } + } + + /** + * + * @return name of the database of this database connection + */ + public String getDatabaseName() { + return databaseName; + } + + private void setConnection() { + setConnection(false); + } + + private void setConnection(boolean foreignKeysOn) { + try { + Class.forName("org.sqlite.JDBC"); + connection = DriverManager.getConnection(jdbcUrl); + statement = connection.createStatement(); + if(foreignKeysOn) { + statement.execute("PRAGMA foreign_keys = ON;"); + } + } catch (ClassNotFoundException | SQLException e) { + Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, e); + } + } + + /** + * Executes sql command, which returns no result. + * + * @param command + * + * @return last inserted row id + */ + public int execute(String command) { + int lastInsertedRowId = 0; + setConnection(); + ResultSet resultSet = null; + try { + statement.executeUpdate(command); + resultSet = statement.executeQuery("SELECT last_insert_rowid() AS LASTINSERTEDROWID;"); + resultSet.next(); + lastInsertedRowId = resultSet.getInt(1); + resultSet.close(); + connection.close(); + } catch (SQLException e) { + Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, e); + } finally { + if(resultSet != null) { + try { + resultSet.close(); + } catch (SQLException ex) { + Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); + } + } + + } + System.err.println(command); + return lastInsertedRowId; + } + + /** + * Executes sql command, which returns no result. + * + * @param command + * + * @return last inserted row id + */ + public int executeWithForeingKeysOff(String command) { + int lastInsertedRowId = 0; + setConnection(false); + ResultSet resultSet = null; + try { + statement.executeUpdate(command); + resultSet = statement.executeQuery("SELECT last_insert_rowid() AS LASTINSERTEDROWID;"); + resultSet.next(); + lastInsertedRowId = resultSet.getInt(1); + resultSet.close(); + connection.close(); + } catch (SQLException e) { + Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, e); + } finally { + if(resultSet != null) { + try { + resultSet.close(); + } catch (SQLException ex) { + Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); + } + } + + } + System.err.println(command); + return lastInsertedRowId; + } + + /** + * Executes sql commands from the command queue. + * + * @param commandQueue + */ + public void executeMoreCommands(CommandStore commandQueue) { + setConnection(); + + try { + connection.setAutoCommit(false); + while (commandQueue.hasNextCommand()) { + String command = commandQueue.getNextCommand(); + System.err.println(command); + statement.executeUpdate(command); + + } + + //No changes has been made in the database yet, so now we will commit + //the changes. + connection.commit(); + } catch (SQLException ex) { + Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); + try { + //An error occured so we rollback the changes. + connection.rollback(); + } catch (SQLException ex1) { + Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex1); + throw new DatabaseOperatingException("Fatal error happened. I was not able to rollback"); + } + } finally { + try { + if(statement != null) { + statement.close(); + connection.close(); + } + } catch (SQLException ex) { + Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); + } + } + } + + /** + * Executes sql commands from the given String, which is split by ; + * character. + * + * @param commands + */ + public void executeMoreCommands(String commands) { + CommandStore commandQueue = new CommandStore(commands); + + this.executeMoreCommands(commandQueue); + } + + /** + * Executes sql command, which returns result. + * + * @param command + * + * @return + */ + public Table executeAndReturn(String command) { + JsonObject table = new JsonObject(); + + JsonArray columns = new JsonArray(); + JsonArray rows = new JsonArray(); + + table.addString("query", command); + table.addArray("columns", columns); + table.addArray("rows", rows); + + setConnection(); + ResultSet resultSet = null; + try { + resultSet = statement.executeQuery(command); + + ResultSetMetaData rsmd = resultSet.getMetaData(); + int columnCount = rsmd.getColumnCount(); + for (int i = 1; i <= columnCount; i++) { + String columnName = rsmd.getColumnName(i); + columns.addString(columnName); + } + + while (resultSet.next()) { + JsonArray row = new JsonArray(); + for (int i = 0; i < columns.size(); i++) { + String columnName = columns.getString(i); + String value = resultSet.getString(columnName); + row.addString(value); + } + rows.addArray(row); + } + + connection.close(); + } catch (SQLException e) { + Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, e); + } finally { + closeConnectionAndResultSet(resultSet); + } + System.err.println(command); + return new Table(table); + } + + public ArrayList executeAndReturnIds(String command, String idColumnName) { + Table table = executeAndReturn(command); + ArrayList list = new ArrayList<>(); + while (table.hasNextRow()) { + table.moveToTheNextRow(); + list.add(table.getString(idColumnName)); + } + + return list; + } + + private void closeConnectionAndResultSet(ResultSet resultSet) { + try { + if(resultSet != null) { + resultSet.close(); + } + if(!connection.isClosed()) { + connection.close(); + } + } catch (SQLException e) { + Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, e); + } + } + + /** + * Updates value. + * + * @param tableName + * @param id + * @param columnName + * @param newValue + */ + public void updateValue(String tableName, + int id, + String columnName, + String newValue) { + String command + = "UPDATE " + tableName + " SET " + columnName + " = '" + newValue + "' WHERE ID = " + id; + this.execute(command); + System.err.println(command); + } + + /** + * Updates value. + * + * @param tableName + * @param id + * @param columnName + * @param newValue + */ + public void updateValue(String tableName, + int id, + String columnName, + int newValue) { + String command + = "UPDATE " + tableName + " SET " + columnName + " = " + newValue + " WHERE ID = " + id; + this.execute(command); + System.err.println(command); + } + + /** + * + * @param tableName + * @param id + * + * @return row with the given id from the given table as a json object + */ + public JsonObject getRow(String tableName, + int id) { + JsonObject row = new JsonObject(); + + JsonArray columns = new JsonArray(); + + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("select * from "); + stringBuilder.append(tableName); + stringBuilder.append(" where id="); + stringBuilder.append(id); + + String command = stringBuilder.toString(); + + setConnection(); + ResultSet resultSet = null; + try { + resultSet = statement.executeQuery(command); + System.err.println(command); + ResultSetMetaData rsmd = resultSet.getMetaData(); + int columnCount = rsmd.getColumnCount(); + for (int i = 1; i <= columnCount; i++) { + String columnName = rsmd.getColumnName(i); + columns.addString(columnName); + } + + if(!resultSet.next()) { + throw new DatabaseOperatingException("There is no row with id " + id + " in table " + tableName); + } + + for (int i = 0; i < columns.size(); i++) { + String columnName = columns.getString(i); + String value = resultSet.getString(columnName); + row.addString(columnName, value); + } + + connection.close(); + } catch (SQLException | PowerException e) { + Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, e); + throw new IllegalStateException(); + } finally { + + try { + if(resultSet != null) { + resultSet.close(); + } + if(!connection.isClosed()) { + connection.close(); + } + } catch (SQLException e) { + Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, e); + } + } + return row; + } + + public JsonObject getRow(String tableName, String uidIn) { + + JsonObject row = new JsonObject(); + + JsonArray columns = new JsonArray(); + + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("select * from "); + stringBuilder.append(tableName); + stringBuilder.append(" where UUID='"); + stringBuilder.append(uidIn); + stringBuilder.append("'"); + + String command = stringBuilder.toString(); + + setConnection(); + ResultSet resultSet = null; + try { + resultSet = statement.executeQuery(command); + System.err.println(command); + ResultSetMetaData rsmd = resultSet.getMetaData(); + int columnCount = rsmd.getColumnCount(); + for (int i = 1; i <= columnCount; i++) { + String columnName = rsmd.getColumnName(i); + columns.addString(columnName); + } + + if(!resultSet.next()) { + throw new DatabaseOperatingException("There is no row with uid " + uidIn + " in table " + tableName); + } + + for (int i = 0; i < columns.size(); i++) { + String columnName = columns.getString(i); + String value = resultSet.getString(columnName); + row.addString(columnName, value); + } + + connection.close(); + } catch (SQLException | PowerException e) { + Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, e); + throw new IllegalStateException(); + } finally { + + try { + if(resultSet != null) { + resultSet.close(); + } + if(!connection.isClosed()) { + connection.close(); + } + } catch (SQLException e) { + Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, e); + } + } + return row; + } + + /** + * + * @param tableName + * + * @return true, if the table is empty, otherwise false. + */ + public boolean isTableEmpty(String tableName) { + Table resultOfSqlQuery = this.executeAndReturn("SELECT * FROM " + tableName); + return resultOfSqlQuery.isEmpty(); + } + + /** + * + * @param table table name + * @param column column name + * @param whereClause for example: year_of_birth is greater than 1995 + * + * @return String value from a table and first row + */ + public String getString(String table, + String column, + String whereClause) { + String command = "SELECT " + column + " FROM " + table + " WHERE " + whereClause; + String value = null; + + setConnection(); + ResultSet resultSet = null; + try { + resultSet = statement.executeQuery(command); + + if(resultSet.next()) { + value = resultSet.getString(column); + } + connection.close(); + } catch (SQLException e) { + Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, e); + } finally { + + closeConnectionAndResultSet(resultSet); + + } + System.err.println(command); + return value; + } + + public boolean existTable(String tableName) { + Table table = executeAndReturn("SELECT name FROM sqlite_master WHERE type='table' AND name='" + tableName + "'"); + return !table.isEmpty(); + } + +} diff --git a/power-db/src/main/java/org/nanoboot/powerframework/db/manager/DatabaseException.java b/power-db/src/main/java/org/nanoboot/powerframework/db/manager/DatabaseException.java new file mode 100644 index 0000000..3fc0af7 --- /dev/null +++ b/power-db/src/main/java/org/nanoboot/powerframework/db/manager/DatabaseException.java @@ -0,0 +1,38 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.db.manager; + +import org.nanoboot.powerframework.core.PowerException; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class DatabaseException extends PowerException { + + public DatabaseException(String message) { + super(message); + } + +} diff --git a/power-db/src/main/java/org/nanoboot/powerframework/db/manager/DatabaseOperatingException.java b/power-db/src/main/java/org/nanoboot/powerframework/db/manager/DatabaseOperatingException.java new file mode 100644 index 0000000..4c693a8 --- /dev/null +++ b/power-db/src/main/java/org/nanoboot/powerframework/db/manager/DatabaseOperatingException.java @@ -0,0 +1,38 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.db.manager; + +import org.nanoboot.powerframework.core.PowerException; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class DatabaseOperatingException extends PowerException { + + public DatabaseOperatingException(String message) { + super(message); + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/database/Database.java b/power-db/src/main/java/org/nanoboot/powerframework/db/manager/Databases.java similarity index 63% rename from src/main/java/org/nanoboot/powerframework/database/Database.java rename to power-db/src/main/java/org/nanoboot/powerframework/db/manager/Databases.java index 88654ff..97ace5c 100644 --- a/src/main/java/org/nanoboot/powerframework/database/Database.java +++ b/power-db/src/main/java/org/nanoboot/powerframework/db/manager/Databases.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,56 +18,44 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.database; +package org.nanoboot.powerframework.db.manager; -import java.io.File; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.nanoboot.powerframework.PowerRuntimeException; +import java.io.*; +import java.sql.*; +import java.util.logging.*; /** * Manipulates with database. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ -public class Database { +public class Databases { private static final String SQLITEEXTENSION = ".sqlite"; - /** - * Constructor - * - * Not meant to be instantiated. - */ - private Database() { - //Not meant to be instantiated. - } - /** * Creates new database with the given name. * * @param databaseName */ public static void createDatabase(String databaseName) { - if (existsDatabase(databaseName)) { - throw new PowerRuntimeException("A database with the given name already exists."); + if(existsDatabase(databaseName)) { + throw new DatabaseOperatingException("A database with the given name already exists."); } Connection connection = null; try { Class.forName("org.sqlite.JDBC"); connection = DriverManager.getConnection("jdbc:sqlite:" + convertDatabaseNameToFileName(databaseName)); - } catch (Exception e) { - Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, e); - throw new PowerRuntimeException("New database was not created."); + } catch (ClassNotFoundException | SQLException e) { + Logger.getLogger(Databases.class.getName()).log(Level.SEVERE, null, e); + throw new DatabaseOperatingException("New database was not created."); } finally { - if (connection != null) { + if(connection != null) { try { connection.close(); } catch (SQLException ex) { - Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex); + Logger.getLogger(Databases.class.getName()).log(Level.SEVERE, null, ex); } } } @@ -79,18 +67,19 @@ public class Database { * @param databaseName */ public static void dropDatabase(String databaseName) { - if (!existsDatabase(databaseName)) { - throw new PowerRuntimeException("There is no database with the given name."); + if(!existsDatabase(databaseName)) { + throw new DatabaseOperatingException("There is no database with the given name."); } File file = new File("./" + convertDatabaseNameToFileName(databaseName)); boolean delete = file.delete(); - if (!delete) { - throw new PowerRuntimeException("The database was not dropped."); + if(!delete) { + throw new DatabaseOperatingException("The database was not dropped."); } } /** * @param databaseName + * * @return true, if a database with the name exists, otherwise false. */ public static boolean existsDatabase(String databaseName) { @@ -102,13 +91,14 @@ public class Database { * Creates a database connection for the database with the given name. * * @param databaseName + * * @return database connection to the database with the given name */ - public static DatabaseConnection createDatabaseConnection(String databaseName) { - if ((databaseName != "") && (!existsDatabase(databaseName))) { - throw new PowerRuntimeException("There is no database with the given name."); + public static Database getDatabase(String databaseName) { + if((!"".equals(databaseName)) && (!existsDatabase(databaseName))) { + throw new DatabaseOperatingException("There is no database with the given name."); } - return new DatabaseConnection(databaseName); + return new Database(databaseName); } /** @@ -116,12 +106,21 @@ public class Database { * * @return database connection */ - public static DatabaseConnection createInMemoryDatabaseConnection() { - return createDatabaseConnection(""); + public static Database createInMemoryDatabaseConnection() { + return getDatabase(""); } private static String convertDatabaseNameToFileName(String databaseName) { return databaseName + SQLITEEXTENSION; } + /** + * Constructor + * + * Not meant to be instantiated. + */ + private Databases() { + //Not meant to be instantiated. + } + } diff --git a/src/main/java/org/nanoboot/powerframework/database/ResultOfSqlQuery.java b/power-db/src/main/java/org/nanoboot/powerframework/db/manager/Table.java similarity index 80% rename from src/main/java/org/nanoboot/powerframework/database/ResultOfSqlQuery.java rename to power-db/src/main/java/org/nanoboot/powerframework/db/manager/Table.java index 254de5a..d507366 100644 --- a/src/main/java/org/nanoboot/powerframework/database/ResultOfSqlQuery.java +++ b/power-db/src/main/java/org/nanoboot/powerframework/db/manager/Table.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,26 +18,28 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.database; +package org.nanoboot.powerframework.db.manager; -import org.nanoboot.powerframework.PowerRuntimeException; -import org.nanoboot.powerframework.collections.Dictionary; -import org.nanoboot.powerframework.json.*; +import org.nanoboot.powerframework.json.JsonObject; +import org.nanoboot.powerframework.json.JsonArray; +import org.nanoboot.powerframework.collections.PowerMap; /** * Represents the result of a sql query. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * + * @author Robert Vokac + * @since 0.0.0 */ -public class ResultOfSqlQuery { +public class Table { private final JsonObject table; private final JsonArray columns; private final JsonArray rows; private int currentRowIndex = -1; - private final Dictionary dictionaryOfColumnNamesIndexes = new Dictionary(); + private final PowerMap dictionaryOfColumnNamesIndexes = new PowerMap(); - ResultOfSqlQuery(JsonObject jsonObject) { + Table(JsonObject jsonObject) { this.table = jsonObject; this.columns = table.getArray("columns"); this.rows = table.getArray("rows"); @@ -45,9 +47,9 @@ public class ResultOfSqlQuery { } private void fillDictionaryOfColumnNamesIndexes() { - for (int i = 0; i < columns.getCountOfItems(); i++) { + for (int i = 0; i < columns.size(); i++) { String currentColumnName = columns.getString(i); - dictionaryOfColumnNamesIndexes.addValue(currentColumnName, i); + dictionaryOfColumnNamesIndexes.put(currentColumnName, i); } } @@ -72,7 +74,7 @@ public class ResultOfSqlQuery { * @return count of rows */ public int getCountOfRows() { - return rows.getCountOfItems(); + return rows.size(); } /** @@ -95,7 +97,7 @@ public class ResultOfSqlQuery { * @return true, if there is a row after the current row, otherwise false. */ public boolean hasNextRow() { - return currentRowIndex + 1 < this.rows.getCountOfItems(); + return currentRowIndex + 1 < this.rows.size(); } /** @@ -106,8 +108,8 @@ public class ResultOfSqlQuery { } private JsonArray getCurrentRow() { - if (currentRowIndex == -1) { - throw new PowerRuntimeException("The position of the current row is before the first row"); + if(currentRowIndex == -1) { + throw new DatabaseOperatingException("The position of the current row is before the first row"); } return rows.getArray(currentRowIndex); } @@ -121,12 +123,13 @@ public class ResultOfSqlQuery { } private int getIndexForTheColumn(String columnName) { - return this.dictionaryOfColumnNamesIndexes.getValue(columnName); + return this.dictionaryOfColumnNamesIndexes.get(columnName); } /** * * @param columnName + * * @return the value of the column of the current row as int */ public int getInt(String columnName) { @@ -137,6 +140,7 @@ public class ResultOfSqlQuery { /** * * @param columnName + * * @return the value of the column of the current row as double */ public double getDouble(String columnName) { @@ -147,6 +151,7 @@ public class ResultOfSqlQuery { /** * * @param columnName + * * @return the value of the column of the current row as String */ public String getString(String columnName) { diff --git a/power-db/src/main/resources/.gitkeep b/power-db/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-db/src/test/java/org/nanoboot/powerframework/db/engines/.gitkeep b/power-db/src/test/java/org/nanoboot/powerframework/db/engines/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/test/java/org/nanoboot/powerframework/database/SqlCommandQueueTest.java b/power-db/src/test/java/org/nanoboot/powerframework/db/manager/CommandStoreTest.java similarity index 75% rename from src/test/java/org/nanoboot/powerframework/database/SqlCommandQueueTest.java rename to power-db/src/test/java/org/nanoboot/powerframework/db/manager/CommandStoreTest.java index 025c0b0..009c47c 100644 --- a/src/test/java/org/nanoboot/powerframework/database/SqlCommandQueueTest.java +++ b/power-db/src/test/java/org/nanoboot/powerframework/db/manager/CommandStoreTest.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,18 +18,22 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.database; +package org.nanoboot.powerframework.db.manager; -import org.junit.Test; import static org.junit.Assert.*; +import org.junit.*; /** + * * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ -public class SqlCommandQueueTest { - public SqlCommandQueueTest() { +@Ignore +public class CommandStoreTest { + + public CommandStoreTest() { } /** @@ -38,13 +42,13 @@ public class SqlCommandQueueTest { @Test public void testAdd() { //arrange - SqlCommandQueue sqlCommandQueue = new SqlCommandQueue(); + CommandStore sqlCommandQueue = new CommandStore(); String expectedString = "insert into customers values ('Jack','Black')"; String returnedString; //act sqlCommandQueue.add("insert into customers values ('Jack','Black')"); sqlCommandQueue.add("insert into customers values ('Susan','White')"); - returnedString = sqlCommandQueue.loadNextCommand(); + returnedString = sqlCommandQueue.getNextCommand(); //assert assertEquals(expectedString, returnedString); } @@ -55,14 +59,14 @@ public class SqlCommandQueueTest { @Test public void testLoadNextCommand() { //arrange - SqlCommandQueue sqlCommandQueue = new SqlCommandQueue(); + CommandStore sqlCommandQueue = new CommandStore(); String expectedString = "insert into customers values ('Susan','White')"; String returnedString; //act sqlCommandQueue.add("insert into customers values ('Jack','Black')"); sqlCommandQueue.add("insert into customers values ('Susan','White')"); - sqlCommandQueue.loadNextCommand(); - returnedString = sqlCommandQueue.loadNextCommand(); + sqlCommandQueue.getNextCommand(); + returnedString = sqlCommandQueue.getNextCommand(); //assert assertEquals(expectedString, returnedString); } @@ -73,13 +77,13 @@ public class SqlCommandQueueTest { @Test public void testIsThereANextCommand() { //arrange - SqlCommandQueue sqlCommandQueue = new SqlCommandQueue(); + CommandStore sqlCommandQueue = new CommandStore(); //act sqlCommandQueue.add("insert into customers values ('Jack','Black')"); sqlCommandQueue.add("insert into customers values ('Susan','White')"); - sqlCommandQueue.loadNextCommand(); + sqlCommandQueue.getNextCommand(); //assert - assertTrue(sqlCommandQueue.isThereANextCommand()); + assertTrue(sqlCommandQueue.hasNextCommand()); } /** @@ -88,14 +92,14 @@ public class SqlCommandQueueTest { @Test public void testIsThereANextCommand2() { //arrange - SqlCommandQueue sqlCommandQueue = new SqlCommandQueue(); + CommandStore sqlCommandQueue = new CommandStore(); //act sqlCommandQueue.add("insert into customers values ('Jack','Black')"); sqlCommandQueue.add("insert into customers values ('Susan','White')"); - sqlCommandQueue.loadNextCommand(); - sqlCommandQueue.loadNextCommand(); + sqlCommandQueue.getNextCommand(); + sqlCommandQueue.getNextCommand(); //assert - assertFalse(sqlCommandQueue.isThereANextCommand()); + assertFalse(sqlCommandQueue.hasNextCommand()); } /** @@ -104,8 +108,8 @@ public class SqlCommandQueueTest { @Test public void testToString() { //arrange - SqlCommandQueue sqlCommandQueue = new SqlCommandQueue(); - String expectedString = "insert into customers values ('Jack','Black'), insert into customers values ('Susan','White'), "; + CommandStore sqlCommandQueue = new CommandStore(); + String expectedString = "insert into customers values ('Jack','Black'), insert into customers values ('Susan','White')"; String returnedString; //act sqlCommandQueue.add("insert into customers values ('Jack','Black')"); diff --git a/src/test/java/org/nanoboot/powerframework/database/DatabaseConnectionTest.java b/power-db/src/test/java/org/nanoboot/powerframework/db/manager/DatabaseConnectionTest.java similarity index 78% rename from src/test/java/org/nanoboot/powerframework/database/DatabaseConnectionTest.java rename to power-db/src/test/java/org/nanoboot/powerframework/db/manager/DatabaseConnectionTest.java index 2864e48..53b2dff 100644 --- a/src/test/java/org/nanoboot/powerframework/database/DatabaseConnectionTest.java +++ b/power-db/src/test/java/org/nanoboot/powerframework/db/manager/DatabaseConnectionTest.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,38 +18,40 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.database; +package org.nanoboot.powerframework.db.manager; -import java.io.File; import org.nanoboot.powerframework.json.JsonObject; - -import org.nanoboot.powerframework.pseudorandom.PseudoRandomGenerator; -import org.junit.AfterClass; -import org.junit.Test; +import java.io.*; import static org.junit.Assert.*; -import org.junit.BeforeClass; + +import org.nanoboot.powerframework.random.generators.linearcongruent.combined.w5.W5RandomGenerator; +import org.junit.*; /** + * * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ + +@Ignore public class DatabaseConnectionTest { private static final File directory; private static final String directoryName; static { - PseudoRandomGenerator pseudoRandomGenerator = PseudoRandomGenerator.getInstance(); - int randomNumber = pseudoRandomGenerator.getInt(0, 999999); + W5RandomGenerator pseudoW5RandomGenerator = W5RandomGenerator.getStaticInstance(); + int randomNumber = pseudoW5RandomGenerator.nextInt(0, 999999); directoryName = "./temp" + randomNumber + "/"; directory = new File(directoryName); } static public boolean deleteDirectory(File path) { - if (path.exists()) { + if(path.exists()) { File[] files = path.listFiles(); for (int i = 0; i < files.length; i++) { - if (files[i].isDirectory()) { + if(files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); @@ -68,7 +70,7 @@ public class DatabaseConnectionTest { } private String getNextDatabaseName() { - return Integer.toString(PseudoRandomGenerator.getInstance().getInt(0, 1000000)); + return Integer.toString(W5RandomGenerator.getStaticInstance().nextInt(0, 1000000)); } /** @@ -80,8 +82,8 @@ public class DatabaseConnectionTest { String databaseName = directoryName + getNextDatabaseName(); String expectedString = databaseName; String returnedString; - Database.createDatabase(databaseName); - DatabaseConnection databaseConnection = Database.createDatabaseConnection(databaseName); + Databases.createDatabase(databaseName); + Database databaseConnection = Databases.getDatabase(databaseName); //act returnedString = databaseConnection.getDatabaseName(); //assert @@ -95,8 +97,8 @@ public class DatabaseConnectionTest { public void testExecute_String() { //arrange String databaseName = directoryName + getNextDatabaseName(); - Database.createDatabase(databaseName); - DatabaseConnection databaseConnection = Database.createDatabaseConnection(databaseName); + Databases.createDatabase(databaseName); + Database databaseConnection = Databases.getDatabase(databaseName); databaseConnection.execute("create table customers(id integer,name text,surname text,yearofbirth integer)"); //act databaseConnection.execute("insert into customers values(1,'John','Green',1954);"); @@ -111,9 +113,9 @@ public class DatabaseConnectionTest { public void testExecute_SqlCommandQueue() { //arrange String databaseName = directoryName + getNextDatabaseName(); - Database.createDatabase(databaseName); - DatabaseConnection databaseConnection = Database.createDatabaseConnection(databaseName); - SqlCommandQueue sqlCommandQueue = new SqlCommandQueue(); + Databases.createDatabase(databaseName); + Database databaseConnection = Databases.getDatabase(databaseName); + CommandStore sqlCommandQueue = new CommandStore(); sqlCommandQueue.add("create table customers(id integer,name text,surname text,yearofbirth integer)"); sqlCommandQueue.add("insert into customers values(1,'John','Green',1954);"); sqlCommandQueue.add("insert into customers values(2,'Anne','Blue',1985);"); @@ -132,9 +134,9 @@ public class DatabaseConnectionTest { public void testExecuteAndReturn() { //arrange String databaseName = directoryName + getNextDatabaseName(); - Database.createDatabase(databaseName); - DatabaseConnection databaseConnection = Database.createDatabaseConnection(databaseName); - SqlCommandQueue sqlCommandQueue = new SqlCommandQueue(); + Databases.createDatabase(databaseName); + Database databaseConnection = Databases.getDatabase(databaseName); + CommandStore sqlCommandQueue = new CommandStore(); sqlCommandQueue.add("create table customers(id integer,name text,surname text,yearofbirth integer)"); sqlCommandQueue.add("insert into customers values(1,'John','Green',1954);"); sqlCommandQueue.add("insert into customers values(2,'Anne','Blue',1985);"); @@ -144,7 +146,7 @@ public class DatabaseConnectionTest { String expectedString = "{\"query\":\"select * from customers\",\"columns\":[\"id\",\"name\",\"surname\",\"yearofbirth\"],\"rows\":[[\"1\",\"John\",\"Green\",\"1954\"],[\"2\",\"Anne\",\"Blue\",\"1985\"],[\"3\",\"Peter\",\"Orange\",\"1990\"]]}"; String returnedString; - ResultOfSqlQuery resultOfSqlQuery; + Table resultOfSqlQuery; //act resultOfSqlQuery = databaseConnection.executeAndReturn(query); returnedString = resultOfSqlQuery.toJsonObject().toMinimalString(); @@ -159,9 +161,9 @@ public class DatabaseConnectionTest { public void testGetRow() { //arrange String databaseName = directoryName + getNextDatabaseName(); - Database.createDatabase(databaseName); - DatabaseConnection databaseConnection = Database.createDatabaseConnection(databaseName); - SqlCommandQueue sqlCommandQueue = new SqlCommandQueue(); + Databases.createDatabase(databaseName); + Database databaseConnection = Databases.getDatabase(databaseName); + CommandStore sqlCommandQueue = new CommandStore(); sqlCommandQueue.add("create table customers(id integer,name text,surname text,yearofbirth integer)"); sqlCommandQueue.add("insert into customers values(1,'John','Green',1954);"); sqlCommandQueue.add("insert into customers values(2,'Anne','Blue',1985);"); @@ -187,9 +189,9 @@ public class DatabaseConnectionTest { //arrange String databaseName = directoryName + getNextDatabaseName(); boolean returnedValue; - Database.createDatabase(databaseName); - DatabaseConnection databaseConnection = Database.createDatabaseConnection(databaseName); - SqlCommandQueue sqlCommandQueue = new SqlCommandQueue(); + Databases.createDatabase(databaseName); + Database databaseConnection = Databases.getDatabase(databaseName); + CommandStore sqlCommandQueue = new CommandStore(); sqlCommandQueue.add("create table customers(id integer,name text,surname text,yearofbirth integer)"); databaseConnection.executeMoreCommands(sqlCommandQueue); //act @@ -207,9 +209,9 @@ public class DatabaseConnectionTest { //arrange String databaseName = directoryName + getNextDatabaseName(); boolean returnedValue; - Database.createDatabase(databaseName); - DatabaseConnection databaseConnection = Database.createDatabaseConnection(databaseName); - SqlCommandQueue sqlCommandQueue = new SqlCommandQueue(); + Databases.createDatabase(databaseName); + Database databaseConnection = Databases.getDatabase(databaseName); + CommandStore sqlCommandQueue = new CommandStore(); sqlCommandQueue.add("create table customers(id integer,name text,surname text,yearofbirth integer)"); sqlCommandQueue.add("insert into customers values(1,'John','Green',1954);"); sqlCommandQueue.add("insert into customers values(2,'Anne','Blue',1985);"); diff --git a/src/test/java/org/nanoboot/powerframework/database/DatabaseTest.java b/power-db/src/test/java/org/nanoboot/powerframework/db/manager/DatabaseTest.java similarity index 68% rename from src/test/java/org/nanoboot/powerframework/database/DatabaseTest.java rename to power-db/src/test/java/org/nanoboot/powerframework/db/manager/DatabaseTest.java index 3fef910..8cc7bed 100644 --- a/src/test/java/org/nanoboot/powerframework/database/DatabaseTest.java +++ b/power-db/src/test/java/org/nanoboot/powerframework/db/manager/DatabaseTest.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,37 +18,38 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.database; +package org.nanoboot.powerframework.db.manager; -import java.io.File; -import org.nanoboot.powerframework.PowerRuntimeException; -import org.nanoboot.powerframework.pseudorandom.PseudoRandomGenerator; -import org.junit.AfterClass; -import org.junit.Test; +import org.nanoboot.powerframework.random.generators.linearcongruent.combined.w5.W5RandomGenerator; +import org.nanoboot.powerframework.core.PowerException; +import java.io.*; import static org.junit.Assert.*; -import org.junit.BeforeClass; +import org.junit.*; /** + * * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ + public class DatabaseTest { private static final File directory; private static final String directoryName; static { - PseudoRandomGenerator pseudoRandomGenerator = PseudoRandomGenerator.getInstance(); - int randomNumber = pseudoRandomGenerator.getInt(0, 999999); + W5RandomGenerator pseudoW5RandomGenerator = W5RandomGenerator.getStaticInstance(); + int randomNumber = pseudoW5RandomGenerator.nextInt(0, 999999); directoryName = "./temp" + randomNumber + "/"; directory = new File(directoryName); } static public boolean deleteDirectory(File path) { - if (path.exists()) { + if(path.exists()) { File[] files = path.listFiles(); for (int i = 0; i < files.length; i++) { - if (files[i].isDirectory()) { + if(files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); @@ -67,7 +68,7 @@ public class DatabaseTest { } private String getNextDatabaseName() { - return Integer.toString(PseudoRandomGenerator.getInstance().getInt(0, 1000000)); + return Integer.toString(W5RandomGenerator.getStaticInstance().nextInt(0, 1000000)); } /** @@ -78,7 +79,7 @@ public class DatabaseTest { //arrange String databaseName = directoryName + getNextDatabaseName(); //act - Database.createDatabase(databaseName); + Databases.createDatabase(databaseName); //assert assertTrue(new File(databaseName + ".sqlite").exists()); } @@ -92,15 +93,15 @@ public class DatabaseTest { boolean isExceptionThrown = false; String databaseName = directoryName + getNextDatabaseName(); //act - Database.createDatabase(databaseName); + Databases.createDatabase(databaseName); try { - Database.createDatabase(databaseName); - } catch (PowerRuntimeException e) { + Databases.createDatabase(databaseName); + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { - fail("There should be thrown PowerRuntimeException"); + if(!isExceptionThrown) { + fail("There should be thrown OkayRuntimeException"); } } @@ -111,11 +112,11 @@ public class DatabaseTest { public void testDropDatabase() { //arrange String databaseName = directoryName + getNextDatabaseName(); - Database.createDatabase(databaseName); + Databases.createDatabase(databaseName); //act - Database.dropDatabase(databaseName); + Databases.dropDatabase(databaseName); //assert - assertFalse(Database.existsDatabase(databaseName)); + assertFalse(Databases.existsDatabase(databaseName)); } /** @@ -128,13 +129,13 @@ public class DatabaseTest { String databaseName = directoryName + getNextDatabaseName(); //act try { - Database.dropDatabase(databaseName); - } catch (PowerRuntimeException e) { + Databases.dropDatabase(databaseName); + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { - fail("There should be thrown PowerRuntimeException"); + if(!isExceptionThrown) { + fail("There should be thrown OkayRuntimeException"); } } @@ -142,13 +143,13 @@ public class DatabaseTest { * Test of existsDatabaseWithThisName method, of class Database. */ @Test - public void testExistsDatabaseWithThisName() { + public void testExistsDatabase() { //arrange String databaseName = directoryName + getNextDatabaseName(); //act - Database.createDatabase(databaseName); + Databases.createDatabase(databaseName); //assert - assertTrue(Database.existsDatabase(databaseName)); + assertTrue(Databases.existsDatabase(databaseName)); } /** @@ -160,7 +161,7 @@ public class DatabaseTest { String databaseName = directoryName + getNextDatabaseName(); //act //assert - assertFalse(Database.existsDatabase(databaseName)); + assertFalse(Databases.existsDatabase(databaseName)); } /** @@ -172,15 +173,15 @@ public class DatabaseTest { boolean isExceptionThrown = false; String databaseName = directoryName + getNextDatabaseName(); //act - Database.createDatabase(databaseName); + Databases.createDatabase(databaseName); try { - Database.createDatabaseConnection(databaseName); - } catch (PowerRuntimeException e) { + Databases.getDatabase(databaseName); + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (isExceptionThrown) { - fail("There should be thrown no PowerRuntimeException"); + if(isExceptionThrown) { + fail("There should be thrown no OkayRuntimeException"); } } @@ -194,13 +195,13 @@ public class DatabaseTest { String databaseName = directoryName + getNextDatabaseName(); //act try { - Database.createDatabaseConnection(databaseName); - } catch (PowerRuntimeException e) { + Databases.getDatabase(databaseName); + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { - fail("There should be thrown PowerRuntimeException"); + if(!isExceptionThrown) { + fail("There should be thrown OkayRuntimeException"); } } diff --git a/src/test/java/org/nanoboot/powerframework/database/ResultOfSqlQueryTest.java b/power-db/src/test/java/org/nanoboot/powerframework/db/manager/TableTest.java similarity index 87% rename from src/test/java/org/nanoboot/powerframework/database/ResultOfSqlQueryTest.java rename to power-db/src/test/java/org/nanoboot/powerframework/db/manager/TableTest.java index 2be8cf6..df49c44 100644 --- a/src/test/java/org/nanoboot/powerframework/database/ResultOfSqlQueryTest.java +++ b/power-db/src/test/java/org/nanoboot/powerframework/db/manager/TableTest.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,18 +18,21 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.database; +package org.nanoboot.powerframework.db.manager; -import org.nanoboot.powerframework.json.JsonArray; import org.nanoboot.powerframework.json.JsonObject; -import org.junit.Test; +import org.nanoboot.powerframework.json.JsonArray; import static org.junit.Assert.*; +import org.junit.*; /** * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * + * @author Robert Vokac + * @since 0.0.0 */ -public class ResultOfSqlQueryTest { +@Ignore +public class TableTest { private static final String jsonObjectAsString; @@ -59,7 +62,7 @@ public class ResultOfSqlQueryTest { jsonObjectAsString = jsonObject.toMinimalString(); } - public ResultOfSqlQueryTest() { + public TableTest() { } /** @@ -83,7 +86,7 @@ public class ResultOfSqlQueryTest { public void testGetColumnNames() { //arrange JsonObject jsonObject = new JsonObject(jsonObjectAsString); - ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + Table resultOfSqlQuery = new Table(jsonObject); String expectedString = "[\"id\",\"name\",\"surname\",\"yearofbirth\"]"; String returnedString; //act @@ -99,7 +102,7 @@ public class ResultOfSqlQueryTest { public void testGetRows() { //arrange JsonObject jsonObject = new JsonObject(jsonObjectAsString); - ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + Table resultOfSqlQuery = new Table(jsonObject); String expectedString = "[[\"1\",\"John\",\"Green\",\"1954\"],[\"2\",\"Anne\",\"Blue\",\"1985\"],[\"3\",\"Peter\",\"Orange\",\"1990\"]]"; String returnedString; //act @@ -115,7 +118,7 @@ public class ResultOfSqlQueryTest { public void testGetCountOfRows() { //arrange JsonObject jsonObject = new JsonObject(jsonObjectAsString); - ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + Table resultOfSqlQuery = new Table(jsonObject); int expectedValue = 3; int returnedValue; //act @@ -131,7 +134,7 @@ public class ResultOfSqlQueryTest { public void testIsEmpty() { //arrange JsonObject jsonObject = new JsonObject(jsonObjectAsString); - ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + Table resultOfSqlQuery = new Table(jsonObject); boolean returnedValue; //act returnedValue = resultOfSqlQuery.isEmpty(); @@ -146,7 +149,7 @@ public class ResultOfSqlQueryTest { public void testResetPosition() { //arrange JsonObject jsonObject = new JsonObject(jsonObjectAsString); - ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + Table resultOfSqlQuery = new Table(jsonObject); String expectedString = "[\"1\",\"John\",\"Green\",\"1954\"]"; String returnedString; //act @@ -166,7 +169,7 @@ public class ResultOfSqlQueryTest { public void testHasNextRow() { //arrange JsonObject jsonObject = new JsonObject(jsonObjectAsString); - ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + Table resultOfSqlQuery = new Table(jsonObject); boolean returnedValue; //act returnedValue = resultOfSqlQuery.hasNextRow(); @@ -181,7 +184,7 @@ public class ResultOfSqlQueryTest { public void testHasNextRow2() { //arrange JsonObject jsonObject = new JsonObject(jsonObjectAsString); - ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + Table resultOfSqlQuery = new Table(jsonObject); resultOfSqlQuery.moveToTheNextRow(); boolean returnedValue; //act @@ -197,7 +200,7 @@ public class ResultOfSqlQueryTest { public void testHasNextRow3() { //arrange JsonObject jsonObject = new JsonObject(jsonObjectAsString); - ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + Table resultOfSqlQuery = new Table(jsonObject); resultOfSqlQuery.moveToTheNextRow(); resultOfSqlQuery.moveToTheNextRow(); resultOfSqlQuery.moveToTheNextRow(); @@ -215,7 +218,7 @@ public class ResultOfSqlQueryTest { public void testMoveToTheNextRow() { //arrange JsonObject jsonObject = new JsonObject(jsonObjectAsString); - ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + Table resultOfSqlQuery = new Table(jsonObject); String expectedString = "[\"2\",\"Anne\",\"Blue\",\"1985\"]"; String returnedString; //act @@ -233,7 +236,7 @@ public class ResultOfSqlQueryTest { public void testGetInt() { //arrange JsonObject jsonObject = new JsonObject(jsonObjectAsString); - ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + Table resultOfSqlQuery = new Table(jsonObject); int expectedValue = 1985; int returnedValue; //act @@ -251,7 +254,7 @@ public class ResultOfSqlQueryTest { public void testGetDouble() { //arrange JsonObject jsonObject = new JsonObject(jsonObjectAsString); - ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + Table resultOfSqlQuery = new Table(jsonObject); double expectedValue = 1985d; double returnedValue; //act @@ -269,7 +272,7 @@ public class ResultOfSqlQueryTest { public void testGetString() { //arrange JsonObject jsonObject = new JsonObject(jsonObjectAsString); - ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + Table resultOfSqlQuery = new Table(jsonObject); String expectedString = "Anne"; String returnedString; //act @@ -287,7 +290,7 @@ public class ResultOfSqlQueryTest { public void testGetQuery() { //arrange JsonObject jsonObject = new JsonObject(jsonObjectAsString); - ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + Table resultOfSqlQuery = new Table(jsonObject); String expectedString = "select * from customers"; String returnedString; //act @@ -303,7 +306,7 @@ public class ResultOfSqlQueryTest { public void testToJsonObject() { //arrange JsonObject jsonObject = new JsonObject(jsonObjectAsString); - ResultOfSqlQuery resultOfSqlQuery = new ResultOfSqlQuery(jsonObject); + Table resultOfSqlQuery = new Table(jsonObject); String expectedString = jsonObjectAsString; String returnedString; //act diff --git a/power-io/pom.xml b/power-io/pom.xml new file mode 100644 index 0000000..e1cbc8c --- /dev/null +++ b/power-io/pom.xml @@ -0,0 +1,68 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-io + jar + + Power IO + IO functionality for the Power library + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + org.nanoboot.powerframework + power-random + ${power.version} + + + org.nanoboot.powerframework + power-collections + ${power.version} + + + org.nanoboot.powerframework + power-log + ${power.version} + + + + junit + junit + 4.12 + test + + + + diff --git a/power-io/src/main/java/module-info.java b/power-io/src/main/java/module-info.java new file mode 100644 index 0000000..a65516b --- /dev/null +++ b/power-io/src/main/java/module-info.java @@ -0,0 +1,36 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +module powerframework.io { + requires powerframework.core; + requires powerframework.random; + requires powerframework.collections; + requires powerframework.log; + requires java.logging; + requires powerframework.utils; + exports org.nanoboot.powerframework.io.bit.base64; +} diff --git a/power-io/src/main/java/org/nanoboot/powerframework/io/bit/Blob.java b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/Blob.java new file mode 100644 index 0000000..41dc4f3 --- /dev/null +++ b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/Blob.java @@ -0,0 +1,228 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.io.bit; + +import org.nanoboot.powerframework.core.PowerException; +import org.nanoboot.powerframework.random.generators.linearcongruent.combined.w5.W5RandomGenerator; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Blob { + + private final byte[] byteArray; +//TODO will hold byte[], but will have methods to set, update, flip, or read every bit of this blob, for example there will be a request to set the fourt bit of the twentieth byte to true (1) + + /** + * + * @param byteArrayIn + */ + public Blob(byte[] byteArrayIn) { + this.byteArray = byteArrayIn; + } + + public Blob(int countOfBytes) { + this.byteArray = new byte[countOfBytes]; + fillAllByZeroes(); + } + + /** + * + * @param string The required format are only zeroes and ones. Example: "01011101110100011001111" + */ + public Blob(String string) { + this(string.length() / 8); + int bitPosition = 0; + for (char element : string.toCharArray()) { + if(!(element == '1' || element == '0')) { + throw new PowerException("The string must contain only characters 0 or 1. " + "The character " + element + " does not follow this rule."); + } + this.setBits(bitPosition++, new boolean[]{element == '1'}); + + } + } + + public Blob(Blob... blobs) { + int countOfBytes = 0; + for (Blob blob : blobs) { + countOfBytes = +blob.getCountOfBytes(); + } + this.byteArray = new byte[countOfBytes]; + int index = 0; + for (Blob blob : blobs) { + for (int j = 0; j < blob.getCountOfBytes(); j++) { + this.byteArray[index++] = Byte.booleanArrayToByte(blob.getByte(j)); + } + } + + fillAllByZeroes(); + } + + public int getCountOfBytes() { + return this.byteArray.length; + } + + public int getCountOfBits() { + return this.byteArray.length * 8; + } + + public void fillAllByZeroes() { + fillWith(false, 0, this.byteArray.length - 1); + } + + public void fillAllByOnes() { + fillWith(true, 0, this.byteArray.length - 1); + } + + public void fillWith(boolean value, int byteFrom, int byteTo) { + byte booleanArray = Byte.booleanArrayToByte(value, value, value, value, value, value, value, value); + for (int i = byteFrom; i <= byteTo; i++) { + this.byteArray[i] = booleanArray; + } + } + + public void fillRandom() { + fillRandom(0, this.byteArray.length - 1); + + } + + public void fillRandom(int byteFrom, int byteTo) { + boolean[] booleanArray; + W5RandomGenerator pseudoW5RandomGenerator = W5RandomGenerator.getStaticInstance(); + for (int i = byteFrom; i <= byteTo; i++) { + + booleanArray = new boolean[8]; + for (int j = 0; j < 8; j++) { + booleanArray[j] = pseudoW5RandomGenerator.nextBoolean(); + } + + byte byteValue = Byte.booleanArrayToByte(booleanArray);; + this.byteArray[i] = byteValue; + } + + } + + public void flopAll() { + flop(0, this.byteArray.length - 1); + + } + + public void flop(int byteFrom, int byteTo) { + for (int bytePosition = byteFrom; bytePosition <= byteTo; bytePosition++) { + byte byteValue = this.byteArray[bytePosition]; + System.out.println("byteValue=" + byteValue); + boolean[] booleanArray = Byte.byteValueToBooleanArray(byteValue); + booleanArray = flopBooleanArray(booleanArray); + System.out.println("!byteValue=" + byteValue); + byteValue = Byte.booleanArrayToByte(booleanArray); + this.byteArray[bytePosition] = byteValue; + } + + } + + public static boolean[] flopBooleanArray(boolean[] booleanArray) { + for (int i = 0; i < booleanArray.length; i++) { + booleanArray[i] = !booleanArray[i]; + } + return booleanArray; + } + + public boolean[] getByte(int bytePosition) { + return Byte.byteValueToBooleanArray(this.byteArray[bytePosition]); + } + + public void setByte(int bytePosition, boolean[] booleanArray) { + this.byteArray[bytePosition] = Byte.booleanArrayToByte(booleanArray); + } + + public boolean[] getBits(int startBit, int endBit) { + boolean[] booleanArray = new boolean[endBit - startBit + 1]; + int booleanArrayIndex = 0; + int startBitDividedByEight = ((int) (startBit / 8)); + int startByte = startBitDividedByEight - 1; + if(startByte < 0) { + startByte = 0; + } + for (int bytePosition = startByte; booleanArrayIndex < (endBit - startBit + 1); bytePosition++) { + int bitPosition = bytePosition * 8; + byte byteValue = this.byteArray[bytePosition]; + boolean[] booleanArrayOfByte = Byte.byteValueToBooleanArray(byteValue); + for (int j = 0; j < 8; j++) { + boolean booleanValue = booleanArrayOfByte[j]; + + if(bitPosition >= startBit && bitPosition <= endBit) { + booleanArray[booleanArrayIndex++] = booleanValue; + } + bitPosition++; + } + } + return booleanArray; + } + + public void setBits(int startBit, boolean[] bitsToSetArray) { + int endBit = startBit + bitsToSetArray.length - 1; + int booleanArrayIndex = 0; + int startBitDividedByEight = ((int) (startBit / 8)); + int startByte = startBitDividedByEight - 1; + if(startByte < 0) { + startByte = 0; + } + for (int bytePosition = startByte; bytePosition < this.byteArray.length && booleanArrayIndex < bitsToSetArray.length; bytePosition++) { + int bitPosition = bytePosition * 8; + byte byteValue = this.byteArray[bytePosition]; + boolean[] booleanArrayOfByte = Byte.byteValueToBooleanArray(byteValue); + for (int j = 0; j < 8; j++) { + + if(bitPosition >= startBit && bitPosition <= endBit) { + boolean booleanValue = bitsToSetArray[booleanArrayIndex++]; +// System.out.println(booleanValue); + booleanArrayOfByte[j] = booleanValue; + } +// System.out.println(bitPosition); + bitPosition++; + this.byteArray[bytePosition] = Byte.booleanArrayToByte(booleanArrayOfByte); + } + } + } + + public boolean getBit(int bitPosition) { + return getBits(bitPosition, bitPosition)[0]; + } + + public void setBit(int bitPosition, boolean value) { + setBits(bitPosition, new boolean[]{value}); + } + + @Override + public String toString() { + StringBuilder stringBuilder = new StringBuilder(); + for (byte byteValue : this.byteArray) { + for (boolean booleanValue : Byte.byteValueToBooleanArray(byteValue)) { + stringBuilder.append(booleanValue ? "1" : "0"); + } + } + return stringBuilder.toString(); + } +} diff --git a/power-io/src/main/java/org/nanoboot/powerframework/io/bit/Byte.java b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/Byte.java new file mode 100644 index 0000000..cb3c68a --- /dev/null +++ b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/Byte.java @@ -0,0 +1,74 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.io.bit; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Byte { + + public static byte booleanArrayToByte(boolean... booleanArray) { + final int TWO = 2; + byte byteValue = -128; + int exponent = 0; + for (int i = booleanArray.length - 1; i >= 0; i--) { + int booleanAsInt = booleanArray[i] ? 1 : 0; + byteValue = (byte) (byteValue + (booleanAsInt * Math.pow(TWO, exponent))); + exponent++; + } + return byteValue; + } + + /** + * Convert a byte array to a boolean array. Bit 0 is represented with false, + * Bit 1 is represented with 1 + * + * @param bytes byte[] + * + * @return boolean[] + */ + private static boolean[] byteArrayToBooleanArray(byte[] bytes) { + boolean[] bits = new boolean[bytes.length * 8]; + for (int i = 0; i < bytes.length * 8; i++) { + if(((bytes[i / 8] + 128) & (1 << (7 - (i % 8)))) > 0) { + bits[i] = true; + } + } + return bits; + } + + /** + * Convert a byte array to a boolean array. Bit 0 is represented with false, + * Bit 1 is represented with 1 + * + * @param byteValueIn + * + * @return boolean[] + */ + public static boolean[] byteValueToBooleanArray(byte byteValueIn) { + return byteArrayToBooleanArray(new byte[]{byteValueIn}); + } + +} diff --git a/power-io/src/main/java/org/nanoboot/powerframework/io/bit/DigitalInformationUnit.java b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/DigitalInformationUnit.java new file mode 100644 index 0000000..6668220 --- /dev/null +++ b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/DigitalInformationUnit.java @@ -0,0 +1,127 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.io.bit; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public enum DigitalInformationUnit { + + /** + * + */ + BIT(null, 1), + + /** + * + */ + BYTE(BIT, 8), + + /** + * + */ + KILOBYTE(BYTE), + + /** + * + */ + MEGABYTE(KILOBYTE), + + /** + * + */ + GIGABYTE(MEGABYTE), + + /** + * + */ + TERABYTE(GIGABYTE), + + /** + * + */ + PETABYTE(TERABYTE), + + /** + * + */ + EXABYTE(PETABYTE); + private static final int CONSTANT1024 = 1024; + private static final int BYTEHASBYTES = 8; + private final long bits; + private final DigitalInformationUnit subordinateUnit; + //TODO + //private final DigitalInformationUnit superiorUnit; + + DigitalInformationUnit(DigitalInformationUnit subordinateUnit, + int bits) { + this.subordinateUnit = subordinateUnit; + this.bits = bits; + } + + DigitalInformationUnit(DigitalInformationUnit subordinateUnit) { + this.subordinateUnit = subordinateUnit; + this.bits = subordinateUnit.getBits() * CONSTANT1024; + } + + /** + * + * @return count of bits of the given unit + */ + public long getBits() { + return bits; + } + + /** + * + * @return count of bytes of the given unit + */ + public long getBytes() { + return bits / BYTEHASBYTES; + } + + /** + * + * @return subordinate unit of this unit. Example KiloByte has subordinate unit Byte. + */ + public DigitalInformationUnit getSubordinateUnit() { + return subordinateUnit; + } + + /** + * + * @param value count of input unit + * @param inputUnit input unit + * @param outputUnit output unit + * + * @return count of output unit + */ + public static long convert(long value, + DigitalInformationUnit inputUnit, + DigitalInformationUnit outputUnit) { + return 0; + //TODO + } +} diff --git a/power-io/src/main/java/org/nanoboot/powerframework/io/bit/TextCoder.java b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/TextCoder.java new file mode 100644 index 0000000..7c35ab1 --- /dev/null +++ b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/TextCoder.java @@ -0,0 +1,291 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.io.bit; + +/* + * + * + * tab + * breakline + * upper letter + * unicode one char start + * unicode start + * unicode end + * ! + * " + * # + * $ + * % + * ' + * + * + + * , + * . + * / + * 0 + * 1 + * 2 + * 3 + * 4 + * 5 + * 6 + * 7 + * 8 + * 9 + * : + * < + * = + * ? + * @ + * a + * b + * c + * d + * e + * f + * g + * h + * i + * j + * k + * l + * m + * n + * o + * p + * q + * r + * s + * t + * u + * v + * w + * x + * y + * z + * ~ + * ( + * { + * { + * _ + * Reverse + * +- + * /\ + * () + * [] + * {} + * <> + * |_ + * ~^ + * %& + * :; + * '` + * + * + * tab + * breakline + * upper letter + * unicode one char start + * unicode start + * unicode end + * ! + * " + * # + * $ + * % + * & + * ' + * + * + + * , + * - + * . + * / + * 0 + * 1 + * 2 + * 3 + * 4 + * 5 + * 6 + * 7 + * 8 + * 9 + * : + * ; + * < + * = + * > + * ? + * @ + * \ + * a + * b + * c + * d + * e + * f + * g + * h + * i + * j + * k + * l + * m + * n + * o + * p + * q + * r + * s + * t + * u + * v + * w + * x + * y + * z + * Extension + * ` + * ~ + * ^ + * ( + * ) + * { + * } + * { + * } + * _ + * | + * + * + */ + /* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + + +import org.nanoboot.powerframework.core.exceptions.NotYetImplementedException; +import org.nanoboot.powerframework.core.PowerObject; +import org.nanoboot.powerframework.core.PowerException; + +/** + * Here goes the description of this class. + * + * + * @author Robert Vokac + * @since 0.0.0 + * + */ +public class TextCoder extends PowerObject { + + + /** + * Constant description + */ + private static final String CONSTANT = "constant"; + private static final String ALPHABET = "1234567890abcdefghijklmnopqrstuvwxyz!?\"'#$%+*,./:<=@~({{_"; + private static final char[] charArray = ALPHABET.toCharArray(); + + public static Blob encode(String string) { + return null; + } + + public static String decode(Blob blob) { + return null; + } + + private static boolean[] charToBooleanArray(char charIn) { + for (int i = 0; i < charArray.length; i++) { + char value = charArray[i]; + if(value == charIn) { + int intValue = i + 1; + String binaryString = String.format("%60s", Integer.toBinaryString(intValue)); + boolean[] returnValue = new boolean[6]; + for (int j = 0; j < 6; j++) { + returnValue[j] = binaryString.charAt(j) == '1'; + } + return returnValue; + } + } + throw new PowerException("Char " + charIn + " was not found."); + } + +// private static boolean[] booleanArrayToChar(boolean[] booleanArrayIn) { +// for (int i = 0; i < charArray.length; i++) { +// char value = charArray[i]; +// if(value == charIn) { +// int intValue = i + 1; +// String binaryString = String.format("%60s", Integer.toBinaryString(intValue)); +// boolean[] returnValue = new boolean[6]; +// for (int j = 0; j < 6; j++) { +// returnValue[j] = binaryString.charAt(j) == '1'; +// } +// return returnValue; +// } +// } +// throw new DataStoringException("Char " + charIn + " was not found."); +// } + /** + * Constructor + * + * Not meant to be instantiated. + */ + private TextCoder() { + } + + /** + * Field description + */ + private String name; + + /** + * Constructor + * + * Not meant to be instantiated. + * / + * private TextCoder() { + * } + * + * /** + * Constructor + * + * Constructor description + * + * @param nameIn + */ + public TextCoder(String nameIn) { + this.name = nameIn; + } + + + @Override + public String toString() { + throw new NotYetImplementedException("toString"); + /** + * LOG.traceStartOfMethod(this, "toString"); + * return NAMEFIELD+"="+name; + */ + } + +} diff --git a/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/Base64Coder.java b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/Base64Coder.java new file mode 100644 index 0000000..88567dd --- /dev/null +++ b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/Base64Coder.java @@ -0,0 +1,86 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.io.bit.base64; + +import org.nanoboot.powerframework.core.PowerException; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Base64Coder { + + private static Base64Implementation BASE64_IMPLEMENTATION = Base64Implementation.JAVA; + + static { + //setBase64Implementation(Base64Implementation.JAVA); + } + + /** + * + * @param encodedDataIn + * + * @return + */ + public static byte[] decode(String encodedDataIn) { + switch (BASE64_IMPLEMENTATION) { + case OKAY: + return OkayBase64Decoder.decode(encodedDataIn); + case JAVA: + return JavaBase64Coder.decode(encodedDataIn); + default: { + throw new PowerException("Unknown Base64Implementation " + BASE64_IMPLEMENTATION.name() + "."); + } + } + } + + /** + * + * @param byteArrayIn + * + * @return + */ + public static String encode(byte[] byteArrayIn) { + switch (BASE64_IMPLEMENTATION) { + case OKAY: + return OkayBase64Encoder.encode(byteArrayIn); + case JAVA: + return JavaBase64Coder.encode(byteArrayIn); + default: { + throw new PowerException("Unknown Base64Implementation " + BASE64_IMPLEMENTATION.name() + "."); + } + } + + } + + public static Base64Implementation getBase64Implementation() { + return BASE64_IMPLEMENTATION; + } + + public static void setBase64Implementation( + Base64Implementation base64Implementation) { + Base64Coder.BASE64_IMPLEMENTATION = base64Implementation; + } + +} diff --git a/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/Base64Convertor.java b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/Base64Convertor.java new file mode 100644 index 0000000..c984d15 --- /dev/null +++ b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/Base64Convertor.java @@ -0,0 +1,63 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.io.bit.base64; + +import org.nanoboot.powerframework.core.PowerException; +import org.nanoboot.powerframework.io.bit.Byte; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +class Base64Convertor { + + private final static char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); + + static char byteToChar(byte byteValue) { + return ALPHABET[byteValue + 128]; + } + + static boolean[] convertCharToBooleanArray(char charIn) { + byte byteValue = charToByte(charIn); + return Byte.byteValueToBooleanArray(byteValue); + } + + private static byte charToByte(char charIn) { + if(charIn == '=') { + return 0; + } + int index = 0; + for (char element : ALPHABET) { + if(element == charIn) { +// System.out.println(charIn+" converted to "+(index)); + return (byte) (index - 128); + } + index++; + } + + throw new PowerException( + "There is no char: " + charIn); + } + +} diff --git a/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/Base64Implementation.java b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/Base64Implementation.java new file mode 100644 index 0000000..6f11f17 --- /dev/null +++ b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/Base64Implementation.java @@ -0,0 +1,35 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.io.bit.base64; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public enum Base64Implementation { + + OKAY, + JAVA, + STACKOVERFLOW; +} diff --git a/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/Base64Padding.java b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/Base64Padding.java new file mode 100644 index 0000000..e3cd0a4 --- /dev/null +++ b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/Base64Padding.java @@ -0,0 +1,88 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.io.bit.base64; + +import org.nanoboot.powerframework.core.PowerException; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +enum Base64Padding { + + NO(""), + ONEBYTE("=="), + TWOBYTE("="); + + private final String padding; + + Base64Padding(String paddingIn) { + this.padding = paddingIn; + } + + public String getPadding() { + return padding; + } + + static Base64Padding getBase64Padding(byte[] byteArrayIn) { + int byteArrayInLength = byteArrayIn.length; + switch (byteArrayInLength % 3) { + case 0: { + return NO; + } + case 1: { + return ONEBYTE; + } + case 2: { + return TWOBYTE; + } + default: { + throw new PowerException("getPadding method: switch command went to default section. "); + } + } + } + + static Base64Padding getBase64Padding(String encodedData) { + if(org.nanoboot.powerframework.utils.StringUtils.isEmpty(encodedData)) { + return NO; + }; + boolean lastCharIsEqual = encodedData.charAt(encodedData.length() - 1) == '='; + + boolean beforeLastCharIsEqual = encodedData.charAt(encodedData.length() - 1 - 1) == '='; + + if(lastCharIsEqual) { + if(beforeLastCharIsEqual) { + return ONEBYTE; + } else { + return TWOBYTE; + } + } else { + if(beforeLastCharIsEqual) { + throw new PowerException("The last character is not \"=\", but the before last is."); + } else { + return NO; + } + } + } +} diff --git a/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/JavaBase64Coder.java b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/JavaBase64Coder.java new file mode 100644 index 0000000..20b7cf7 --- /dev/null +++ b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/JavaBase64Coder.java @@ -0,0 +1,53 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.io.bit.base64; + +import java.util.*; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +class JavaBase64Coder { + + /** + * + * @param encodedDataIn + * + * @return + */ + static byte[] decode(String encodedDataIn) { + return Base64.getDecoder().decode(encodedDataIn); + } + + /** + * + * @param byteArrayIn + * + * @return + */ + static String encode(byte[] byteArrayIn) { + return Base64.getEncoder().encodeToString(byteArrayIn); + } +} diff --git a/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/OkayBase64Decoder.java b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/OkayBase64Decoder.java new file mode 100644 index 0000000..21d971c --- /dev/null +++ b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/OkayBase64Decoder.java @@ -0,0 +1,132 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.io.bit.base64; + +import java.util.Arrays; +import org.nanoboot.powerframework.collections.PowerQueue; +import org.nanoboot.powerframework.core.PowerException; +import org.nanoboot.powerframework.io.bit.Byte; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +class OkayBase64Decoder { + + /** + * Logger for this class. + */ + private static final org.nanoboot.powerframework.log.Logger LOG = org.nanoboot.powerframework.log.Logger.getLogger(OkayBase64Decoder.class); + + /** + * + * @param encodedDataIn + * + * @return + */ + public static byte[] decode(String encodedDataIn) { + LOG.traceStartOfMethod(null, "decode", "encodedDataIn", encodedDataIn); + if(encodedDataIn.length() % 4 != 0) { + throw new PowerException("The string length is " + encodedDataIn.length() + ". This length is not divisible four and it must be."); + } + String encodedData = encodedDataIn; + Base64Padding base64Padding = Base64Padding.getBase64Padding(encodedData); + int byteArrayLength = getByteArrayLength(encodedDataIn, base64Padding); + System.out.println("byteArrayLength=" + byteArrayLength); + byte[] byteArray = new byte[byteArrayLength]; + + PowerQueue bitQueue = new PowerQueue<>(); + processChars(byteArray, encodedData, bitQueue); + + return byteArray; + } + + private static int getByteArrayLength(String encodedDataIn, + Base64Padding base64Padding) { + LOG.traceStartOfMethod(null, "getByteArrayLength", "encodedDataIn", encodedDataIn, "base64Padding", base64Padding); + int stringLength = encodedDataIn.length(); + int byteArrayLength = stringLength / 4 * 3; + switch (base64Padding) { + case NO: { + return byteArrayLength; + } + case ONEBYTE: { + return byteArrayLength - 2; + } + case TWOBYTE: { + return byteArrayLength - 1; + } + default: { + throw new PowerException("Unknown Base64Padding " + base64Padding.name() + "."); + } + } + } + + private static void processChars(byte[] byteArray, + String encodedDataIn, + PowerQueue bitQueue) { + LOG.traceStartOfMethod(null, "processChars", "encodedDataIn", encodedDataIn, "bitQueue", bitQueue); + int byteArrayIndex = 0; + for (int i = 0; i < encodedDataIn.length(); i++) { + if(i % 100000 == 0) { + System.out.println(i + "/" + encodedDataIn.length()); + } + char charValue = encodedDataIn.charAt(i); + processChar(charValue, bitQueue); + byteArrayIndex = feedQueue(byteArray, byteArrayIndex, bitQueue); + } + } + + private static void processChar(char charValue, + PowerQueue bitQueue) { + LOG.traceStartOfMethod(null, "processChar", "charValue", charValue, "bitQueue", bitQueue.toString()); +// System.out.println("processChar " + charValue); + +// System.out.println(charValue + " transformed to " + sixBits.toString()); +// System.out.println("sixBits for "+charValue+":" + sixBits.toString()); + boolean[] booleanArray = Base64Convertor.convertCharToBooleanArray(charValue); + for (int j = 2; j < 8; j++) { + boolean element = booleanArray[j]; +// System.out.println("to queue added: " + element); + bitQueue.add(element); + } + } + + private static int feedQueue(byte[] byteArray, + int startByteArrayIndex, + PowerQueue bitQueue) { + LOG.traceStartOfMethod(null, "feedQueue", "byteArray", Arrays.asList(byteArray).toString(), "bitQueue", bitQueue.toString()); + int index = startByteArrayIndex; + while (index < byteArray.length && bitQueue.size() >= 8) { + + boolean[] booleanArray = new boolean[]{bitQueue.poll(), bitQueue.poll(), bitQueue.poll(), bitQueue.poll(), bitQueue.poll(), bitQueue.poll(), bitQueue.poll(), bitQueue.poll()}; +// System.out.println("feeding with "+(byteInstance.getByteValue()+128)); + byteArray[index] = (byte) (Byte.booleanArrayToByte(booleanArray) + 128); + index++; + + } + startByteArrayIndex = index; + return startByteArrayIndex; + } +} diff --git a/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/OkayBase64Encoder.java b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/OkayBase64Encoder.java new file mode 100644 index 0000000..41bc5b8 --- /dev/null +++ b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/OkayBase64Encoder.java @@ -0,0 +1,87 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.io.bit.base64; + +import org.nanoboot.powerframework.collections.PowerQueue; +import org.nanoboot.powerframework.io.bit.Byte; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +class OkayBase64Encoder { + + /** + * + * @param byteArrayIn + * + * @return + */ + public static String encode(byte[] byteArrayIn) { + StringBuilder stringBuilder = new StringBuilder(); + Base64Padding base64Padding = Base64Padding.getBase64Padding(byteArrayIn); + + iterateBytes(byteArrayIn, stringBuilder); + stringBuilder.append(base64Padding.getPadding()); + return stringBuilder.toString(); + } + + private static void iterateBytes(byte[] byteArrayIn, + StringBuilder stringBuilder) { + PowerQueue bitQueue = new PowerQueue<>(); + + for (int i = 0; i < byteArrayIn.length; i++) { + processByteToQueue(byteArrayIn[i], bitQueue); + feedQueue(bitQueue, stringBuilder); + + } + if(bitQueue.size() > 0) { + while (bitQueue.size() < 6) { + bitQueue.add(false); + } + feedQueue(bitQueue, stringBuilder); + } + } + + private static void processByteToQueue(byte byteValue, + PowerQueue bitQueue) { + boolean[] booleanArray = Byte.byteValueToBooleanArray(byteValue); + for (boolean element : booleanArray) { + //System.out.print(element ? "1" : "0"); + bitQueue.add(element); + } + } + + private static void feedQueue(PowerQueue bitQueue, + StringBuilder stringBuilder) { + while (bitQueue.size() >= 6) { + + byte byteValue = Byte.booleanArrayToByte(bitQueue.poll(), bitQueue.poll(), bitQueue.poll(), bitQueue.poll(), bitQueue.poll(), bitQueue.poll()); + stringBuilder.append(Base64Convertor.byteToChar(byteValue)); + + } + } + + private OkayBase64Encoder() { + } +} diff --git a/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/package-info.java b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/package-info.java new file mode 100644 index 0000000..fd5bb32 --- /dev/null +++ b/power-io/src/main/java/org/nanoboot/powerframework/io/bit/base64/package-info.java @@ -0,0 +1,29 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * Package with utilities used to convert byte array to base64 string representation and vice versa + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +package org.nanoboot.powerframework.io.bit.base64; diff --git a/power-io/src/main/java/org/nanoboot/powerframework/io/fs/BinaryFile.java b/power-io/src/main/java/org/nanoboot/powerframework/io/fs/BinaryFile.java new file mode 100644 index 0000000..1ce88d8 --- /dev/null +++ b/power-io/src/main/java/org/nanoboot/powerframework/io/fs/BinaryFile.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.io.fs; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class BinaryFile { + +} diff --git a/power-io/src/main/java/org/nanoboot/powerframework/io/fs/Directory.java b/power-io/src/main/java/org/nanoboot/powerframework/io/fs/Directory.java new file mode 100644 index 0000000..e1405e5 --- /dev/null +++ b/power-io/src/main/java/org/nanoboot/powerframework/io/fs/Directory.java @@ -0,0 +1,41 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.io.fs; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Directory { + + /** + * + * @param name directory name Example:MyDocuments + * @param location directory location Example:/John/work/2017 + */ + public Directory(String name, + String location) { + + } +} diff --git a/power-io/src/main/java/org/nanoboot/powerframework/io/fs/Disk.java b/power-io/src/main/java/org/nanoboot/powerframework/io/fs/Disk.java new file mode 100644 index 0000000..fe42ea6 --- /dev/null +++ b/power-io/src/main/java/org/nanoboot/powerframework/io/fs/Disk.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.io.fs; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Disk { + +} diff --git a/power-io/src/main/java/org/nanoboot/powerframework/io/fs/File.java b/power-io/src/main/java/org/nanoboot/powerframework/io/fs/File.java new file mode 100644 index 0000000..6716eea --- /dev/null +++ b/power-io/src/main/java/org/nanoboot/powerframework/io/fs/File.java @@ -0,0 +1,35 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.io.fs; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class File { + + private static final String ROOTFOLDER = "FILESYSTEM"; + String name; + String location; +} diff --git a/power-io/src/main/java/org/nanoboot/powerframework/io/fs/FileSystem.java b/power-io/src/main/java/org/nanoboot/powerframework/io/fs/FileSystem.java new file mode 100644 index 0000000..7f2f2e5 --- /dev/null +++ b/power-io/src/main/java/org/nanoboot/powerframework/io/fs/FileSystem.java @@ -0,0 +1,85 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.io.fs; + +import java.io.UnsupportedEncodingException; +import java.net.URISyntaxException; +import java.net.URLDecoder; +import java.security.CodeSource; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class FileSystem { + + private static final FileSystem defaultFileSystem = null; + + /** + * + * @param defaultFileSystemArg default file system + */ + public static void setDefaultFileSystem(FileSystem defaultFileSystemArg) { + } + + /** + * + * @param aclass Class instance + * + * @return path to the class file + */ + public static String getJarContainingFolder(Class aclass) { + CodeSource codeSource = aclass.getProtectionDomain().getCodeSource(); + java.io.File jarFile = null; + if(codeSource.getLocation() != null) { + try { + jarFile = new java.io.File(codeSource.getLocation().toURI()); + } catch (URISyntaxException ex) { + Logger.getLogger(FileSystem.class.getName()).log(Level.SEVERE, null, ex); + } + } else { + String path = aclass.getResource(aclass.getSimpleName() + ".class").getPath(); + String jarFilePath = path.substring(path.indexOf(':') + 1, path.indexOf('!')); + try { + jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8"); + } catch (UnsupportedEncodingException ex) { + Logger.getLogger(FileSystem.class.getName()).log(Level.SEVERE, null, ex); + } + jarFile = new java.io.File(jarFilePath); + } + return jarFile.getParentFile().getAbsolutePath(); + } + private final String location; + + /** + * + * @param locationIn path to the root folder of this abstract file system + */ + public FileSystem(String locationIn) { + this.location = locationIn; + } + +} diff --git a/power-io/src/main/java/org/nanoboot/powerframework/io/fs/FileType.java b/power-io/src/main/java/org/nanoboot/powerframework/io/fs/FileType.java new file mode 100644 index 0000000..4b22f19 --- /dev/null +++ b/power-io/src/main/java/org/nanoboot/powerframework/io/fs/FileType.java @@ -0,0 +1,41 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.io.fs; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public enum FileType { + + /** + * + */ + DIRECTORY, + + /** + * + */ + BYTEARRAY; +} diff --git a/power-io/src/main/java/org/nanoboot/powerframework/io/fs/PowerFileSystem.java b/power-io/src/main/java/org/nanoboot/powerframework/io/fs/PowerFileSystem.java new file mode 100644 index 0000000..95525a9 --- /dev/null +++ b/power-io/src/main/java/org/nanoboot/powerframework/io/fs/PowerFileSystem.java @@ -0,0 +1,66 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.io.fs; + +import org.nanoboot.powerframework.core.PowerObject; + +/** + * Here goes the description of this class. + * + * @author Robert Vokac + * @since 0.0.0 + * + */ +public class PowerFileSystem extends PowerObject { + + /** + * Constant description + */ + private static final String CONSTANT = "constant"; + + /** + * Field description + */ + private String name; + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private PowerFileSystem() { + } + + /** + * Constructor + * + * Constructor description + * + * @param nameIn + */ + public PowerFileSystem(String nameIn) { + this.name = nameIn; + } + + + + +} diff --git a/power-io/src/main/java/org/nanoboot/powerframework/io/fs/TextFile.java b/power-io/src/main/java/org/nanoboot/powerframework/io/fs/TextFile.java new file mode 100644 index 0000000..f8511ec --- /dev/null +++ b/power-io/src/main/java/org/nanoboot/powerframework/io/fs/TextFile.java @@ -0,0 +1,31 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.io.fs; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class TextFile { + +} diff --git a/power-io/src/main/java/org/nanoboot/powerframework/io/fs/virtualfilesystem/.gitkeep b/power-io/src/main/java/org/nanoboot/powerframework/io/fs/virtualfilesystem/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-io/src/main/resources/.gitkeep b/power-io/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-io/src/test/java/org/nanoboot/powerframework/io/bit/BlobTest.java b/power-io/src/test/java/org/nanoboot/powerframework/io/bit/BlobTest.java new file mode 100644 index 0000000..641a7de --- /dev/null +++ b/power-io/src/test/java/org/nanoboot/powerframework/io/bit/BlobTest.java @@ -0,0 +1,418 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.io.bit; + +import org.nanoboot.powerframework.random.generators.linearcongruent.combined.w5.W5RandomGenerator; +import org.junit.*; +import static org.junit.Assert.*; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class BlobTest { + + public BlobTest() { + } + + @BeforeClass + public static void setUpClass() { + } + + @AfterClass + public static void tearDownClass() { + } + + @Before + public void setUp() { + } + + @After + public void tearDown() { + } + + /** + * Test of fillAllByZeroes method, of class Blob. + */ + @Test + public void testBlobString() { + + //arrange + Blob blob = new Blob(10); + blob.fillRandom(); + Blob blob2; + String expectedString = blob.toString(); + String returnedString; + //act + blob2 = new Blob(expectedString); + returnedString = blob2.toString(); + //assert + System.out.println(expectedString); + System.out.println(returnedString); + assertTrue(expectedString.equals(returnedString)); + } + + /** + * Test of fillAllByZeroes method, of class Blob. + */ + @Test + public void testFillAllByZeroes() { + + //arrange + Blob blob = new Blob(2); + String expectedString = "0000000000000000"; + String returnedString; + //act + returnedString = blob.toString(); + //assert + assertTrue(expectedString.equals(returnedString)); + } + + /** + * Test of fillAllByZeroes method, of class Blob. + */ + @Test + public void testFillAllByZeroes2() { + //arrange + Blob blob = new Blob(2); + blob.fillRandom(); + blob.fillAllByZeroes(); + String expectedString = "0000000000000000"; + String returnedString; + //act + returnedString = blob.toString(); + //assert + assertTrue(expectedString.equals(returnedString)); + } + + /** + * Test of fillAllByOnes method, of class Blob. + */ + @Test + public void testFillAllByOnes() { + //arrange + Blob blob = new Blob(2); + blob.fillAllByOnes(); + String expectedString = "1111111111111111"; + String returnedString; + //act + returnedString = blob.toString(); + //assert + assertTrue(expectedString.equals(returnedString)); + } + + /** + * Test of fillAllByOnes method, of class Blob. + */ + @Test + public void testFillAllByOnes2() { + //arrange + Blob blob = new Blob(2); + blob.fillRandom(); + blob.fillAllByOnes(); + String expectedString = "1111111111111111"; + String returnedString; + //act + returnedString = blob.toString(); + //assert + assertTrue(expectedString.equals(returnedString)); + } + + /** + * Test of fillRandom method, of class Blob. + */ + @Test + public void testFillRandom() { + //arrange + Blob blob = new Blob(2); + blob.fillRandom(); + blob.fillAllByOnes(); + String notExpectedString = "0000000000000000"; + String returnedString; + //act + returnedString = blob.toString(); + //assert + assertFalse(notExpectedString.equals(returnedString)); + } + + /** + * Test of getByte method, of class Blob. + */ + @Test + public void testGetByte() { + //arrange + Blob blob = new Blob(5); + + boolean[] expectedArray = new boolean[]{true, false, false, false, true, true, false, true}; + boolean[] returnedArray; + blob.setByte(2, new boolean[]{true, false, false, false, true, true, false, true}); + //act + + returnedArray = blob.getByte(2); + //assert + assertArrayEquals(expectedArray, returnedArray); + } + + /** + * Test of setByte method, of class Blob. + */ + @Test + public void testSetByte() { + //arrange + Blob blob = new Blob(5); + + String expectedString = "0000000000000000100011010000000000000000"; + String returnedString; + //act + blob.setByte(2, new boolean[]{true, false, false, false, true, true, false, true}); + returnedString = blob.toString(); + //assert + assertTrue(expectedString.equals(returnedString)); + } + + /** + * Test of getBits method, of class Blob. + */ + @Test + public void testGetBits() { + //arrange + Blob blob = new Blob(2); + blob.setByte(0, new boolean[]{true, true, false, true, false, true, true, false}); + blob.setByte(1, new boolean[]{false, true, true, false, false, false, true, false}); + + boolean[] expectedArray = new boolean[]{true, false, false, true, true, false}; + boolean[] returnedArray; + + //act + returnedArray = blob.getBits(6, 11); + //assert + assertArrayEquals(expectedArray, returnedArray); + } + + /** + * Test of getBits method, of class Blob. + */ + @Test + public void testGetBits2() { + //arrange + Blob blob = new Blob(4); + blob.setByte(0, new boolean[]{true, true, false, true, false, true, true, false}); + blob.setByte(1, new boolean[]{false, true, true, false, false, false, true, false}); + blob.setByte(2, new boolean[]{true, false, true, true, false, true, false, false}); + blob.setByte(3, new boolean[]{false, true, false, true, false, true, false, true}); + + boolean[] expectedArray = new boolean[]{false, true, true, false, true, false, false, false, true}; + boolean[] returnedArray; + + //act + returnedArray = blob.getBits(17, 25); + //assert + assertArrayEquals(expectedArray, returnedArray); + } + + /** + * Test of getBits method, of class Blob. + */ + @Test + public void testSetBits() { + //arrange + Blob blob = new Blob(4); + blob.fillAllByZeroes(); + + boolean[] expectedArray = new boolean[]{false, true, true, false, true, false, false, false, true}; + boolean[] returnedArray; + + //act + blob.setBits(17, new boolean[]{false, true, true, false, true, false, false, false, true}); + + returnedArray = blob.getBits(17, 25); + + //assert + assertArrayEquals(expectedArray, returnedArray); + } + + /** + * Test of getBits method, of class Blob. + */ + @Test + public void testSetBits2() { + + W5RandomGenerator pseudoW5RandomGenerator = W5RandomGenerator.getStaticInstance(); + + for (int i = 0; i < 10; i++) { + //System.out.println("Iteration number " + i); + //arrange + Blob blob = new Blob(4); + + boolean[] randomBooleanArray = new boolean[8]; + + for (int j = 0; j < 8; j++) { + randomBooleanArray[j] = pseudoW5RandomGenerator.nextBoolean(); + } + //act + String randomBooleanArrayAsString = new Blob(new byte[]{Byte.booleanArrayToByte(randomBooleanArray)}).toString(); + //System.out.println("Random boolean array is " + randomBooleanArrayAsString); + int startBit = pseudoW5RandomGenerator.nextInt(0, 24); + //System.out.println("Start bit is " + startBit); + blob.setBits(startBit, randomBooleanArray); + //System.out.println("The blob is now: "); + String blobAsString = blob.toString(); + for (int k = 0; k < blobAsString.length(); k++) { + + //System.out.print(blobAsString.charAt(k)); + if((k + 1) % 8 == 0) { + //System.out.println(); + } + } + String blobAsStringSubstring = blobAsString.substring(startBit, startBit + 8); + //System.out.println("blobAsStringSubstring=" + blobAsStringSubstring); + //System.out.println("randomBooleanArrayAsString=" + randomBooleanArrayAsString); + //assert + assertArrayEquals(randomBooleanArrayAsString.toCharArray(), blobAsStringSubstring.toCharArray()); + } + + } + + /** + * Test of toString method, of class Blob. + */ + @Test + public void testToString() { + //arrange + boolean[][] booleanArrays = new boolean[][]{{false, true, true, false, true, false, false, false}, {true, true, false, true, false, true, false, true}}; + Blob blob = new Blob(2); + + String expectedString = "0110100011010101"; + String returnedString; + + //act + blob.setByte(0, booleanArrays[0]); + blob.setByte(1, booleanArrays[1]); + + returnedString = blob.toString(); + + //assert + assertEquals(expectedString, returnedString); + } + +// +// /** +// * Test of flopAll method, of class Blob. +// */ +// @Test +// public void testFlopAll() { +// //arrange +// Blob blob = new Blob(2); +// +// String expectedString = "1111111111111111"; +// String returnedString; +// +// //act +// blob.flopAll(); +// +// returnedString = blob.toString(); +// +// //assert +// assertArrayEquals(expectedString.toCharArray(), returnedString.toCharArray()); +// } +// +// /** +// * Test of flopAll method, of class Blob. +// */ +// @Test +// public void testFlopAll2() { +// //arrange +// Blob blob = new Blob(2); +// +// String expectedString = "0000000000000000"; +// String returnedString; +// +// //act +// blob.fillAllByOnes(); +// blob.flopAll(); +// +// returnedString = blob.toString(); +// +// //assert +// assertArrayEquals(expectedString.toCharArray(), returnedString.toCharArray()); +// } +// +// /** +// * Test of flopAll method, of class Blob. +// */ +// @Test +// public void testFlopAll3() { +// //arrange +// Blob blob = new Blob("0100100101010001"); +// String expectedString = "1011011010101110"; +// String returnedString; +// +// //act +// blob.flopAll(); +// +// returnedString = blob.toString(); +// +// //assert +// assertArrayEquals(expectedString.toCharArray(), returnedString.toCharArray()); +// } + +// /** +// * Test of flop method, of class Blob. +// */ +// @Test +// public void testFlop() { +// //arrange +// Blob blob = new Blob("0100100101010001"); +// String expectedString = "1011011001010001"; +// String returnedString; +// +// //act +// blob.flop(0, 0); +// +// returnedString = blob.toString(); +// System.out.println("###\n" + expectedString + "\n" + returnedString); +// +// //assert +// assertArrayEquals(expectedString.toCharArray(), returnedString.toCharArray()); +// } + /** + * Test of flopBooleanArray method, of class Blob. + */ + @Test + public void testFlopBooleanArray() { + //arrange + + boolean[] booleanArray = new boolean[]{true, true, false, true, false, true, true, false}; + Blob blob = new Blob(Byte.booleanArrayToByte(booleanArray)); + + boolean[] expectedArray = new boolean[]{false, false, true, false, true, false, false, true}; + boolean[] returnedArray; + + //act + returnedArray = Blob.flopBooleanArray(booleanArray); + //assert + assertArrayEquals(expectedArray, returnedArray); + } + +} diff --git a/power-io/src/test/java/org/nanoboot/powerframework/io/bit/ByteTest.java b/power-io/src/test/java/org/nanoboot/powerframework/io/bit/ByteTest.java new file mode 100644 index 0000000..ed74611 --- /dev/null +++ b/power-io/src/test/java/org/nanoboot/powerframework/io/bit/ByteTest.java @@ -0,0 +1,204 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.io.bit; + +import java.util.Arrays; +import org.junit.*; +import static org.junit.Assert.*; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class ByteTest { + + public ByteTest() { + } + + @BeforeClass + public static void setUpClass() { + } + + @AfterClass + public static void tearDownClass() { + } + + @Before + public void setUp() { + } + + @After + public void tearDown() { + } + + /** + * Test of getByteValue method, of class Byte. + */ + @Test + public void testBooleanArrayToByte() { + //arrange + boolean[] booleanArray = new boolean[]{false, false, false, false, false, false, false, false}; + byte expectedValue = -128; + int returnedValue; + //act + returnedValue = Byte.booleanArrayToByte(booleanArray); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getByteValue method, of class Byte. + */ + @Test + public void testBooleanArrayToByte2() { + //arrange + boolean[] booleanArray = new boolean[]{false, false, false, false, false, false, false, true}; + byte expectedValue = -127; + int returnedValue; + //act + returnedValue = Byte.booleanArrayToByte(booleanArray); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getByteValue method, of class Byte. + */ + @Test + public void testBooleanArrayToByte3() { + //arrange + boolean[] booleanArray = new boolean[]{true, true, true, true, true, true, true, true}; + byte expectedValue = 127; + int returnedValue; + //act + returnedValue = Byte.booleanArrayToByte(booleanArray); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getBooleanArray method, of class Byte. + */ + @Test + public void testByteValueToBooleanArray() { + byte byteValue = -128; + boolean[] expectedValue = new boolean[]{false, false, false, false, false, false, false, false}; + boolean[] returnedValue; + //act + returnedValue = Byte.byteValueToBooleanArray(byteValue); + //assert + System.out.println(Arrays.toString(returnedValue)); + Assert.assertArrayEquals(expectedValue, returnedValue); + } + + /** + * Test of getBooleanArray method, of class Byte. + */ + @Test + public void testByteValueToBooleanArray2() { + byte byteValue = -127; + boolean[] expectedValue = new boolean[]{false, false, false, false, false, false, false, true}; + boolean[] returnedValue; + //act + returnedValue = Byte.byteValueToBooleanArray(byteValue); + //assert + + Assert.assertArrayEquals(expectedValue, returnedValue); + } + + /** + * Test of getBooleanArray method, of class Byte. + */ + @Test + public void testByteValueToBooleanArray3() { + byte byteValue = -124; + boolean[] expectedValue = new boolean[]{false, false, false, false, false, true, false, false}; + boolean[] returnedValue; + //act + returnedValue = Byte.byteValueToBooleanArray(byteValue); + //assert + + Assert.assertArrayEquals(expectedValue, returnedValue); + } + + /** + * Test of getBooleanArray method, of class Byte. + */ + @Test + public void testByteValueToBooleanArray4() { + byte byteValue = 0; + boolean[] expectedValue = new boolean[]{true, false, false, false, false, false, false, false}; + boolean[] returnedValue; + //act + returnedValue = Byte.byteValueToBooleanArray(byteValue); + //assert + + Assert.assertArrayEquals(expectedValue, returnedValue); + } + + /** + * Test of getBooleanArray method, of class Byte. + */ + @Test + public void testByteValueToBooleanArray5() { + byte byteValue = 1; + boolean[] expectedValue = new boolean[]{true, false, false, false, false, false, false, true}; + boolean[] returnedValue; + //act + returnedValue = Byte.byteValueToBooleanArray(byteValue); + //assert + + Assert.assertArrayEquals(expectedValue, returnedValue); + } + + /** + * Test of getBooleanArray method, of class Byte. + */ + @Test + public void testByteValueToBooleanArray6() { + byte byteValue = 126; + boolean[] expectedValue = new boolean[]{true, true, true, true, true, true, true, false}; + boolean[] returnedValue; + //act + returnedValue = Byte.byteValueToBooleanArray(byteValue); + //assert + + Assert.assertArrayEquals(expectedValue, returnedValue); + } + + /** + * Test of getBooleanArray method, of class Byte. + */ + @Test + public void testByteValueToBooleanArray7() { + byte byteValue = (byte) (127); + boolean[] expectedValue = new boolean[]{true, true, true, true, true, true, true, true}; + boolean[] returnedValue; + //act + returnedValue = Byte.byteValueToBooleanArray(byteValue); + //assert + + Assert.assertArrayEquals(expectedValue, returnedValue); + } +} diff --git a/power-json/pom.xml b/power-json/pom.xml new file mode 100644 index 0000000..4528518 --- /dev/null +++ b/power-json/pom.xml @@ -0,0 +1,62 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-json + jar + + Power Json + Json functionality for the Power library + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + org.nanoboot.powerframework + power-random + ${power.version} + + + org.nanoboot.powerframework + power-utils + ${power.version} + + + org.nanoboot.powerframework + power-collections + ${power.version} + + + + + diff --git a/power-json/src/main/java/module-info.java b/power-json/src/main/java/module-info.java new file mode 100644 index 0000000..6e7368c --- /dev/null +++ b/power-json/src/main/java/module-info.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +module powerframework.json { + exports org.nanoboot.powerframework.json; + requires java.logging; + requires powerframework.collections; + requires powerframework.core; +} diff --git a/power-json/src/main/java/org/nanoboot/powerframework/json/ArrayWithItemsSplitByComma.java b/power-json/src/main/java/org/nanoboot/powerframework/json/ArrayWithItemsSplitByComma.java new file mode 100644 index 0000000..b3b5cdf --- /dev/null +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/ArrayWithItemsSplitByComma.java @@ -0,0 +1,62 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +import java.util.*; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class ArrayWithItemsSplitByComma { + + /** + * Returns list of indexes of commas for the given indentation and the given + * String + * + * @param itemsSplitByComma + * @return + */ + static ArrayList getListWithItemsSplitByComma( + String itemsSplitByComma) { + ArrayWithItemsSplitByComma arrayWithItemsSplitByComma = new ArrayWithItemsSplitByComma(itemsSplitByComma); + return arrayWithItemsSplitByComma.arrayList; + } + + private final ArrayList arrayList = new ArrayList<>(); + + private ArrayWithItemsSplitByComma(final String itemsSplitByComma) { + ArrayList listOfCommas = CommasFinder.getListOfIndexesOfCommas(itemsSplitByComma); + int beginIndex = 0; + int endIndex; + for (int element : listOfCommas) { + endIndex = element; + arrayList.add(itemsSplitByComma.substring(beginIndex, endIndex).trim()); + beginIndex = ++endIndex; + } + endIndex = itemsSplitByComma.length(); + arrayList.add(itemsSplitByComma.substring(beginIndex, endIndex).trim()); + } + +} diff --git a/power-json/src/main/java/org/nanoboot/powerframework/json/CommasFinder.java b/power-json/src/main/java/org/nanoboot/powerframework/json/CommasFinder.java new file mode 100644 index 0000000..af031ca --- /dev/null +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/CommasFinder.java @@ -0,0 +1,92 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +import java.util.*; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +class CommasFinder { + + private static boolean nestingWillBeIncreased(char charToCheck) { + return (charToCheck == JsonConstants.OBJECTSTART) || (charToCheck == JsonConstants.ARRAYSTART); + } + + private static boolean nestingWillBeDecreased(char charToCheck) { + return (charToCheck == JsonConstants.OBJECTEND) || (charToCheck == JsonConstants.ARRAYEND); + } + + static ArrayList getListOfIndexesOfCommas(final String string) { + CommasFinder commasFinder = new CommasFinder(string); + return commasFinder.listOfCommas; + } + + private final ArrayList listOfCommas = new ArrayList<>(); + private int nesting = 0; + private char currentChar; + private int charIndex; + private final String string; + + private CommasFinder(final String string) { + this.string = string; + //System.out.println(string); + for (charIndex = 0; charIndex < string.length(); charIndex++) { + updateCurrentChar(); + //System.out.println(string.charAt(charIndex)); + skipStringIfNecessarily(); + + if ((currentChar == JsonConstants.COMMA) && (nesting == 0)) { + //System.out.println("přidání"); + listOfCommas.add(charIndex); + } + if (nestingWillBeIncreased(currentChar)) { + nesting++; + } + if (nestingWillBeDecreased(currentChar)) { + nesting--; + } + + } + } + + private void skipStringIfNecessarily() { + + if ((currentChar == JsonConstants.APOSTROPHE) && (nesting == 0)) { + //System.out.println("skok"); + charIndex++;//NOSONAR + updateCurrentChar(); + while (JsonConstants.APOSTROPHE != currentChar) { + charIndex++;//NOSONAR + updateCurrentChar(); + } + } + } + + private void updateCurrentChar() { + currentChar = string.charAt(charIndex); + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonArray.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonArray.java similarity index 56% rename from src/main/java/org/nanoboot/powerframework/json/JsonArray.java rename to power-json/src/main/java/org/nanoboot/powerframework/json/JsonArray.java index 93ee6c9..ec7d534 100644 --- a/src/main/java/org/nanoboot/powerframework/json/JsonArray.java +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonArray.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -21,20 +21,21 @@ package org.nanoboot.powerframework.json; import java.util.ArrayList; -import org.nanoboot.powerframework.PowerRuntimeException; /** * Represents json array. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public class JsonArray { +//TODO implement serializable interface private ArrayList arrayList = new ArrayList<>(); /** * Constructor - * + *

* Used to create empty jsonObject. */ public JsonArray() { @@ -43,38 +44,41 @@ public class JsonArray { /** * Constructor - * + *

* From String creates json array. * * @param stringRepresentationOfThisJsonArray */ - public JsonArray(String stringRepresentationOfThisJsonArray) { + public JsonArray(final String stringRepresentationOfThisJsonArray) { JsonArrayParser.parseStringToJsonArray(this, stringRepresentationOfThisJsonArray); } /** - * * @return count of items of this json array. */ - public int getCountOfItems() { + public int size() { return this.arrayList.size(); } /** - * * @return result of this control */ public boolean isEmpty() { return this.arrayList.isEmpty(); } + public void clear() { + this.arrayList.clear(); + } + /** * New value is added- object is converted to the most suitable json value * type and is set as the new value. * * @param object + * @return */ - public void add(Object object) {//NOSONAR + public JsonArray add(Object object) {//NOSONAR if (object == null) { addNull(); } else { @@ -107,31 +111,41 @@ public class JsonArray { addDouble((double) object); break; default: - throw new PowerRuntimeException("I can't add the given object as value."); + throw new JsonException(object.getClass().getName() + " I can't add the given object (" + object.getClass().getName() + ") as value."); } } + return this; + } + + void addJsonValue(JsonValue jsonValue) { + this.arrayList.add(jsonValue); } /** * Adds null. + * + * @return */ - public void addNull() { + public JsonArray addNull() { this.arrayList.add(new JsonValue()); + return this; } /** * Adds json object. * - * @param value + * @param value value to use + * @return */ - public void addObject(JsonObject value) { + public JsonArray addObject(JsonObject value) { this.arrayList.add(new JsonValue(value)); + return this; } /** * Adds json array. * - * @param value + * @param value value to use * @return */ public JsonArray addArray(JsonArray value) {//this @@ -142,79 +156,91 @@ public class JsonArray { /** * Adds boolean. * - * @param value + * @param value value to use + * @return */ - public void addBoolean(boolean value) { - this.arrayList.add(new JsonValue(new JsonBoolean(value))); + public JsonArray addBoolean(boolean value) { + this.arrayList.add(new JsonValue(value)); + return this; } /** * Adds String. * - * @param value + * @param value value to use * @return */ - public JsonArray addString(String value) { - this.arrayList.add(new JsonValue(new JsonString(value))); + public JsonArray addString(final String value) { + this.arrayList.add(new JsonValue(value)); return this; } /** * Adds char. * - * @param value + * @param value value to use + * @return */ - public void addChar(char value) { - this.arrayList.add(new JsonValue(new JsonChar(value))); + public JsonArray addChar(char value) { + this.arrayList.add(new JsonValue(value)); + return this; } /** * Adds int. * - * @param value + * @param value value to use + * @return */ - public void addInt(int value) { - this.arrayList.add(new JsonValue(new JsonInt(value))); + public JsonArray addInt(int value) { + this.arrayList.add(new JsonValue(value)); + return this; } /** * Adds long. * - * @param value + * @param value value to use + * @return */ - public void addLong(long value) { - this.arrayList.add(new JsonValue(new JsonLong(value))); + public JsonArray addLong(long value) { + this.arrayList.add(new JsonValue(value)); + return this; } /** * Adds float. * - * @param value + * @param value value to use + * @return */ - public void addFloat(float value) { - this.arrayList.add(new JsonValue(new JsonFloat(value))); + public JsonArray addFloat(float value) { + this.arrayList.add(new JsonValue(value)); + return this; } /** * Adds double. * - * @param value + * @param value value to use + * @return */ - public void addDouble(double value) { - this.arrayList.add(new JsonValue(new JsonDouble(value))); + public JsonArray addDouble(double value) { + this.arrayList.add(new JsonValue(value)); + return this; } /** - * * @param index * @return json value type of the value at the given index */ public JsonValueType getJsonValueType(int index) { - return this.arrayList.get(index).getJsonValueType(); + return this.arrayList + .get(index) + .getJsonValueType(); } /** - * * @param index * @return JsonObject */ @@ -223,7 +249,6 @@ public class JsonArray { } /** - * * @param index * @return JsonArraz */ @@ -232,155 +257,167 @@ public class JsonArray { } /** - * * @param index * @return boolean */ public boolean getBoolean(int index) { - return this.arrayList.get(index).getJsonBoolean().getBoolean(); + return this.arrayList.get(index).getJsonBoolean(); } /** - * * @param index * @return String */ public String getString(int index) { - return this.arrayList.get(index).getJsonString().getString(); + return this.arrayList.get(index).getJsonString(); } /** - * * @param index * @return char */ public char getChar(int index) { - return this.arrayList.get(index).getJsonChar().getChar(); + return this.arrayList.get(index).getJsonChar(); } /** - * * @param index * @return int */ public int getInt(int index) { - return this.arrayList.get(index).getJsonInt().getInt(); + return this.arrayList.get(index).getJsonInt(); } /** - * * @param index * @return long */ public long getLong(int index) { - return this.arrayList.get(index).getJsonLong().getLong(); + return this.arrayList.get(index).getJsonLong(); } /** - * * @param index * @return float */ public float getFloat(int index) { - return this.arrayList.get(index).getJsonFloat().getFloat(); + return this.arrayList.get(index).getJsonFloat(); } /** - * * @param index * @return double */ public double getDouble(int index) { - return this.arrayList.get(index).getJsonDouble().getDouble(); + return this.arrayList.get(index).getJsonDouble(); } /** - * * @param index to be updated + * @return */ - public void updateNull(int index) { + public JsonArray updateNull(int index) { this.arrayList.set(index, new JsonValue()); + return this; } /** - * * @param index - * @param value to be updated + * @param value value to use to be updated + * @return */ - public void updateObject(int index, JsonObject value) { + public JsonArray updateObject(int index, + JsonObject value) { this.arrayList.set(index, new JsonValue(value)); + return this; } /** - * * @param index - * @param value to be updated + * @param value value to use to be updated + * @return */ - public void updateArray(int index, JsonArray value) { + public JsonArray updateArray(int index, + JsonArray value) { this.arrayList.set(index, new JsonValue(value)); + return this; } /** - * * @param index - * @param value to be updated + * @param value value to use to be updated + * @return */ - public void updateBoolean(int index, boolean value) { - this.arrayList.set(index, new JsonValue(new JsonBoolean(value))); + public JsonArray updateBoolean(int index, + boolean value) { + this.arrayList.set(index, new JsonValue(value)); + return this; } /** - * * @param index - * @param value to be updated + * @param value value to use to be updated + * @return */ - public void updateString(int index, String value) { - this.arrayList.set(index, new JsonValue(new JsonString(value))); + public JsonArray updateString(int index, + String value) { + this.arrayList.set(index, new JsonValue(value)); + return this; } /** - * * @param index - * @param value to be updated + * @param value value to use to be updated + * @return */ - public void updateChar(int index, char value) { - this.arrayList.set(index, new JsonValue(new JsonChar(value))); + public JsonArray updateChar(int index, + char value) { + this.arrayList.set(index, new JsonValue(value)); + return this; } /** - * * @param index - * @param value to be updated + * @param value value to use to be updated + * @return */ - public void updateInt(int index, int value) { - this.arrayList.set(index, new JsonValue(new JsonInt(value))); + public JsonArray updateInt(int index, + int value) { + this.arrayList.set(index, new JsonValue(value)); + return this; } /** - * * @param index - * @param value to be updated + * @param value value to use to be updated + * @return */ - public void updateLong(int index, long value) { - this.arrayList.set(index, new JsonValue(new JsonLong(value))); + public JsonArray updateLong(int index, + long value) { + this.arrayList.set(index, new JsonValue(value)); + return this; } /** - * * @param index - * @param value to be updated + * @param value value to use to be updated + * @return */ - public void updateFloat(int index, float value) { - this.arrayList.set(index, new JsonValue(new JsonFloat(value))); + public JsonArray updateFloat(int index, + float value) { + this.arrayList.set(index, new JsonValue(value)); + return this; } /** - * * @param index - * @param value to be updated + * @param value value to use to be updated + * @return */ - public void updateDouble(int index, double value) { - this.arrayList.set(index, new JsonValue(new JsonDouble(value))); + public JsonArray updateDouble(int index, + double value) { + this.arrayList.set(index, new JsonValue(value)); + return this; } /** @@ -396,8 +433,25 @@ public class JsonArray { return this.arrayList.get(index); } + boolean isJsonValueType(int index, + JsonValueType jsonValueType) { + return this.getJsonValueType(index) == jsonValueType; + } + + public String toString(JsonPrint jsonPrint) { + switch (jsonPrint) { + case MINIMAL: { + return toMinimalString(); + } + case PRETTY: { + return toPrettyString(); + } + default: + throw new JsonException("Unknown JsonPrint: " + jsonPrint); + } + } + /** - * * @return representation of this json array as minimal String */ public String toMinimalString() { @@ -405,7 +459,6 @@ public class JsonArray { } /** - * * @return representation of this json array as pretty String */ public String toPrettyString() { @@ -413,7 +466,6 @@ public class JsonArray { } /** - * * @return copy of this json array */ public JsonArray getCopy() { diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonArrayParser.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonArrayParser.java similarity index 59% rename from src/main/java/org/nanoboot/powerframework/json/JsonArrayParser.java rename to power-json/src/main/java/org/nanoboot/powerframework/json/JsonArrayParser.java index 063f0d3..a49ba25 100644 --- a/src/main/java/org/nanoboot/powerframework/json/JsonArrayParser.java +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonArrayParser.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -21,68 +21,66 @@ package org.nanoboot.powerframework.json; import java.util.ArrayList; -import org.nanoboot.powerframework.PowerRuntimeException; /** * Is used to create json arrays from Strings. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ class JsonArrayParser extends JsonParser { - /** - * Constructor - * - * Not meant to be instantiated. - */ - private JsonArrayParser() { - //Not meant to be instantiated. - } - /** * Parses String to empty json object. * - * @param jsonObject - * @param stringRepresentationOfJsonObject + * @param jsonArray + * @param stringRepresentationOfJsonArray * @return json object from parsed String */ - static JsonArray parseStringToJsonArray(JsonArray jsonArray, String stringRepresentationOfJsonArray) { + static JsonArray parseStringToJsonArray(JsonArray jsonArray, + String stringRepresentationOfJsonArray) { if (!jsonArray.isEmpty()) { - throw new PowerRuntimeException("I can't parse. The json array is not empty."); + throw new JsonException("I can't parse. The json array is not empty."); } String trimmedStringRepresentationOfJsonArray = stringRepresentationOfJsonArray.trim(); if (!isStringJsonArray(trimmedStringRepresentationOfJsonArray)) { - throw new PowerRuntimeException("I can't parse. The trimmed String does not start with [ or does not end with ]"); + throw new JsonException("I can't parse. The trimmed String does not start with [ or does not end with ]: " + trimmedStringRepresentationOfJsonArray); } String collectionsOfValuesOfTheJsonArrayString = deleteTheCharAtTheStartAndTheEnd(trimmedStringRepresentationOfJsonArray); if ("".equals(collectionsOfValuesOfTheJsonArrayString)) { return jsonArray; } + if ("".equals(collectionsOfValuesOfTheJsonArrayString.trim())) { + return jsonArray; + } fillJsonArrayWithParsedValues(jsonArray, collectionsOfValuesOfTheJsonArrayString); return jsonArray; } - private static boolean isStringJsonArray(String trimmedStringRepresentationOfJsonArray) { - return (getFirstCharOfTheString(trimmedStringRepresentationOfJsonArray) == JsonSpecialCharSequences.getArrayLeft()) && (getLastCharOfTheString(trimmedStringRepresentationOfJsonArray) == JsonSpecialCharSequences.getArrayRight()); + private static boolean isStringJsonArray( + String trimmedStringRepresentationOfJsonArray) { + return (getFirstCharOfTheString(trimmedStringRepresentationOfJsonArray) == JsonConstants.ARRAYSTART) && (getLastCharOfTheString(trimmedStringRepresentationOfJsonArray) == JsonConstants.ARRAYEND); } - private static void fillJsonArrayWithParsedValues(JsonArray jsonArray, String collectionsOfValuesOfTheJsonArrayString) { + private static void fillJsonArrayWithParsedValues(JsonArray jsonArray, + String collectionsOfValuesOfTheJsonArrayString) { + ArrayList array = ArrayWithItemsSplitByComma.getListWithItemsSplitByComma(collectionsOfValuesOfTheJsonArrayString); + for (final String element : array) { - ArrayList listOfCommas = getListOfIndexesOfTheStringWhereCharIsCommaAndNestingIsZero(collectionsOfValuesOfTheJsonArrayString); + JsonValue jsonValue = JsonValue.parseStringToJsonValue(element); - int beginIndex; - int indexOfComma = 0; - for (int i = 0; i < listOfCommas.size(); i++) { - beginIndex = ++indexOfComma; - indexOfComma = listOfCommas.get(i); - if (i == 0) { - beginIndex = 0; - } - String fraction = collectionsOfValuesOfTheJsonArrayString.substring(beginIndex, indexOfComma); - Object parsedObject = JsonParser.parseStringToValue(fraction); - jsonArray.add(parsedObject); + jsonArray.addJsonValue(jsonValue); } } + /** + * Constructor + *

+ * Not meant to be instantiated. + */ + private JsonArrayParser() { + //Not meant to be instantiated. + } + } diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonArrayPrinter.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonArrayPrinter.java similarity index 74% rename from src/main/java/org/nanoboot/powerframework/json/JsonArrayPrinter.java rename to power-json/src/main/java/org/nanoboot/powerframework/json/JsonArrayPrinter.java index dc15959..1d36b3f 100644 --- a/src/main/java/org/nanoboot/powerframework/json/JsonArrayPrinter.java +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonArrayPrinter.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -23,21 +23,12 @@ package org.nanoboot.powerframework.json; /** * Used to create String representation of a json array. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ class JsonArrayPrinter { /** - * Constructor - * - * Not meant to be instantiated. - */ - private JsonArrayPrinter() { - //Not meant to be instantiated. - } - - /** - * * @return representation of the json array as pretty String */ static String toMinimalString(JsonArray jsonArray) { @@ -45,7 +36,6 @@ class JsonArrayPrinter { } /** - * * @return representation of the json array as pretty String */ static String toPrettyString(JsonArray jsonArray) { @@ -54,34 +44,31 @@ class JsonArrayPrinter { } /** - * * @return representation of the json array as String */ - static String toString(JsonArray jsonArray, boolean printAsPrettyVersion) { + static String toString(JsonArray jsonArray, + boolean printAsPrettyVersion) { StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append(JsonSpecialCharSequences.getArrayLeft()); + stringBuilder.append(JsonConstants.ARRAYSTART); if (printAsPrettyVersion) { - stringBuilder.append(JsonSpecialCharSequences.getLineBreak()); + stringBuilder.append(JsonConstants.LINEBREAK); } int i = 0; String value; - while (i != jsonArray.getCountOfItems()) { - if (printAsPrettyVersion) { - value = jsonArray.getJsonValue(i).toPrettyString(); - } else { - value = jsonArray.getJsonValue(i).toMinimalString(); - } + while (i != jsonArray.size()) { + + value = printAsPrettyVersion ? jsonArray.getJsonValue(i).toPrettyString() : jsonArray.getJsonValue(i).toMinimalString(); if (printAsPrettyVersion) { if (!((jsonArray.getJsonValue(i).isArray()) || (jsonArray.getJsonValue(i).isObject()))) { - stringBuilder.append(JsonSpecialCharSequences.getTab()); + stringBuilder.append(JsonConstants.TAB); } else { value = JsonPrinter.addTabOnEveryLineStart(value); } } stringBuilder.append(value); - if ((i + 1) != jsonArray.getCountOfItems()) { + if ((i + 1) != jsonArray.size()) { stringBuilder.append(","); } if (printAsPrettyVersion) { @@ -89,10 +76,20 @@ class JsonArrayPrinter { } i++; } - stringBuilder.append(JsonSpecialCharSequences.getArrayRight()); + + stringBuilder.append(JsonConstants.ARRAYEND); return stringBuilder.toString(); } + /** + * Constructor + *

+ * Not meant to be instantiated. + */ + private JsonArrayPrinter() { + //Not meant to be instantiated. + } + } diff --git a/power-json/src/main/java/org/nanoboot/powerframework/json/JsonArraySerializable.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonArraySerializable.java new file mode 100644 index 0000000..b3e8f15 --- /dev/null +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonArraySerializable.java @@ -0,0 +1,45 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public interface JsonArraySerializable { + + /** + * Creates JsonArray representation of the instance + * of the class implementing this interface. + * + * @return JsonArray representation of the instance + * of the class implementing this interface + */ + JsonArray toJsonArray(); + /** + * Sets this object from a json array. + * @param jsonArray given json array + */ + void fromJsonArray(JsonArray jsonArray); +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonBoolean.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonBoolean.java similarity index 69% rename from src/main/java/org/nanoboot/powerframework/json/JsonBoolean.java rename to power-json/src/main/java/org/nanoboot/powerframework/json/JsonBoolean.java index f0b882f..f3a983e 100644 --- a/src/main/java/org/nanoboot/powerframework/json/JsonBoolean.java +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonBoolean.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -23,26 +23,19 @@ package org.nanoboot.powerframework.json; /** * Represents boolean json value. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ class JsonBoolean { - private final boolean value; - - JsonBoolean(boolean value) { - this.value = value; + static String toString(boolean value) { + return value ? JsonConstants.TRUE : JsonConstants.FALSE; } - boolean getBoolean() { - return this.value; - } - - @Override - public String toString() { - if (getBoolean()) { - return JsonSpecialCharSequences.getTrue(); - } else { - return JsonSpecialCharSequences.getFalse(); - } + /** + * Not meant to be instantiated. + */ + private JsonBoolean() { + //Not meant to be instantiated. } } diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonChar.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonChar.java similarity index 77% rename from src/main/java/org/nanoboot/powerframework/json/JsonChar.java rename to power-json/src/main/java/org/nanoboot/powerframework/json/JsonChar.java index 2b406e2..11247bc 100644 --- a/src/main/java/org/nanoboot/powerframework/json/JsonChar.java +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonChar.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -23,26 +23,23 @@ package org.nanoboot.powerframework.json; /** * Represents char json value. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ class JsonChar { - private final char value; - - JsonChar(char value) { - this.value = value; - } - - char getChar() { - return this.value; - } - - @Override - public String toString() { + static String toString(char value) { StringBuilder sb = new StringBuilder(); sb.append('\"'); - sb.append(Character.toString(getChar())); + sb.append(Character.toString(value)); sb.append('\"'); return sb.toString(); } + + /** + * Not meant to be instantiated. + */ + private JsonChar() { + //Not meant to be instantiated. + } } diff --git a/power-json/src/main/java/org/nanoboot/powerframework/json/JsonConstants.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonConstants.java new file mode 100644 index 0000000..12e305e --- /dev/null +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonConstants.java @@ -0,0 +1,48 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +/** + * Used to store char and String constants used to parse or print json objects + * or arrays. + * + * @author Robert Vokac + * @since 0.0.0 + */ +class JsonConstants { + + static final char OBJECTSTART = '{'; + static final char OBJECTEND = '}'; + static final char ARRAYSTART = '['; + static final char ARRAYEND = ']'; + static final char COMMA = ','; + static final char COLON = ':'; + static final char APOSTROPHE = '"'; + static final char LINEBREAK = '\n'; + static final String NULL = "null"; + static final String TRUE = "true"; + static final String FALSE = "false"; + static final String TAB = " "; + static final char SPACE = ' '; + + private JsonConstants() { + } +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonDouble.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonDouble.java similarity index 75% rename from src/main/java/org/nanoboot/powerframework/json/JsonDouble.java rename to power-json/src/main/java/org/nanoboot/powerframework/json/JsonDouble.java index 6822cd6..a791a17 100644 --- a/src/main/java/org/nanoboot/powerframework/json/JsonDouble.java +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonDouble.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -23,22 +23,19 @@ package org.nanoboot.powerframework.json; /** * Represents double json value. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ class JsonDouble { - private final double value; - - JsonDouble(double value) { - this.value = value; + static String toString(double value) { + return Double.toString(value); } - double getDouble() { - return this.value; - } - - @Override - public String toString() { - return Double.toString(getDouble()); + /** + * Not meant to be instantiated. + */ + private JsonDouble() { + //Not meant to be instantiated. } } diff --git a/power-json/src/main/java/org/nanoboot/powerframework/json/JsonException.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonException.java new file mode 100644 index 0000000..05ee387 --- /dev/null +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonException.java @@ -0,0 +1,41 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +import org.nanoboot.powerframework.core.PowerException; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class JsonException extends PowerException { + + /** + * @param message + */ + public JsonException(final String message) { + super(message); + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonFloat.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonFloat.java similarity index 75% rename from src/main/java/org/nanoboot/powerframework/json/JsonFloat.java rename to power-json/src/main/java/org/nanoboot/powerframework/json/JsonFloat.java index 88be199..8a170e9 100644 --- a/src/main/java/org/nanoboot/powerframework/json/JsonFloat.java +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonFloat.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -23,22 +23,19 @@ package org.nanoboot.powerframework.json; /** * Represents float json value. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ class JsonFloat { - private final float value; - - JsonFloat(float value) { - this.value = value; + static String toString(float value) { + return Float.toString(value); } - float getFloat() { - return this.value; - } - - @Override - public String toString() { - return Float.toString(getFloat()); + /** + * Not meant to be instantiated. + */ + private JsonFloat() { + //Not meant to be instantiated. } } diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonInt.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonInt.java similarity index 75% rename from src/main/java/org/nanoboot/powerframework/json/JsonInt.java rename to power-json/src/main/java/org/nanoboot/powerframework/json/JsonInt.java index 58fe21d..fd76fa0 100644 --- a/src/main/java/org/nanoboot/powerframework/json/JsonInt.java +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonInt.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -23,23 +23,20 @@ package org.nanoboot.powerframework.json; /** * Represents int json value. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ class JsonInt { - private final int value; - - JsonInt(int value) { - this.value = value; + static String toString(int value) { + return Integer.toString(value); } - int getInt() { - return this.value; - } - - @Override - public String toString() { - return Integer.toString(getInt()); + /** + * Not meant to be instantiated. + */ + private JsonInt() { + //Not meant to be instantiated. } } diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonLong.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonLong.java similarity index 75% rename from src/main/java/org/nanoboot/powerframework/json/JsonLong.java rename to power-json/src/main/java/org/nanoboot/powerframework/json/JsonLong.java index 93fa2ea..2e76f48 100644 --- a/src/main/java/org/nanoboot/powerframework/json/JsonLong.java +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonLong.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -23,22 +23,19 @@ package org.nanoboot.powerframework.json; /** * Represents long json value. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ class JsonLong { - private final long value; - - JsonLong(long value) { - this.value = value; + static String toString(long value) { + return Long.toString(value); } - long getLong() { - return this.value; - } - - @Override - public String toString() { - return Long.toString(getLong()); + /** + * Not meant to be instantiated. + */ + private JsonLong() { + //Not meant to be instantiated. } } diff --git a/power-json/src/main/java/org/nanoboot/powerframework/json/JsonObject.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonObject.java new file mode 100644 index 0000000..fd30579 --- /dev/null +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonObject.java @@ -0,0 +1,708 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +import org.nanoboot.powerframework.collections.PowerMap; +import org.nanoboot.powerframework.core.PowerObject; + + +import java.util.List; +import java.util.Map; + +/** + * Represents json object of json. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class JsonObject extends PowerObject { + /** + * Constant for Double. + */ + private static final String JAVALANG_DOUBLE = "java.lang.Double"; + /** + * Constant for double. + */ + private static final String JAVALANG_FLOAT = "java.lang.Float"; + /** + * Constant for Long. + */ + private static final String JAVALANG_LONG = "java.lang.Long"; + /** + * Constant for Integer. + */ + private static final String JAVALANG_INTEGER = "java.lang.Integer"; + /** + * Constant for Character. + */ + private static final String JAVALANG_CHARACTER = "java.lang.Character"; + /** + * Constant for String. + */ + private static final String JAVALANG_STRING = "java.lang.String"; + /** + * Constant for Boolean. + */ + private static final String JAVALANG_BOOLEAN = "java.lang.Boolean"; + /** + * Constant for JsonArray. + */ + private static final String POWERJSON_JSON_ARRAY = + "org.nanoboot.powerframework.json.JsonArray"; + /** + * Constant for JsonObject. + */ + private static final String POWERJSON_JSON_OBJECT = + "org.nanoboot.powerframework.json.JsonObject"; + /** + * Internal map. + */ + private final Map map = new PowerMap<>(); + /** + * Json validation schema. + */ + private JsonObject validationByJsonObject = null; + + /** + * Constructor + *

+ * Used to create empty jsonObject. + */ + public JsonObject() { + // Used to create empty jsonObject. + } + + //todo + // +// /** +// * Test of toJsonObject method, of class LinkedList. +// */ +// @Test +// public void testToJsonObject() { +// //arrange +// SingleLinkedList linkedList0 = new SingleLinkedList<>(); +// String expectedString = "{\"firstNode\":{\"key\":\"\",\"element\":\"Jack\",\"next\":{\"key\":\"\",\"element\":\"Anne\",\"next\":{\"key\":\"\",\"element\":\"John\",\"next\":{\"key\":\"\",\"element\":\"George\",\"next\":{\"key\":\"\",\"element\":\"Kate\",\"next\":null}}}}},\"lastNode\":{\"key\":\"\",\"element\":\"Kate\",\"next\":null}}"; +// String returnedString; +// //act +// linkedList0 +// ;linkedList.addAfterLast("Jack") +// ;linkedList.addAfterLast("Anne") +// ;linkedList.addAfterLast("John") +// ;linkedList.addAfterLast("George") +// ;linkedList.addAfterLast("Kate"); +// returnedString = linkedList0.toJsonObject().toMinimalString(); +// //assert +// assertEquals(expectedString, returnedString); +// +// } + + + + /** + * Constructor + *

+ * From String creates json object. + * + * @param textToParse json as text + */ + public JsonObject(final String textToParse) { + JsonObjectParser.parseStringToJsonObject(this, textToParse); + } + + /** + * @param jsonObject json validating schema + */ + public void setValidationJsonObject(final JsonObject jsonObject) { + if (this.validationByJsonObject == null) { + String msg = "The validation json object has been already set."; + throw new JsonException(msg); + } + this.validationByJsonObject = jsonObject; + } + + /** + * @return copy of validating json + */ + public JsonObject getValidationJsonObjectCopy() { + return this.validationByJsonObject.getCopy(); + } + + /** + * @return result of the validation + */ + public boolean validate() { + return false; + } + + /** + * @return count of items(keys and its values) of this json object + */ + public int size() { + return map.size(); + } + + /** + * @return result of this control + */ + public boolean isEmpty() { + return map.isEmpty(); + } + + /** + * Removes all values of this json object. + */ + public void clear() { + this.map.clear(); + } + + /** + * @param key key to use + * @return result of this control + */ + public boolean hasKey(final String key) { + return this.map.containsKey(key); + } + + /** + * Add to this json object new key, object is converted to the most suitable + * json value type and is set as value of the key. + * + * @param key key to use + * @param object object to use + * @return json object, which was added + */ + public JsonObject add(final String key, + final Object object) { + if (object == null) { + addNull(key); + } else { + switch (object.getClass().getName()) { + case POWERJSON_JSON_OBJECT: + addObject(key, (JsonObject) object); + break; + case POWERJSON_JSON_ARRAY: + addArray(key, (JsonArray) object); + break; + case JAVALANG_BOOLEAN: + addBoolean(key, (boolean) object); + break; + case JAVALANG_STRING: + addString(key, (String) object); + break; + case JAVALANG_CHARACTER: + addChar(key, (char) object); + break; + case JAVALANG_INTEGER: + addInt(key, (int) object); + break; + case JAVALANG_LONG: + addLong(key, (long) object); + break; + case JAVALANG_FLOAT: + addFloat(key, (float) object); + break; + case JAVALANG_DOUBLE: + addDouble(key, (double) object); + break; + default: + String msg = + object.getClass().getName() + + " I can't add the given object as value."; + throw new JsonException(msg); + } + } + return this; + } + + final void addJsonValue(final String key, + final JsonValue jsonValue) { + this.map.put(key, jsonValue); + } + + /** + * Add to this json object new key with null as value. + * + * @param key key to use + * @return this + */ + public JsonObject addNull(final String key) { + this.map.put(key, new JsonValue()); + return this; + } + + /** + * Add to this json object new key with json object as value. + * + * @param key key to use + * @param value value to use + * @return this + */ + public JsonObject addObject(final String key, + final JsonObject value) { + this.map.put(key, new JsonValue(value)); + return this; + } + + /** + * *Add to this json object new key with json array as value. + * + * @param key key to use + * @param value value to use + * @return this + */ + public JsonObject addArray(final String key, + final JsonArray value) { + this.map.put(key, new JsonValue(value)); + return this; + } + + /** + * Add to this json object new key with the value of the boolean as the + * value of the key. + * + * @param key key to use + * @param value value to use + * @return this + */ + public JsonObject addBoolean(final String key, + final boolean value) { + this.map.put(key, new JsonValue(value)); + return this; + } + + /** + * Add to this json object new key with the value of the String as the value + * of the key. + * + * @param key key to use + * @param value value to use + * @return this + */ + public JsonObject addString(final String key, + final String value) { + this.map.put(key, new JsonValue(value)); + return this; + } + + /** + * Add to this json object new key with the value of the char as the value + * of the key. + * + * @param key key to use + * @param value value to use + * @return this + */ + public JsonObject addChar(final String key, + final char value) { + this.map.put(key, new JsonValue(value)); + return this; + } + + /** + * Add to this json object new key with the value of the int as the value of + * the key. + * + * @param key key to use + * @param value value to use + * @return this + */ + public JsonObject addInt(final String key, + final int value) { + this.map.put(key, new JsonValue(value)); + return this; + } + + /** + * Add to this json object new key with the value of the long as the value + * of the key. + * + * @param key key to use + * @param value value to use + * @return this + */ + public JsonObject addLong(final String key, + final long value) { + this.map.put(key, new JsonValue(value)); + return this; + } + + /** + * Add to this json object new key with the value of the float as the value + * of the key. + * + * @param key key to use + * @param value value to use + * @return this + */ + public JsonObject addFloat(final String key, + final float value) { + this.map.put(key, new JsonValue(value)); + return this; + } + + /** + * Add to this json object new key with the value of the double as the value + * of the key. + * + * @param key key to use + * @param value value to use + * @return this + */ + public JsonObject addDouble(final String key, + final double value) { + this.map.put(key, new JsonValue(value)); + return this; + } + + public boolean isNull(final String key) { + return getJsonValueType(key) == JsonValueType.NULL; + } + /** + * @param key key to use + * @return value type of the value of the given key + */ + public JsonValueType getJsonValueType(final String key) { + return map.get(key).getJsonValueType(); + } + + final boolean isJsonValueType(final String key, + final JsonValueType jsonValueType) { + return this.getJsonValueType(key) == jsonValueType; + } + + /** + * @param key key to use + * @return object instance converted from the value of the given key + */ + public Object get(final String key) { + return map.get(key).toObject(); + } + + /** + * @param key key to use + * @return json object from the value of the given key + */ + public JsonObject getObject(final String key) { + return this.map.get(key).getJsonObject(); + } + + /** + * @param key key to use + * @return json array from the value of the given key + */ + public JsonArray getArray(final String key) { + return this.map.get(key).getJsonArray(); + } + + /** + * @param key key to use + * @return boolean from the value of the given key + */ + public boolean getBoolean(final String key) { + return this.map.get(key).getJsonBoolean(); + } + + /** + * @param key key to use + * @return String from the value of the given key + */ + public String getString(final String key) { + return this.map.get(key).getJsonString(); + } + + /** + * @param key key to use + * @return char from the value of the given key + */ + public char getChar(final String key) { + return this.map.get(key).getJsonChar(); + } + + /** + * @param key key to use + * @return int from the value of the given key + */ + public int getInt(final String key) { + return this.map.get(key).getJsonInt(); + } + + /** + * @param key key to use + * @return long from the value of the given key + */ + public long getLong(final String key) { + return this.map.get(key).getJsonLong(); + } + + /** + * @param key key to use + * @return float from the value of the given key + */ + public float getFloat(final String key) { + return this.map.get(key).getJsonFloat(); + } + + /** + * @param key key to use + * @return double from the value of the given key + */ + public double getDouble(final String key) { + return this.map.get(key).getJsonDouble(); + } + + /** + * Updates the value of the given key. + * + * @param key key to use + * @param object object to use + * @return this + */ + public JsonObject update(final String key, + final Object object) { + if (object == null) { + updateNull(key); + } else { + switch (object.getClass().getName()) { + case POWERJSON_JSON_OBJECT: + updateObject(key, (JsonObject) object); + break; + case POWERJSON_JSON_ARRAY: + updateArray(key, (JsonArray) object); + break; + case JAVALANG_BOOLEAN: + updateBoolean(key, (boolean) object); + break; + case JAVALANG_STRING: + updateString(key, (String) object); + break; + case JAVALANG_CHARACTER: + updateChar(key, (char) object); + break; + case JAVALANG_INTEGER: + updateInt(key, (int) object); + break; + case JAVALANG_LONG: + updateLong(key, (long) object); + break; + case JAVALANG_FLOAT: + updateFloat(key, (float) object); + break; + case JAVALANG_DOUBLE: + updateDouble(key, (double) object); + break; + default: + String msg = "I can't add the given object as value."; + throw new JsonException(msg); + } + } + return this; + } + + /** + * Updates the value of the given key. + * + * @param key key to use + * @return this + */ + public JsonObject updateNull(final String key) { + this.map.replace(key, new JsonValue()); + return this; + } + + /** + * Updates the value of the given key. + * + * @param key key to use + * @param value value to use + * @return this + */ + public JsonObject updateObject(final String key, + final JsonObject value) { + this.map.replace(key, new JsonValue(value)); + return this; + } + + /** + * Updates the value of the given key. + * + * @param key key to use + * @param value value to use + * @return this + */ + public JsonObject updateArray(final String key, + final JsonArray value) { + this.map.replace(key, new JsonValue(value)); + return this; + } + + /** + * Updates the value of the given key. + * + * @param key key to use + * @param value value to use + * @return this + */ + public JsonObject updateBoolean(final String key, + final boolean value) { + this.map.replace(key, new JsonValue(value)); + return this; + } + + /** + * Updates the value of the given key. + * + * @param key key to use + * @param value value to use + * @return this + */ + public JsonObject updateString(final String key, + final String value) { + this.map.replace(key, new JsonValue(value)); + return this; + } + + /** + * Updates the value of the given key. + * + * @param key key to use + * @param value value to use + * @return this + */ + public JsonObject updateChar(final String key, + final char value) { + this.map.replace(key, new JsonValue(value)); + return this; + } + + /** + * Updates the value of the given key. + * + * @param key key to use + * @param value value to use + * @return this + */ + public JsonObject updateInt(final String key, + final int value) { + this.map.replace(key, new JsonValue(value)); + return this; + } + + /** + * Updates the value of the given key. + * + * @param key key to use + * @param value value to use + * @return this + */ + public JsonObject updateLong(final String key, + final long value) { + this.map.replace(key, new JsonValue(value)); + return this; + } + + /** + * Updates the value of the given key. + * + * @param key key to use + * @param value value to use + * @return this + */ + public JsonObject updateFloat(final String key, + final float value) { + this.map.replace(key, new JsonValue(value)); + return this; + } + + /** + * Updates the value of the given key. + * + * @param key key to use + * @param value value to use + * @return this + */ + public JsonObject updateDouble(final String key, + final double value) { + this.map.replace(key, new JsonValue(value)); + return this; + } + + /** + * Removes the key and its value. + * + * @param key key to use + */ + public void removeJsonValue(final String key) { + this.map.remove(key); + } + + /** + * @param jsonPrint object, which text representation will be created + * @return string representation of this json object + */ + public String toString(final JsonPrint jsonPrint) { + switch (jsonPrint) { + case MINIMAL: return toMinimalString(); + case PRETTY: return toPrettyString(); + default: + throw new JsonException("Unknown JsonPrint: " + jsonPrint); + } + } + + /** + * @return String representation of this json object in minimal version + */ + public String toMinimalString() { + return JsonObjectPrinter.toMinimalString(this); + } + + /** + * @return String representation of this json object in pretty toString + * version + */ + public String toPrettyString() { + return JsonObjectPrinter.toPrettyString(this); + } + + /** + * @return copy of this json object + */ + public JsonObject getCopy() { + String stringRepresentationOfThisObject = this.toMinimalString(); + return new JsonObject(stringRepresentationOfThisObject); + } + + /** + * @return key iterator + */ + public List keyList() { + return ((PowerMap) this.map).keyList(); + } + + final JsonValue getJsonValue(final String key) { + return this.map.get(key); + } + + @Override + public final String toString() { + return this.toMinimalString(); + } + +} diff --git a/power-json/src/main/java/org/nanoboot/powerframework/json/JsonObjectDeserializable.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonObjectDeserializable.java new file mode 100644 index 0000000..b55c2e8 --- /dev/null +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonObjectDeserializable.java @@ -0,0 +1,37 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public interface JsonObjectDeserializable { + + /** + * Sets this object from a json object. + * @param jsonObject given json object + */ + void fromJsonObject(JsonObject jsonObject); +} diff --git a/power-json/src/main/java/org/nanoboot/powerframework/json/JsonObjectKeyValue.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonObjectKeyValue.java new file mode 100644 index 0000000..15320c3 --- /dev/null +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonObjectKeyValue.java @@ -0,0 +1,84 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class JsonObjectKeyValue { + + private String key; + private String value; + + JsonObjectKeyValue(final String string) { + int colonIndex = findColonIndex(string); + parseKey(string, colonIndex); + parseValue(string, colonIndex); + } + + private void parseKey(final String string, + int colonIndex) { + final int keyStartIndex = 0; + final int keyEndIndex = colonIndex; + key = string.substring(keyStartIndex, keyEndIndex).trim(); + key = cleanKey(key); + } + + private void parseValue(final String string, + int colonIndex) { + final int valueStartIndex = ++colonIndex; + final int valueEndIndex = string.length(); + value = string.substring(valueStartIndex, valueEndIndex).trim(); + } + + private int findColonIndex(final String string) { + int colonIndex; + for (colonIndex = 0; colonIndex < string.length(); colonIndex++) { + char currentChar = string.charAt(colonIndex); + if (currentChar == JsonConstants.COLON) { + return colonIndex; + } + } + throw new JsonException("Colon was not found in " + string); + } + + /** + * Removes the apostrophe from the key. + * + * @param key + * @return + */ + private String cleanKey(final String key) { + return JsonParser.deleteTheCharAtTheStartAndTheEnd(key); + } + + String getKey() { + return key; + } + + String getValue() { + return value; + } +} diff --git a/power-json/src/main/java/org/nanoboot/powerframework/json/JsonObjectParser.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonObjectParser.java new file mode 100644 index 0000000..8147ba7 --- /dev/null +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonObjectParser.java @@ -0,0 +1,78 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +import java.util.*; + +/** + * Is used to create json objects from strings. + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +class JsonObjectParser extends JsonParser { + + /** + * Parses String to empty json object. + * + * @param jsonObject + * @param stringRepresentationOfJsonObject + * @return json object from parsed String + */ + static JsonObject parseStringToJsonObject(JsonObject jsonObject, + String stringRepresentationOfJsonObject) { + if (!jsonObject.isEmpty()) { + throw new JsonException("I can't parse. The json object is not empty."); + } + String trimmedStringRepresentationOfJsonObject = stringRepresentationOfJsonObject.trim(); + if (!isStringJsonObject(trimmedStringRepresentationOfJsonObject)) { + throw new JsonException("I can't parse. The trimmed String does not start with { or does not end with }"); + } + String collectionsOfValuesOfTheJsonObjectString = deleteTheCharAtTheStartAndTheEnd(trimmedStringRepresentationOfJsonObject); + + ArrayList array = ArrayWithItemsSplitByComma.getListWithItemsSplitByComma(collectionsOfValuesOfTheJsonObjectString); + for (final String element : array) { + JsonObjectKeyValue jsonObjectKeyValue = new JsonObjectKeyValue(element); + String key = jsonObjectKeyValue.getKey(); + String value = jsonObjectKeyValue.getValue(); + JsonValue jsonValue = JsonValue.parseStringToJsonValue(value); + //System.out.println("\n\nelement: " + element + "\nkey: " + key + " \nvalue: " + value + " " + jsonValue.getJsonValueType() + " " + jsonValue.toMinimalString()); + + jsonObject.addJsonValue(key, jsonValue); + } + return jsonObject; + } + + private static boolean isStringJsonObject( + String trimmedStringRepresentationOfJsonObject) { + return (getFirstCharOfTheString(trimmedStringRepresentationOfJsonObject) == JsonConstants.OBJECTSTART) && (getLastCharOfTheString(trimmedStringRepresentationOfJsonObject) == JsonConstants.OBJECTEND); + } + + /** + * Constructor + *

+ * Not meant to be instantiated. + */ + private JsonObjectParser() { + //Not meant to be instantiated. + } +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonObjectPrinter.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonObjectPrinter.java similarity index 65% rename from src/main/java/org/nanoboot/powerframework/json/JsonObjectPrinter.java rename to power-json/src/main/java/org/nanoboot/powerframework/json/JsonObjectPrinter.java index ca3cfa6..4ebe964 100644 --- a/src/main/java/org/nanoboot/powerframework/json/JsonObjectPrinter.java +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonObjectPrinter.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -20,27 +20,18 @@ package org.nanoboot.powerframework.json; -import org.nanoboot.powerframework.collections.DictionaryKeyIterator; +import java.util.List; /** * Used to create String representation of a json object. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ class JsonObjectPrinter extends JsonPrinter { - /** - * Constructor - * - * Not meant to be instantiated. - */ - private JsonObjectPrinter() { - //Not meant to be instantiated. - } - /** * @param jsonObject - * * @return String representation of this json object in minimal version */ static String toMinimalString(JsonObject jsonObject) { @@ -49,8 +40,8 @@ class JsonObjectPrinter extends JsonPrinter { /** * @param jsonObject - * - * @return String representation of this json object in pretty print version + * @return String representation of this json object in pretty toString + * version */ static String toPrettyString(JsonObject jsonObject) { return toString(jsonObject, true); @@ -59,50 +50,60 @@ class JsonObjectPrinter extends JsonPrinter { /** * @param jsonObject * @param printAsPrettyVersion - * * @return String representation of this json object */ - static String toString(JsonObject jsonObject, boolean printAsPrettyVersion) { - DictionaryKeyIterator keyIterator = jsonObject.getKeyIterator(); + static String toString(JsonObject jsonObject, + boolean printAsPrettyVersion) { + List keyList = jsonObject.keyList(); String value; String key; StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append(JsonSpecialCharSequences.getObjectLeft()); + stringBuilder.append(JsonConstants.OBJECTSTART); if (printAsPrettyVersion) { - stringBuilder.append(JsonSpecialCharSequences.getLineBreak()); + stringBuilder.append(JsonConstants.LINEBREAK); } - while (keyIterator.hasNext()) { - key = keyIterator.getNextKey(); - if (printAsPrettyVersion) { - value = jsonObject.getJsonValue(key).toPrettyString(); - } else { - value = jsonObject.getJsonValue(key).toMinimalString(); - } + int setSize = keyList.size(); + int index = 0; + int lastIndex = setSize - 1; + for (String e : keyList){ + key = e; + value = printAsPrettyVersion ? jsonObject.getJsonValue(key).toPrettyString() : jsonObject.getJsonValue(key).toMinimalString(); if (printAsPrettyVersion) { - stringBuilder.append(JsonSpecialCharSequences.getTab()); + stringBuilder.append(JsonConstants.TAB); } - stringBuilder.append(JsonSpecialCharSequences.getApostrophe()); + stringBuilder.append(JsonConstants.APOSTROPHE); stringBuilder.append(key); - stringBuilder.append(JsonSpecialCharSequences.getApostrophe()); - stringBuilder.append(JsonSpecialCharSequences.getColon()); + stringBuilder.append(JsonConstants.APOSTROPHE); + stringBuilder.append(JsonConstants.COLON); if (printAsPrettyVersion && ((jsonObject.getJsonValue(key).isArray()) || (jsonObject.getJsonValue(key).isObject()))) { value = addTabOnEveryLineStartWithoutFirst(value); } stringBuilder.append(value); - if (keyIterator.hasNext()) { + boolean hasNext = index != lastIndex; + if (hasNext) { stringBuilder.append(","); } if (printAsPrettyVersion) { - stringBuilder.append(JsonSpecialCharSequences.getLineBreak()); + stringBuilder.append(JsonConstants.LINEBREAK); } + index++; } - stringBuilder.append(JsonSpecialCharSequences.getObjectRight()); + stringBuilder.append(JsonConstants.OBJECTEND); return stringBuilder.toString(); } + + /** + * Constructor + *

+ * Not meant to be instantiated. + */ + private JsonObjectPrinter() { + //Not meant to be instantiated. + } } diff --git a/power-json/src/main/java/org/nanoboot/powerframework/json/JsonObjectSerializable.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonObjectSerializable.java new file mode 100644 index 0000000..19680a6 --- /dev/null +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonObjectSerializable.java @@ -0,0 +1,40 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public interface JsonObjectSerializable { + + /** + * Creates JsonObject representation of the instance + * of the class implementing this interface. + * + * @return JsonObject representation of the instance + * of the class implementing this interface + */ + JsonObject toJsonObject(); +} diff --git a/src/main/java/org/nanoboot/powerframework/json/SerializableToJsonObject.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonObjectValidator.java similarity index 80% rename from src/main/java/org/nanoboot/powerframework/json/SerializableToJsonObject.java rename to power-json/src/main/java/org/nanoboot/powerframework/json/JsonObjectValidator.java index 8216581..9fa8016 100644 --- a/src/main/java/org/nanoboot/powerframework/json/SerializableToJsonObject.java +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonObjectValidator.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -21,10 +21,11 @@ package org.nanoboot.powerframework.json; /** + * * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ -public interface SerializableToJsonObject { - public JsonObject toJsonObject(); - public void fromJsonObject(JsonObject jsonObject); +class JsonObjectValidator { + } diff --git a/power-json/src/main/java/org/nanoboot/powerframework/json/JsonParser.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonParser.java new file mode 100644 index 0000000..eb5293c --- /dev/null +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonParser.java @@ -0,0 +1,53 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +/** + * Used to parse String representation of JsonObject or JsonArray to their + * object representation. + * + * @author Robert Vokac + * @since 0.0.0 + */ +class JsonParser { + + static char getFirstCharOfTheString(final String string) { + return string.charAt(0); + } + + static char getLastCharOfTheString(final String string) { + return string.charAt(string.length() - 1); + } + + protected static String deleteTheCharAtTheStartAndTheEnd(final String string) { + return string.substring(1, string.length() - 1); + } + + /** + * Constructor + *

+ * Not meant to be instantiated. + */ + JsonParser() { + //Not meant to be instantiated. + } + +} diff --git a/power-json/src/main/java/org/nanoboot/powerframework/json/JsonPrint.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonPrint.java new file mode 100644 index 0000000..f511a5a --- /dev/null +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonPrint.java @@ -0,0 +1,39 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +/** + * + * @author Robert Vokac + * @since 0.0.0 + */ +public enum JsonPrint { + + /** + * + */ + PRETTY, + + /** + * + */ + MINIMAL; +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonPrinter.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonPrinter.java similarity index 71% rename from src/main/java/org/nanoboot/powerframework/json/JsonPrinter.java rename to power-json/src/main/java/org/nanoboot/powerframework/json/JsonPrinter.java index 509d913..0e2eae3 100644 --- a/src/main/java/org/nanoboot/powerframework/json/JsonPrinter.java +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonPrinter.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -23,25 +23,27 @@ package org.nanoboot.powerframework.json; /** * Used for JsonObjectPrinter and JsonArrayPrinter to extend. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ class JsonPrinter { + private static final String BREAKTAB = "\n" + JsonConstants.TAB; + + protected static String addTabOnEveryLineStart(final String value) { + return JsonConstants.TAB + addTabOnEveryLineStartWithoutFirst(value); + } + + protected static String addTabOnEveryLineStartWithoutFirst(final String value) { + return value.replace("\n", BREAKTAB); + } + /** * Constructor - * + *

* Not meant to be instantiated. */ JsonPrinter() { //Not meant to be instantiated. } - - static String addTabOnEveryLineStart(String value) { - String result = value.replace("\n", new String("\n" + JsonSpecialCharSequences.getTab())); - return JsonSpecialCharSequences.getTab() + result; - } - - static String addTabOnEveryLineStartWithoutFirst(String value) { - return value.replace("\n", new String("\n" + JsonSpecialCharSequences.getTab())); - } } diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonString.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonString.java similarity index 77% rename from src/main/java/org/nanoboot/powerframework/json/JsonString.java rename to power-json/src/main/java/org/nanoboot/powerframework/json/JsonString.java index 5b8bb2c..5316676 100644 --- a/src/main/java/org/nanoboot/powerframework/json/JsonString.java +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonString.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -23,26 +23,26 @@ package org.nanoboot.powerframework.json; /** * Represents String json value. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * + * + * @author Robert Vokac + * @since 0.0.0 */ + class JsonString { - private final String value; - - JsonString(String value) { - this.value = value; - } - - String getString() { - return this.value; - } - - @Override - public String toString() { + static String toString(final String value) { StringBuilder sb = new StringBuilder(); sb.append('\"'); - sb.append(getString()); + sb.append(value); sb.append('\"'); return sb.toString(); } + + /** + * Not meant to be instantiated. + */ + private JsonString() { + //Not meant to be instantiated. + } } diff --git a/power-json/src/main/java/org/nanoboot/powerframework/json/JsonValue.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonValue.java new file mode 100644 index 0000000..b37201d --- /dev/null +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonValue.java @@ -0,0 +1,364 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Pattern; + +import static org.nanoboot.powerframework.json.JsonParser.deleteTheCharAtTheStartAndTheEnd; +import static org.nanoboot.powerframework.json.JsonParser.getFirstCharOfTheString; + +/** + * Represents json value. + * + * @author Robert Vokac + * @since 0.0.0 + */ +class JsonValue { + + static JsonValue parseStringToJsonValue(final String stringToParse) {//NOSONAR + String trimmedStringToParse = stringToParse.trim(); + final char firstChar = getFirstCharOfTheString(trimmedStringToParse); + + if ("null".equals(trimmedStringToParse)) { + return new JsonValue(); + } + if (JsonConstants.OBJECTSTART == firstChar) { + return new JsonValue(new JsonObject(trimmedStringToParse)); + } + if (JsonConstants.ARRAYSTART == firstChar) { + return new JsonValue(new JsonArray(trimmedStringToParse)); + } + if ("true".equals(trimmedStringToParse)) { + return new JsonValue(true); + } + if ("false".equals(trimmedStringToParse)) { + return new JsonValue(false); + } + if (JsonConstants.APOSTROPHE == firstChar) { + return parseStringToStringOrChar(trimmedStringToParse); + } + try { + return parseStringToIntOrLongOrFloatOrDouble(trimmedStringToParse); + } catch (Exception e) { + throw new JsonException("Something went wrong. I am not able to parse: \"" + stringToParse + "\". " + e); + } + + } + + private static JsonValue parseStringToStringOrChar(final String stringToParse) { + String stringWithoutQuotes = deleteTheCharAtTheStartAndTheEnd(stringToParse); + if (stringWithoutQuotes.length() == 1) { + return new JsonValue(stringWithoutQuotes.charAt(0)); + } else { + return new JsonValue(stringWithoutQuotes); + } + } + + private static JsonValue parseStringToIntOrLongOrFloatOrDouble( + String stringToParse) { + String intOrLongPattern = "-?[0-9]*"; + String floatOrDoublePattern = "-?([0-9]*)\\.([0-9]*)"; + + if (Pattern.matches(floatOrDoublePattern, stringToParse)) { + return parseStringToFloatOrDouble(stringToParse); + } + if (Pattern.matches(intOrLongPattern, stringToParse)) { + return parseStringToIntOrLong(stringToParse); + } + throw new JsonException("I am not able to parse the number: \"" + stringToParse + "\"."); + } + + private static JsonValue parseStringToIntOrLong(final String stringToParse) { + try { + return new JsonValue(Integer.parseInt(stringToParse)); + } catch (NumberFormatException e) { + //Logger.getLogger(JsonParser.class.getName()).log(Level.SEVERE, null, e); + try { + return new JsonValue(Long.parseLong(stringToParse)); + } catch (NumberFormatException e2) { + Logger.getLogger(JsonParser.class.getName()).log(Level.SEVERE, null, e2); + throw new JsonException("The number is too long."); + } + } + } + + private static JsonValue parseStringToFloatOrDouble(final String stringToParse) { + int digitsPrecision = 0; + String stringToParseWithoutMinus = stringToParse; + if (stringToParseWithoutMinus.startsWith("-")) { + stringToParseWithoutMinus = stringToParseWithoutMinus.substring(1); + } + for (int i = 0; i < stringToParseWithoutMinus.length(); i++) { + char currentChar = stringToParseWithoutMinus.charAt(i); + if (currentChar == '.') { + digitsPrecision = stringToParseWithoutMinus.length() - 1 - i; + break; + } + } + if (digitsPrecision > 6) { + try { + return new JsonValue(Double.parseDouble(stringToParse)); + } catch (NumberFormatException e) { + //NOSONAR + throw new JsonException("The number is too long."); + } + } else { + return new JsonValue(Float.parseFloat(stringToParse)); + } + } + + private JsonValueType jsonValueType = null; + + private JsonObject jsonObject; + private JsonArray jsonArray; + private boolean jsonBoolean; + private String jsonString; + private char jsonChar; + private int jsonInt; + private long jsonLong; + private float jsonFloat; + private double jsonDouble; + + JsonValue() { + this.jsonValueType = JsonValueType.NULL; + } + + JsonValue(JsonObject jsonObject) { + this.jsonValueType = JsonValueType.OBJECT; + this.jsonObject = jsonObject; + } + + JsonValue(JsonArray jsonArray) { + this.jsonValueType = JsonValueType.ARRAY; + this.jsonArray = jsonArray; + } + + JsonValue(boolean jsonBoolean) { + this.jsonValueType = JsonValueType.BOOLEAN; + this.jsonBoolean = jsonBoolean; + } + + JsonValue(final String jsonString) { + this.jsonValueType = JsonValueType.STRING; + this.jsonString = jsonString; + } + + JsonValue(char jsonLiteral) { + this.jsonValueType = JsonValueType.CHAR; + this.jsonChar = jsonLiteral; + } + + JsonValue(int jsonInt) { + this.jsonValueType = JsonValueType.INT; + this.jsonInt = jsonInt; + } + + JsonValue(long jsonLong) { + this.jsonValueType = JsonValueType.LONG; + this.jsonLong = jsonLong; + } + + JsonValue(float jsonFloat) { + this.jsonValueType = JsonValueType.FLOAT; + this.jsonFloat = jsonFloat; + } + + JsonValue(double jsonDouble) { + this.jsonValueType = JsonValueType.DOUBLE; + this.jsonDouble = jsonDouble; + } + + JsonValueType getJsonValueType() { + return this.jsonValueType; + } + + boolean isJsonValueType(JsonValueType jsonValueType) { + return this.jsonValueType == jsonValueType; + } + + boolean isNull() { + return isJsonValueType(JsonValueType.NULL); + } + + boolean isObject() { + return isJsonValueType(JsonValueType.OBJECT); + } + + boolean isArray() { + return isJsonValueType(JsonValueType.ARRAY); + } + + boolean isBoolean() { + return isJsonValueType(JsonValueType.BOOLEAN); + } + + boolean isString() { + return isJsonValueType(JsonValueType.STRING); + } + + boolean isChar() { + return isJsonValueType(JsonValueType.CHAR); + } + + boolean isInt() { + return isJsonValueType(JsonValueType.INT); + } + + boolean isLong() { + return isJsonValueType(JsonValueType.LONG); + } + + boolean isFloat() { + return isJsonValueType(JsonValueType.FLOAT); + } + + boolean isDouble() { + return isJsonValueType(JsonValueType.DOUBLE); + } + + JsonObject getJsonObject() { + throwExceptionIfTypeDoesNotMatch(JsonValueType.OBJECT); + return this.jsonObject; + } + + JsonArray getJsonArray() { + throwExceptionIfTypeDoesNotMatch(JsonValueType.ARRAY); + return this.jsonArray; + } + + boolean getJsonBoolean() { + throwExceptionIfTypeDoesNotMatch(JsonValueType.BOOLEAN); + return this.jsonBoolean; + } + + String getJsonString() { + throwExceptionIfTypeDoesNotMatch(JsonValueType.STRING); + return this.jsonString; + } + + char getJsonChar() { + throwExceptionIfTypeDoesNotMatch(JsonValueType.CHAR); + return this.jsonChar; + } + + int getJsonInt() { + throwExceptionIfTypeDoesNotMatch(JsonValueType.INT); + return this.jsonInt; + } + + long getJsonLong() { + throwExceptionIfTypeDoesNotMatch(JsonValueType.LONG); + return this.jsonLong; + } + + float getJsonFloat() { + throwExceptionIfTypeDoesNotMatch(JsonValueType.FLOAT); + return this.jsonFloat; + } + + double getJsonDouble() { + throwExceptionIfTypeDoesNotMatch(JsonValueType.DOUBLE); + return this.jsonDouble; + } + + private void throwExceptionIfTypeDoesNotMatch( + JsonValueType wantedJsonValueType) { + if (this.getJsonValueType().equals(wantedJsonValueType)) { + return; + } + throw new JsonException("This JsonValue has no type " + wantedJsonValueType + " The value type is " + this.getJsonValueType().name()); + } + + String toPrettyString() { + return toString(true); + } + + String toMinimalString() { + return toString(false); + } + + String toString(boolean printAsPrettyVersion) {//NOSONAR + switch (this.jsonValueType) { + case NULL: + return JsonConstants.NULL; + case OBJECT: + return printAsPrettyVersion ? this.getJsonObject().toPrettyString() : this.getJsonObject().toMinimalString(); + case ARRAY: + return printAsPrettyVersion ? this.getJsonArray().toPrettyString() : this.getJsonArray().toMinimalString(); + case BOOLEAN: + return JsonBoolean.toString(jsonBoolean); + case STRING: + return JsonString.toString(jsonString); + case CHAR: + return JsonChar.toString(jsonChar); + case INT: + return JsonInt.toString(jsonInt); + case LONG: + return JsonLong.toString(jsonLong); + case FLOAT: + return JsonFloat.toString(jsonFloat); + case DOUBLE: + return JsonDouble.toString(jsonDouble); + default: + throw new IllegalStateException("Enum error."); + } + } + + Object toObject() {//NOSONAR + switch (jsonValueType) { + case NULL: + return null; + + case OBJECT: + return this.getJsonObject(); + + case ARRAY: + return this.getJsonArray(); + + case BOOLEAN: + return this.jsonBoolean; + + case STRING: + return this.jsonString; + + case CHAR: + return this.jsonChar; + + case INT: + return this.jsonInt; + + case LONG: + return this.jsonLong; + + case FLOAT: + return this.jsonFloat; + + case DOUBLE: + return this.jsonDouble; + + default: + throw new IllegalStateException("Enum error."); + } + + } +} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonValueType.java b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonValueType.java similarity index 91% rename from src/main/java/org/nanoboot/powerframework/json/JsonValueType.java rename to power-json/src/main/java/org/nanoboot/powerframework/json/JsonValueType.java index 3f983cf..433eab8 100644 --- a/src/main/java/org/nanoboot/powerframework/json/JsonValueType.java +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/JsonValueType.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -23,7 +23,8 @@ package org.nanoboot.powerframework.json; /** * Represents the type of a json value. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public enum JsonValueType { diff --git a/power-json/src/main/java/org/nanoboot/powerframework/json/package-info.java b/power-json/src/main/java/org/nanoboot/powerframework/json/package-info.java new file mode 100644 index 0000000..2fffa38 --- /dev/null +++ b/power-json/src/main/java/org/nanoboot/powerframework/json/package-info.java @@ -0,0 +1,27 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * Json classes. + * + * @author Robert Vokac + * @since 0.0.0 + */ +package org.nanoboot.powerframework.json; diff --git a/power-json/src/main/resources/.gitkeep b/power-json/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-json/src/test/java/org/nanoboot/powerframework/json/ArrayWithItemsSplitByCommaTest.java b/power-json/src/test/java/org/nanoboot/powerframework/json/ArrayWithItemsSplitByCommaTest.java new file mode 100644 index 0000000..8fec2a6 --- /dev/null +++ b/power-json/src/test/java/org/nanoboot/powerframework/json/ArrayWithItemsSplitByCommaTest.java @@ -0,0 +1,66 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +import java.util.*; + +import static org.junit.Assert.assertTrue; + +import org.junit.*; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class ArrayWithItemsSplitByCommaTest { + + public ArrayWithItemsSplitByCommaTest() { + } + + /** + * Test of getListWithItemsSplitByComma method, of class + * ArrayWithItemsSplitByComma. + */ + @Test + public void testGetListWithItemsSplitByComma() { + //arrange + String stringToSplit = "\"date of death\":null,\"father\":{\"name\":\"Peter\",\"surname\":\"Black\"},\"mother\":{\"name\":\"Sue\",\"surname\":\"Black\"},\"property\":[null,{\"type\":\"computer\",\"cpu\":\"corei7\",\"ram\":\"16GB\"},[\"8GB memory card\",\"16GB memory card\",\"32GB memory card\",\"128GB memory card\"],true,\"car\",\"y\",42,9987987998798,4.56,1.646659262492],\"is rich\":true,\"name\":\"John\",\"surname\":\"Black\",\"date of birth\":\"1975-09-23\",\"favorit letter\":\"W\",\"year of birth\":1975,\"favorit very long number\":8798799845647987,\"height\":173.5466,\"height- high precision\":173.54666549879545"; + String expectedString = "\"date of death\":null###\"father\":{\"name\":\"Peter\",\"surname\":\"Black\"}###\"mother\":{\"name\":\"Sue\",\"surname\":\"Black\"}###\"property\":[null,{\"type\":\"computer\",\"cpu\":\"corei7\",\"ram\":\"16GB\"},[\"8GB memory card\",\"16GB memory card\",\"32GB memory card\",\"128GB memory card\"],true,\"car\",\"y\",42,9987987998798,4.56,1.646659262492]###\"is rich\":true###\"name\":\"John\"###\"surname\":\"Black\"###\"date of birth\":\"1975-09-23\"###\"favorit letter\":\"W\"###\"year of birth\":1975###\"favorit very long number\":8798799845647987###\"height\":173.5466###\"height- high precision\":173.54666549879545###"; + String returnedString; + StringBuilder stringBuilder = new StringBuilder(); + //act + ArrayList list = ArrayWithItemsSplitByComma.getListWithItemsSplitByComma(stringToSplit); + final String threeHashes = "###"; + for (String element : list) { + stringBuilder.append(element); + stringBuilder.append(threeHashes); + } + + returnedString = stringBuilder.toString(); + //System.out.println("a" + expectedString + "b" + "\n" + "c" + returnedString + "d"); + //assert + assertTrue(expectedString.equals(returnedString)); + } + +} diff --git a/power-json/src/test/java/org/nanoboot/powerframework/json/CommasFinderTest.java b/power-json/src/test/java/org/nanoboot/powerframework/json/CommasFinderTest.java new file mode 100644 index 0000000..443c375 --- /dev/null +++ b/power-json/src/test/java/org/nanoboot/powerframework/json/CommasFinderTest.java @@ -0,0 +1,64 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.json; + +import java.util.*; + +import static org.junit.Assert.assertTrue; + +import org.junit.*; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class CommasFinderTest { + + public CommasFinderTest() { + } + + /** + * Test of getListOfIndexesOfCommas method, of class CommasFinder. + */ + @Test + public void testGetListOfIndexesOfCommas() { + String stringToSplit = "\"date of death\":null,\"father\":{\"name\":\"Peter\",\"surname\":\"Black\"},\"mother\":{\"name\":\"Sue\",\"surname\":\"Black\"},\"property\":[null,{\"type\":\"computer\",\"cpu\":\"corei7\",\"ram\":\"16GB\"},[\"8GB memory card\",\"16GB memory card\",\"32GB memory card\",\"128GB memory card\"],true,\"car\",\"y\",42,9987987998798,4.56,1.646659262492],\"is rich\":true,\"name\":\"John\",\"surname\":\"Black\",\"date of birth\":\"1975-09-23\",\"favorit letter\":\"W\",\"year of birth\":1975,\"favorit very long number\":8798799845647987,\"height\":173.5466,\"height- high precision\":173.54666549879545"; + //arrange + String expectedString = "20,64,106,302,317,331,349,378,399,420,464,482,"; + String returnedString; + StringBuilder stringBuilder = new StringBuilder(); + //act + ArrayList listOfCommas = CommasFinder.getListOfIndexesOfCommas(stringToSplit); + for (int element : listOfCommas) { + stringBuilder.append(element); + stringBuilder.append(JsonConstants.COMMA); + } + + returnedString = stringBuilder.toString(); + //System.out.println("a"+expectedString+"b"+"\n"+"c"+returnedString+"d"); + //assert + assertTrue(expectedString.equals(returnedString)); + } + +} diff --git a/src/test/java/org/nanoboot/powerframework/json/JsonArrayTest.java b/power-json/src/test/java/org/nanoboot/powerframework/json/JsonArrayTest.java similarity index 97% rename from src/test/java/org/nanoboot/powerframework/json/JsonArrayTest.java rename to power-json/src/test/java/org/nanoboot/powerframework/json/JsonArrayTest.java index f20522f..1602db7 100644 --- a/src/test/java/org/nanoboot/powerframework/json/JsonArrayTest.java +++ b/power-json/src/test/java/org/nanoboot/powerframework/json/JsonArrayTest.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -20,13 +20,18 @@ package org.nanoboot.powerframework.json; -import org.junit.Test; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.*; /** + * * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ + public class JsonArrayTest { /** @@ -70,7 +75,7 @@ public class JsonArrayTest { jsonArray.addString("calm"); //act - returnedValue = jsonArray.getCountOfItems(); + returnedValue = jsonArray.size(); //assert assertEquals(expectedValue, returnedValue); } @@ -113,7 +118,7 @@ public class JsonArrayTest { } /** - * Test of add method, of class JsonArray. + * Test of addJsonValue method, of class JsonArray. */ @Test public void testAdd() { @@ -684,7 +689,7 @@ public class JsonArrayTest { JsonArray jsonArray = new JsonArray(); jsonArray.addInt(4);//act jsonValue = jsonArray.getJsonValue(0); - returnedValue = jsonValue.getJsonInt().getInt(); + returnedValue = jsonValue.getJsonInt(); //assert assertEquals(expectedValue, returnedValue); } @@ -790,6 +795,7 @@ public class JsonArrayTest { returnedString = propertyCopy.toMinimalString(); //assert boolean result = expectedString.equals(returnedString); + //System.out.println(expectedString +"\n"+ returnedString); assertEquals(expectedString, returnedString); } diff --git a/src/test/java/org/nanoboot/powerframework/json/JsonObjectTest.java b/power-json/src/test/java/org/nanoboot/powerframework/json/JsonObjectTest.java similarity index 93% rename from src/test/java/org/nanoboot/powerframework/json/JsonObjectTest.java rename to power-json/src/test/java/org/nanoboot/powerframework/json/JsonObjectTest.java index bff39e7..e8969c4 100644 --- a/src/test/java/org/nanoboot/powerframework/json/JsonObjectTest.java +++ b/power-json/src/test/java/org/nanoboot/powerframework/json/JsonObjectTest.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -20,14 +20,16 @@ package org.nanoboot.powerframework.json; -import org.nanoboot.powerframework.PowerRuntimeException; -import org.nanoboot.powerframework.collections.DictionaryKeyIterator; -import org.junit.Test; +import java.util.*; + import static org.junit.Assert.*; +import org.junit.*; + /** * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public class JsonObjectTest { @@ -52,6 +54,7 @@ public class JsonObjectTest { personJohnBlack = new JsonObject(expectedString); returnedString = personJohnBlack.toMinimalString(); //assert + //System.out.println(expectedString+" fff "+returnedString); boolean result = expectedString.equals(returnedString); assertEquals(expectedString, returnedString); } @@ -70,7 +73,7 @@ public class JsonObjectTest { jsonObject.addString("nick", "Johny"); jsonObject.addString("name", "John"); jsonObject.addInt("age", 43); - returnedValue = jsonObject.getCountOfItems(); + returnedValue = jsonObject.size(); //assert assertEquals(expectedValue, returnedValue); } @@ -110,7 +113,7 @@ public class JsonObjectTest { } /** - * Test of containsValueWithKey method, of class JsonObject. + * Test of hasKey method, of class JsonObject. */ @Test public void testContainsValueWithKey() { @@ -123,13 +126,13 @@ public class JsonObjectTest { jsonObject.addString("nick", "Johny"); jsonObject.addString("name", "John"); jsonObject.addInt("age", 43); - returnedValue = jsonObject.containsValueWithKey("nick"); + returnedValue = jsonObject.hasKey("nick"); //assert assertEquals(expectedValue, returnedValue); } /** - * Test of containsValueWithKey method, of class JsonObject. + * Test of hasKey method, of class JsonObject. */ @Test public void testContainsValueWithKey2() { @@ -142,13 +145,13 @@ public class JsonObjectTest { jsonObject.addString("nick", "Johny"); jsonObject.addString("name", "John"); jsonObject.addInt("age", 43); - returnedValue = jsonObject.containsValueWithKey("nationality"); + returnedValue = jsonObject.hasKey("nationality"); //assert assertEquals(expectedValue, returnedValue); } /** - * Test of containsValueWithKey method, of class JsonObject. + * Test of hasKey method, of class JsonObject. */ @Test public void testContainsValueWithKey3() { @@ -158,13 +161,13 @@ public class JsonObjectTest { boolean returnedValue; //act jsonObject.addString("personality", "calm"); - returnedValue = jsonObject.containsValueWithKey("personality"); + returnedValue = jsonObject.hasKey("personality"); //assert assertEquals(expectedValue, returnedValue); } /** - * Test of add method, of class JsonObject. + * Test of addJsonValue method, of class JsonObject. */ @Test public void testAdd_ObjectIsNull() { @@ -180,7 +183,7 @@ public class JsonObjectTest { } /** - * Test of add method, of class JsonObject. + * Test of addJsonValue method, of class JsonObject. */ @Test public void testAdd_ObjectIsJsonObject() { @@ -196,7 +199,7 @@ public class JsonObjectTest { } /** - * Test of add method, of class JsonObject. + * Test of addJsonValue method, of class JsonObject. */ @Test public void testAdd_ObjectIsJsonArray() { @@ -212,7 +215,7 @@ public class JsonObjectTest { } /** - * Test of add method, of class JsonObject. + * Test of addJsonValue method, of class JsonObject. */ @Test public void testAdd_ObjectIsBoolean() { @@ -228,7 +231,7 @@ public class JsonObjectTest { } /** - * Test of add method, of class JsonObject. + * Test of addJsonValue method, of class JsonObject. */ @Test public void testAdd_ObjectIsString() { @@ -244,7 +247,7 @@ public class JsonObjectTest { } /** - * Test of add method, of class JsonObject. + * Test of addJsonValue method, of class JsonObject. */ @Test public void testAdd_ObjectIsChar() { @@ -260,7 +263,7 @@ public class JsonObjectTest { } /** - * Test of add method, of class JsonObject. + * Test of addJsonValue method, of class JsonObject. */ @Test public void testAdd_ObjectIsInt() { @@ -276,7 +279,7 @@ public class JsonObjectTest { } /** - * Test of add method, of class JsonObject. + * Test of addJsonValue method, of class JsonObject. */ @Test public void testAdd_ObjectIsLong() {//arrange @@ -291,7 +294,7 @@ public class JsonObjectTest { } /** - * Test of add method, of class JsonObject. + * Test of addJsonValue method, of class JsonObject. */ @Test public void testAdd_ObjectIsFloat() { @@ -307,7 +310,7 @@ public class JsonObjectTest { } /** - * Test of add method, of class JsonObject. + * Test of addJsonValue method, of class JsonObject. */ @Test public void testAdd_ObjectIsDouble() { @@ -333,7 +336,7 @@ public class JsonObjectTest { boolean returnedValue; //act jsonObject.addNull("nothing"); - returnedValue = jsonObject.containsValueWithKey("nothing"); + returnedValue = jsonObject.hasKey("nothing"); //assert assertEquals(expectedValue, returnedValue); } @@ -349,7 +352,7 @@ public class JsonObjectTest { boolean returnedValue; //act jsonObject.addObject("object", new JsonObject()); - returnedValue = jsonObject.containsValueWithKey("object"); + returnedValue = jsonObject.hasKey("object"); //assert assertEquals(expectedValue, returnedValue); } @@ -365,7 +368,7 @@ public class JsonObjectTest { boolean returnedValue; //act jsonObject.addArray("array", new JsonArray()); - returnedValue = jsonObject.containsValueWithKey("array"); + returnedValue = jsonObject.hasKey("array"); //assert assertEquals(expectedValue, returnedValue); } @@ -381,7 +384,7 @@ public class JsonObjectTest { boolean returnedValue; //act jsonObject.addBoolean("boolean", true); - returnedValue = jsonObject.containsValueWithKey("boolean"); + returnedValue = jsonObject.hasKey("boolean"); //assert assertEquals(expectedValue, returnedValue); } @@ -397,7 +400,7 @@ public class JsonObjectTest { boolean returnedValue; //act jsonObject.addString("String", "some text"); - returnedValue = jsonObject.containsValueWithKey("String"); + returnedValue = jsonObject.hasKey("String"); //assert assertEquals(expectedValue, returnedValue); } @@ -413,7 +416,7 @@ public class JsonObjectTest { boolean returnedValue; //act jsonObject.addChar("char", 'a'); - returnedValue = jsonObject.containsValueWithKey("char"); + returnedValue = jsonObject.hasKey("char"); //assert assertEquals(expectedValue, returnedValue); } @@ -429,7 +432,7 @@ public class JsonObjectTest { boolean returnedValue; //act jsonObject.addInt("int", 2); - returnedValue = jsonObject.containsValueWithKey("int"); + returnedValue = jsonObject.hasKey("int"); //assert assertEquals(expectedValue, returnedValue); } @@ -445,7 +448,7 @@ public class JsonObjectTest { boolean returnedValue; //act jsonObject.addLong("long", 2l); - returnedValue = jsonObject.containsValueWithKey("long"); + returnedValue = jsonObject.hasKey("long"); //assert assertEquals(expectedValue, returnedValue); } @@ -461,7 +464,7 @@ public class JsonObjectTest { boolean returnedValue; //act jsonObject.addFloat("float", 2.5f); - returnedValue = jsonObject.containsValueWithKey("float"); + returnedValue = jsonObject.hasKey("float"); //assert assertEquals(expectedValue, returnedValue); } @@ -477,7 +480,7 @@ public class JsonObjectTest { boolean returnedValue; //act jsonObject.addDouble("double", 2.5d); - returnedValue = jsonObject.containsValueWithKey("double"); + returnedValue = jsonObject.hasKey("double"); //assert assertEquals(expectedValue, returnedValue); } @@ -642,6 +645,21 @@ public class JsonObjectTest { assertEquals(expectedValue, returnedValue); } + /** + * Test of isJsonValueType method, of class JsonObject. + */ + @Test + public void testIsJsonValueType() { + //arrange + JsonObject jsonObject = new JsonObject(); + JsonValueType jsonValueType = JsonValueType.DOUBLE; + + //act + jsonObject.addDouble("double", 2.5d); + //assert + assertTrue(jsonObject.isJsonValueType("double", jsonValueType)); + } + /** * Test of get method, of class JsonObject. */ @@ -1010,12 +1028,12 @@ public class JsonObjectTest { jsonObject.removeJsonValue("nick"); try { jsonObject.getString("nick"); - } catch (PowerRuntimeException e) { + } catch (NoSuchElementException e) { isExceptionThrown = true; } //assert if (!isExceptionThrown) { - fail("There should be thrown PowerRuntimeException"); + fail("There should be thrown NoSuchElementException"); } } @@ -1163,6 +1181,7 @@ public class JsonObjectTest { personJohnBlackCopy = personJohnBlack.getCopy(); returnedString = personJohnBlackCopy.toMinimalString(); //assert + System.out.println(expectedString + " " + returnedString); boolean result = expectedString.equals(returnedString); assertEquals(expectedString, returnedString); } @@ -1174,7 +1193,7 @@ public class JsonObjectTest { public void testGetKeyIterator() { //arrange JsonObject jsonObject = new JsonObject(); - DictionaryKeyIterator dictionaryKeyIterator; + List list; String expectedString = "name"; String returnedString; //act @@ -1182,31 +1201,10 @@ public class JsonObjectTest { jsonObject.addString("nick", "Johny"); jsonObject.addString("name", "John"); jsonObject.addInt("age", 43); - dictionaryKeyIterator = jsonObject.getKeyIterator(); - dictionaryKeyIterator.getNextKey(); - dictionaryKeyIterator.getNextKey(); - returnedString = dictionaryKeyIterator.getNextKey();; - //assert - assertEquals(expectedString, returnedString); - } + list = jsonObject.keyList(); - /** - * Test of getJsonValue method, of class JsonObject. - */ - @Test - public void testGetJsonValue() { - //arrange - JsonObject jsonObject = new JsonObject(); - DictionaryKeyIterator dictionaryKeyIterator; - String expectedString = "John"; - String returnedString; - //act - jsonObject.addString("personality", "calm"); - jsonObject.addString("nick", "Johny"); - jsonObject.addString("name", "John"); - jsonObject.addInt("age", 43); + returnedString = list.get(2); - returnedString = jsonObject.getJsonValue("name").getJsonString().getString(); //assert assertEquals(expectedString, returnedString); } diff --git a/src/test/java/org/nanoboot/powerframework/json/JsonValueTest.java b/power-json/src/test/java/org/nanoboot/powerframework/json/JsonValueTest.java similarity index 85% rename from src/test/java/org/nanoboot/powerframework/json/JsonValueTest.java rename to power-json/src/test/java/org/nanoboot/powerframework/json/JsonValueTest.java index cd4a4bf..27920b8 100644 --- a/src/test/java/org/nanoboot/powerframework/json/JsonValueTest.java +++ b/power-json/src/test/java/org/nanoboot/powerframework/json/JsonValueTest.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -20,13 +20,18 @@ package org.nanoboot.powerframework.json; -import org.nanoboot.powerframework.PowerRuntimeException; -import org.junit.Test; -import static org.junit.Assert.*; +import org.nanoboot.powerframework.core.PowerException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.*; /** + * * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public class JsonValueTest { @@ -45,9 +50,9 @@ public class JsonValueTest { JsonValue jsonValue; JsonValueType expectedValue; JsonValueType returnedValue = JsonValueType.STRING; - JsonString jsonString; + String jsonString; //act - jsonString = new JsonString("hello"); + jsonString = "hello"; jsonValue = new JsonValue(jsonString); expectedValue = jsonValue.getJsonValueType(); //assert @@ -115,9 +120,9 @@ public class JsonValueTest { JsonValue jsonValue; JsonValueType expectedValue; JsonValueType returnedValue = JsonValueType.BOOLEAN; - JsonBoolean jsonBoolean; + boolean jsonBoolean; //act - jsonBoolean = new JsonBoolean(true); + jsonBoolean = true; jsonValue = new JsonValue(jsonBoolean); expectedValue = jsonValue.getJsonValueType(); //assert @@ -133,9 +138,9 @@ public class JsonValueTest { JsonValue jsonValue; JsonValueType expectedValue; JsonValueType returnedValue = JsonValueType.STRING; - JsonString jsonString; + String jsonString; //act - jsonString = new JsonString("hello"); + jsonString = "hello"; jsonValue = new JsonValue(jsonString); expectedValue = jsonValue.getJsonValueType(); //assert @@ -151,9 +156,9 @@ public class JsonValueTest { JsonValue jsonValue; JsonValueType expectedValue; JsonValueType returnedValue = JsonValueType.CHAR; - JsonChar jsonChar; + char jsonChar; //act - jsonChar = new JsonChar('h'); + jsonChar = 'h'; jsonValue = new JsonValue(jsonChar); expectedValue = jsonValue.getJsonValueType(); //assert @@ -169,9 +174,9 @@ public class JsonValueTest { JsonValue jsonValue; JsonValueType expectedValue; JsonValueType returnedValue = JsonValueType.INT; - JsonInt jsonInt; + int jsonInt; //act - jsonInt = new JsonInt(549); + jsonInt = 549; jsonValue = new JsonValue(jsonInt); expectedValue = jsonValue.getJsonValueType(); //assert @@ -187,9 +192,9 @@ public class JsonValueTest { JsonValue jsonValue; JsonValueType expectedValue; JsonValueType returnedValue = JsonValueType.LONG; - JsonLong jsonLong; + long jsonLong; //act - jsonLong = new JsonLong(4l); + jsonLong = 4l; jsonValue = new JsonValue(jsonLong); expectedValue = jsonValue.getJsonValueType(); //assert @@ -205,9 +210,9 @@ public class JsonValueTest { JsonValue jsonValue; JsonValueType expectedValue; JsonValueType returnedValue = JsonValueType.FLOAT; - JsonFloat jsonFloat; + float jsonFloat; //act - jsonFloat = new JsonFloat(8.6f); + jsonFloat = 8.6f; jsonValue = new JsonValue(jsonFloat); expectedValue = jsonValue.getJsonValueType(); //assert @@ -223,9 +228,9 @@ public class JsonValueTest { JsonValue jsonValue; JsonValueType expectedValue; JsonValueType returnedValue = JsonValueType.DOUBLE; - JsonDouble jsonDouble; + double jsonDouble; //act - jsonDouble = new JsonDouble(8.6d); + jsonDouble = 8.6d; jsonValue = new JsonValue(jsonDouble); expectedValue = jsonValue.getJsonValueType(); //assert @@ -239,12 +244,12 @@ public class JsonValueTest { public void testGetJsonObject() { //arrange boolean isExceptionThrown = false; - JsonString jsonString = new JsonString("hello"); + String jsonString = "hello"; JsonValue jsonValue = new JsonValue(jsonString); //act try { jsonValue.getJsonObject(); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert @@ -261,12 +266,12 @@ public class JsonValueTest { //arrange boolean isExceptionThrown = false; - JsonString jsonString = new JsonString("hello"); + String jsonString = "hello"; JsonValue jsonValue = new JsonValue(jsonString); //act try { jsonValue.getJsonArray(); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert @@ -283,12 +288,12 @@ public class JsonValueTest { //arrange boolean isExceptionThrown = false; - JsonString jsonString = new JsonString("hello"); + String jsonString = "hello"; JsonValue jsonValue = new JsonValue(jsonString); //act try { jsonValue.getJsonBoolean(); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert @@ -305,12 +310,12 @@ public class JsonValueTest { //arrange boolean isExceptionThrown = false; - JsonString jsonString = new JsonString("hello"); + String jsonString = "hello"; JsonValue jsonValue = new JsonValue(jsonString); //act try { jsonValue.getJsonString(); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert @@ -327,12 +332,12 @@ public class JsonValueTest { //arrange boolean isExceptionThrown = false; - JsonString jsonString = new JsonString("hello"); + String jsonString = "hello"; JsonValue jsonValue = new JsonValue(jsonString); //act try { jsonValue.getJsonChar(); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert @@ -349,12 +354,12 @@ public class JsonValueTest { //arrange boolean isExceptionThrown = false; - JsonString jsonString = new JsonString("hello"); + String jsonString = "hello"; JsonValue jsonValue = new JsonValue(jsonString); //act try { jsonValue.getJsonInt(); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert @@ -371,12 +376,12 @@ public class JsonValueTest { //arrange boolean isExceptionThrown = false; - JsonString jsonString = new JsonString("hello"); + String jsonString = "hello"; JsonValue jsonValue = new JsonValue(jsonString); //act try { jsonValue.getJsonLong(); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert @@ -393,12 +398,12 @@ public class JsonValueTest { //arrange boolean isExceptionThrown = false; - JsonString jsonString = new JsonString("hello"); + String jsonString = "hello"; JsonValue jsonValue = new JsonValue(jsonString); //act try { jsonValue.getJsonFloat(); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert @@ -415,12 +420,12 @@ public class JsonValueTest { //arrange boolean isExceptionThrown = false; - JsonString jsonString = new JsonString("hello"); + String jsonString = "hello"; JsonValue jsonValue = new JsonValue(jsonString); //act try { jsonValue.getJsonDouble(); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert diff --git a/power-log/pom.xml b/power-log/pom.xml new file mode 100644 index 0000000..8b02e40 --- /dev/null +++ b/power-log/pom.xml @@ -0,0 +1,64 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-log + jar + + Power Log + Log functionality for the Power library + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + org.nanoboot.powerframework + power-time + ${power.version} + + + org.nanoboot.powerframework + power-utils + ${power.version} + + + + + junit + junit + 4.12 + test + + + + diff --git a/power-log/src/main/java/module-info.java b/power-log/src/main/java/module-info.java new file mode 100644 index 0000000..b4fd93c --- /dev/null +++ b/power-log/src/main/java/module-info.java @@ -0,0 +1,31 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +module powerframework.log { + exports org.nanoboot.powerframework.log; + requires powerframework.time; + requires powerframework.utils; +} diff --git a/power-log/src/main/java/org/nanoboot/powerframework/log/Level.java b/power-log/src/main/java/org/nanoboot/powerframework/log/Level.java new file mode 100644 index 0000000..819c6ca --- /dev/null +++ b/power-log/src/main/java/org/nanoboot/powerframework/log/Level.java @@ -0,0 +1,106 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.log; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public enum Level { + + /** + * + */ + OFF(0, "off", "The highest possible rank and is intended to turn off logging."), + + /** + * + */ + FATAL(1, "fatal", "Severe errors that cause premature termination. Expect these to be immediately visible on a status console."), + + /** + * + */ + ERROR(2, "error", "Other runtime errors or unexpected conditions. Expect these to be immediately visible on a status console."), + + /** + * + */ + WARN(3, "warn", "Use of deprecated APIs, poor use of API, 'almost' errors, other runtime situations that are undesirable or unexpected, but not necessarily \"wrong\". Expect these to be immediately visible on a status console."), + + /** + * + */ + INFO(4, "info", "Interesting runtime events (startup/shutdown). Expect these to be immediately visible on a console, so be conservative and keep to a minimum."), + + /** + * + */ + DEBUG(5, "debug", "Detailed information on the flow through the system. Expect these to be written to logs only. Generally speaking, most lines logged by your application should be written as DEBUG."), + + /** + * + */ + TRACE(6, "trace", "Most detailed information. Expect these to be written to logs only. "), + + /** + * + */ + ALL(7, "all", "All possible information will be logged."); + private final int verbiageIndex; + private final String name; + private final String description; + + Level(int verbiageIndex, + String name, + String description) { + this.verbiageIndex = verbiageIndex; + this.name = name; + this.description = description; + } + + /** + * + * @return + */ + public int getVerbiageIndex() { + return verbiageIndex; + } + + /** + * + * @return + */ + public String getDescription() { + return this.description; + } + + /** + * + * @return + */ + public String getName() { + return name; + } +} diff --git a/power-log/src/main/java/org/nanoboot/powerframework/log/LogRowCreator.java b/power-log/src/main/java/org/nanoboot/powerframework/log/LogRowCreator.java new file mode 100644 index 0000000..2073b28 --- /dev/null +++ b/power-log/src/main/java/org/nanoboot/powerframework/log/LogRowCreator.java @@ -0,0 +1,78 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.log; + +import org.nanoboot.powerframework.time.utils.LocalSettings; +import org.nanoboot.powerframework.time.moment.TimeZone; +import org.nanoboot.powerframework.time.moment.ZonedDateTime; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +class LogRowCreator { + + private static final String DELIMITER = " "; + private static final String START = "["; + private static final String END = "]"; + private static final String STATIC = "----------STATIC"; + private static final String DASH = "-"; + private static final String NOTOKAYOBJECT = "NOT_OKAY_OBJECT"; + + static String createRow(long rowNumber, + Object object, + Level level, + String className, + String message) { + + if(object instanceof String) { + message = message + DELIMITER + "Warning: The object to log is String."; + } + + int hashCode = object == null ? 0 : object.hashCode(); + String hashCodeAsHexString = Integer.toHexString(hashCode); + + String hash = hashCodeAsHexString; + + TimeZone timeZone = LocalSettings.getLocalTimeZone(); + String time = ZonedDateTime.getCurrentZonedDateTimeForTimeZone(timeZone).toString(); + return org.nanoboot.powerframework.utils.StringUtils.appendObjects( + String.format("%08d", rowNumber), DELIMITER, + START, Thread.currentThread().getName(), END, DELIMITER, + level, DELIMITER, + START, time, " ", timeZone.toString(), END, DELIMITER, + hash, DELIMITER, + className, DELIMITER, + message + ); + + } + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private LogRowCreator() { + } +} diff --git a/power-log/src/main/java/org/nanoboot/powerframework/log/Logger.java b/power-log/src/main/java/org/nanoboot/powerframework/log/Logger.java new file mode 100644 index 0000000..1a1516b --- /dev/null +++ b/power-log/src/main/java/org/nanoboot/powerframework/log/Logger.java @@ -0,0 +1,294 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.log; + +import java.io.BufferedWriter; +import java.io.FileWriter; + +/** + * + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Logger { + + private static Level level = Level.OFF; + private static Target target = Target.NOTARGET; + //0 for no limit + private static long maximumLogFileSizeInBytes = 0; + private static boolean logOkayClasses = false; + private static long rowNumber = 0; + + /** + * + * @param classValue + * + * @return + */ + public static Logger getLogger(Class classValue) { + return new Logger(classValue); + } + + /** + * + * @param levelArg + */ + public static void setLevel(Level levelArg) { + level = levelArg; + } + + /** + * + * @return + */ + public static Level getLevel() { + return level; + } + + /** + * + * @param targetArg + */ + public static void setTarget(Target targetArg) { + target = targetArg; + } + + /** + * + * @return + */ + public static Target getTarget() { + return target; + } + + /** + * + * @return + */ + public static long getMaximumLogFileSizeInBytes() { + return maximumLogFileSizeInBytes; + } + +// /** +// * +// * @param digitalInformationUnit +// * @param value +// */ +// public static void setMaximumLogFileSize( +// DigitalInformationUnit digitalInformationUnit, +// long value) { +// maximumLogFileSizeInBytes = digitalInformationUnit.getBytes() * value; +// } + + /** + * + * @return + */ + public static boolean isLogOkayClasses() { + return logOkayClasses; + } + + /** + * + * @param logOkayClasses + */ + public static void setLogOkayClasses(boolean logOkayClasses) { + Logger.logOkayClasses = logOkayClasses; + } + + private static boolean isLevelWanted(Level levelArg) { + if(Logger.getLevel().getVerbiageIndex() == 0) { + return false; + } + return levelArg.getVerbiageIndex() <= Logger.getLevel().getVerbiageIndex(); + } + private final String className; + private final boolean isOkayClass; + + private Logger(Class classValue) { + this.className = classValue.getName(); + isOkayClass = className.startsWith("org.nanoboot.powerframework."); + } + + /** + * + * @param object + * @param message + */ + public void fatal(Object object, + String message) { + log(object, Level.FATAL, message); + } + + /** + * + * @param object + * @param message + */ + public void error(Object object, + String message) { + log(object, Level.ERROR, message); + } + + /** + * + * @param object + * @param message + */ + public void warn(Object object, + String message) { + log(object, Level.WARN, message); + } + + /** + * + * @param object + * @param message + */ + public void info(Object object, + String message) { + log(object, Level.INFO, message); + } + + /** + * + * @param object + * @param message + */ + public void debug(Object object, + String message) { + log(object, Level.DEBUG, message); + } + + /** + * + * @param object + * @param message + */ + public void trace(Object object, + String message) { + log(object, Level.TRACE, message); + } + + /** + * + * @param object + * @param methodName + * @param typeValue + */ + public void traceStartOfMethod(Object object, + String methodName, + Object... typeValue) { + trace(object, MethodStartMessageCreator.createMethodStartMessage(methodName, typeValue)); + } + + /** + * + * @param object + * @param methodName + */ + public void traceStartOfMethod(Object object, + String methodName) { + trace(object, MethodStartMessageCreator.createMethodStartMessage(methodName)); + } + + /** + * + * @param object + * @param level + * @param message + */ + public void log(Object object, + Level level, + String message) { + if((!(isLogOkayClasses())) && this.isOkayClass()) { + return; + } +// if(PseudoRandomGenerator.getGlobalInstance().getInt(0, 3)>1){return;} + if(getTarget() == Target.NOTARGET || !isLevelWanted(level)) { + return; + } + + String row = LogRowCreator.createRow(++rowNumber, object, level, getClassName(), message); + if(target == Target.CONSOLE || target == Target.CONSOLEANDFILES) { + if(level.getVerbiageIndex() <= 2) { + System.err.println(row); + } else { + System.out.println(row); + + } + } + + if(target == Target.FILES || target == Target.CONSOLEANDFILES) { + logStringBuilder.append(row).append("\n"); + final String LOGGINGFILENAME = "log.txt"; + + try (BufferedWriter bw = new BufferedWriter(new FileWriter(LOGGINGFILENAME, true))) { + bw.write(row); + bw.newLine(); + bw.flush(); + } catch (Exception e) { + System.err.println("Can't write next log row to file " + LOGGINGFILENAME); + } + + if(level.getVerbiageIndex() <= 4) { + try (BufferedWriter bw = new BufferedWriter(new FileWriter("info_" + LOGGINGFILENAME, true))) { + bw.write(row); + bw.newLine(); + bw.flush(); + } catch (Exception e) { + System.err.println("Can't write next log row to file " + "info_" + LOGGINGFILENAME); + } + } +// TODO +// write to files + } + } + + private static StringBuilder logStringBuilder = new StringBuilder(); + + public static void saveToFile() { + final String LOGGINGFILENAME = "log.txt"; + try (BufferedWriter bw = new BufferedWriter(new FileWriter(LOGGINGFILENAME, true))) { + bw.write(logStringBuilder.toString()); + logStringBuilder = new StringBuilder(); + bw.newLine(); + bw.flush(); + } catch (Exception e) { + System.err.println("Can't write next log row to file " + LOGGINGFILENAME); + } + } + + private String getClassName() { + return this.className; + } + + /** + * + * @return + */ + public boolean isOkayClass() { + return isOkayClass; + } +} diff --git a/power-log/src/main/java/org/nanoboot/powerframework/log/MethodStartMessageCreator.java b/power-log/src/main/java/org/nanoboot/powerframework/log/MethodStartMessageCreator.java new file mode 100644 index 0000000..c10d178 --- /dev/null +++ b/power-log/src/main/java/org/nanoboot/powerframework/log/MethodStartMessageCreator.java @@ -0,0 +1,83 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.log; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +class MethodStartMessageCreator { + + private static final String ARGUMENTSSTART = "("; + private static final String ARGUMENTSEND = ")"; + + private static final Object[] emptyObjectArray = new Object[]{}; + + static String createMethodStartMessage(String methodName) { + return createMethodStartMessage(methodName, emptyObjectArray); + } + + static String createMethodStartMessage(String methodName, + Object... typeValue) { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("method ").append(methodName).append(" - start - ").append(ARGUMENTSSTART); + + { + for (int i = 0; i < typeValue.length; i++) { + if(i == typeValue.length) { + break; + } + stringBuilder.append(typeValue[i]); + + i++; + if(i == typeValue.length) { + break; + } + stringBuilder.append("="); + stringBuilder.append(typeValue[i]); + + if((i + 1) != typeValue.length) { + stringBuilder.append(", "); + } else { + break; + } + } + } + + stringBuilder.append(ARGUMENTSEND); + if(typeValue.length % 2 != 0) { + stringBuilder.append(" There is a mismatch: The length of typeValue.length%2!=0;"); + } + return stringBuilder.toString(); + } + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private MethodStartMessageCreator() { + } + +} diff --git a/power-log/src/main/java/org/nanoboot/powerframework/log/Target.java b/power-log/src/main/java/org/nanoboot/powerframework/log/Target.java new file mode 100644 index 0000000..3219388 --- /dev/null +++ b/power-log/src/main/java/org/nanoboot/powerframework/log/Target.java @@ -0,0 +1,50 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.log; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public enum Target { + + /** + * + */ + NOTARGET, + + /** + * + */ + CONSOLE, + + /** + * + */ + FILES, + + /** + * + */ + CONSOLEANDFILES; +} diff --git a/power-log/src/main/resources/.gitkeep b/power-log/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-log/src/test/java/org/nanoboot/powerframework/log/.gitkeep b/power-log/src/test/java/org/nanoboot/powerframework/log/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-mail/.gitignore b/power-mail/.gitignore new file mode 100755 index 0000000..e8f4b88 --- /dev/null +++ b/power-mail/.gitignore @@ -0,0 +1,9 @@ +#files to ignore + +*.metadata/** +*.recommenders/** +*target/** +*build/** +*.idea/** +*.class +*.iml diff --git a/power-mail/README.md b/power-mail/README.md new file mode 100755 index 0000000..dc74e79 --- /dev/null +++ b/power-mail/README.md @@ -0,0 +1,2 @@ +# power-mail +todo: create interfaces and integration with Spring and new mailer-cli standalone module diff --git a/power-mail/bin/.gitignore b/power-mail/bin/.gitignore new file mode 100644 index 0000000..c42cc37 --- /dev/null +++ b/power-mail/bin/.gitignore @@ -0,0 +1,2 @@ +mailer.properties +mailer-conf.properties diff --git a/power-mail/bin/backup.sql b/power-mail/bin/backup.sql new file mode 100644 index 0000000..dacbae8 --- /dev/null +++ b/power-mail/bin/backup.sql @@ -0,0 +1,16 @@ +dsdgfsdgrsd +dsdgfsdgrsd +dsdgfsdgrsd +dsdgfsdgrsd +dsdgfsdgrsd +dsdgfsdgrsd +dsdgfsdgrsd +dsdgfsdgrsd +dsdgfsdgrsd +dsdgfsdgrsd +dsdgfsdgrsd +dsdgfsdgrsd +dsdgfsdgrsd +dsdgfsdgrsd +dsdgfsdgrsd +dsdgfsdgrsd diff --git a/power-mail/bin/backupfile.sh b/power-mail/bin/backupfile.sh new file mode 100755 index 0000000..1c3e0d4 --- /dev/null +++ b/power-mail/bin/backupfile.sh @@ -0,0 +1,12 @@ +fileToBackup=$1 + +if [ -n "$fileToBackup" ]; then + echo "Info: Var fileToBackup was supplied! fileToBackup=$fileToBackup" +else + echo "Fatal: Var fileToBackup was not supplied. Exiting" + exit +fi +echo "Sending backup of file $fileToBackup." + +./mailerrv.sh "Sending backup of file $fileToBackup" "Hello,

I send you the backup file: $fileToBackup.

With regards, Robert Vokac." $fileToBackup +#>> ./mailer.log diff --git a/power-mail/bin/mailer.jar b/power-mail/bin/mailer.jar new file mode 100644 index 0000000..4e8bcb3 Binary files /dev/null and b/power-mail/bin/mailer.jar differ diff --git a/power-mail/bin/mailer.properties.template b/power-mail/bin/mailer.properties.template new file mode 100755 index 0000000..316dea4 --- /dev/null +++ b/power-mail/bin/mailer.properties.template @@ -0,0 +1,6 @@ +from=name@gmail.com +serverurl=smtp.gmail.com +serverport=465 +username=name@gmail.com +password=password +ssl=1 diff --git a/power-mail/bin/mailer.sh b/power-mail/bin/mailer.sh new file mode 100755 index 0000000..e703560 --- /dev/null +++ b/power-mail/bin/mailer.sh @@ -0,0 +1,46 @@ +SERVER_CONF=mailer-conf.properties +TO=$1 +SUBJECT=$2 +TEXT=$3 +ATTACHMENT=$4 + +if [ -n "$TO" ]; then + echo "Info: Var TO was supplied! TO=$TO" +else + echo "Fatal: Var TO was not supplied. Exiting" + exit +fi + +if [ -n "$SUBJECT" ]; then + echo "Info: Var SUBJECT was supplied! SUBJECT=$SUBJECT" +else + echo "Fatal: Var SUBJECT was not supplied. Exiting" + exit +fi + +if [ -n "$TEXT" ]; then + echo "Info: Var TEXT was supplied! TEXT=$TEXT" +else + echo "Fatal: Var TEXT was not supplied. Exiting" + exit +fi + +if [ -n "$ATTACHMENT" ]; then + echo "Info: Var ATTACHMENT was supplied! ATTACHMENT=$ATTACHMENT" +else + echo "Info: Var ATTACHMENT was not supplied." +fi + + +export JAVA_HOME=/home/robertvokac/\.jdks/openjdk-16.0.1 + + +$JAVA_HOME/bin/java -jar mailer.jar \ +serverconf=$SERVER_CONF \ +to=$TO \ +"subject=$SUBJECT" \ +"text=$TEXT" \ +attachment=$ATTACHMENT +#>> ./mailer.log + + diff --git a/power-mail/bin/mailerrv.sh b/power-mail/bin/mailerrv.sh new file mode 100755 index 0000000..7cc5586 --- /dev/null +++ b/power-mail/bin/mailerrv.sh @@ -0,0 +1,5 @@ +TO=robertvokac@nanoboot.org + +./mailer.sh $TO "$1" "$2" "$3" + +#>> ./mailer.log diff --git a/power-mail/environment-startup.txt b/power-mail/environment-startup.txt new file mode 100644 index 0000000..e69de29 diff --git a/power-mail/pom.xml b/power-mail/pom.xml new file mode 100755 index 0000000..7907e9f --- /dev/null +++ b/power-mail/pom.xml @@ -0,0 +1,110 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-mail + jar + + Power Mail + Mailing utilities + + + true + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + 3.3.0 + + + + org.nanoboot.powerframework.mail.Main + + + + jar-with-dependencies + + + + + make-assembly + package + + single + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + org.nanoboot.powerframework.mail.Main + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + ${checkstyle.skip} + + + + + + + + + + junit + junit + 4.12 + test + + + com.sun.mail + jakarta.mail + 2.0.1 + + + + + org.projectlombok + lombok + + + diff --git a/power-mail/src/main/java/module-info.java b/power-mail/src/main/java/module-info.java new file mode 100644 index 0000000..fa09e34 --- /dev/null +++ b/power-mail/src/main/java/module-info.java @@ -0,0 +1,31 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +module powerframework.mail { + exports org.nanoboot.powerframework.mail; + requires lombok; + requires jakarta.mail; +} diff --git a/power-mail/src/main/java/org/nanoboot/powerframework/mail/MailBox.java b/power-mail/src/main/java/org/nanoboot/powerframework/mail/MailBox.java new file mode 100644 index 0000000..417b52e --- /dev/null +++ b/power-mail/src/main/java/org/nanoboot/powerframework/mail/MailBox.java @@ -0,0 +1,111 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.mail; + +import jakarta.mail.MessagingException; +import jakarta.mail.Multipart; +import jakarta.mail.PasswordAuthentication; +import jakarta.mail.Session; +import jakarta.mail.Transport; +import lombok.Data; + +import jakarta.mail.internet.InternetAddress; +import jakarta.mail.internet.MimeBodyPart; +import jakarta.mail.internet.MimeMessage; +import jakarta.mail.internet.MimeMultipart; +import java.io.File; +import java.io.IOException; +import java.util.Properties; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +@Data +public class MailBox { + private SmtpServer smtpServer; + public MailBox() { + + } + public MailBox(SmtpServer smtpServer) { + this.smtpServer = smtpServer; + } + /** + * + * @param mailMessage + * @return null, if everything is OK, otherwise the error descriptiopn + */ + public String send (final MailMessage mailMessage, final SmtpUser user) { + + Properties props = new Properties(); + props.put("mail.smtp.host", smtpServer.getServerUrl()); + + props.put("mail.smtp.auth", "true"); + props.put("mail.smtp.port", smtpServer.getServerPort()); + props.put("mail.smtp.ssl.enable", smtpServer.getSsl().equals("1") ? "true" : "false"); + props.put("mail.debug", "true"); + Session session = Session.getDefaultInstance(props, + new jakarta.mail.Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(user.getUserName(), user.getPassword()); + } + }); + + try { + + MimeMessage message = new MimeMessage(session); + message.setFrom(new InternetAddress(smtpServer.getFrom())); + message.setRecipients(jakarta.mail.Message.RecipientType.TO, + InternetAddress.parse(mailMessage.getTo())); + message.setSubject(mailMessage.getSubject(), "utf-8"); + + // if plaint text + // message.setText(target.text); + + Multipart multipart = new MimeMultipart(); + + MimeBodyPart text = new MimeBodyPart(); + // if html text + String type = mailMessage.getMailMessageType() == MailMessageType.TEXT ? "text/plain" : "text/html"; + text.setContent(mailMessage.getText(), type+"; charset=utf-8"); + multipart.addBodyPart(text); + + if(mailMessage.getAttachment() != null && !mailMessage.getAttachment().isEmpty()) { + MimeBodyPart attachment = new MimeBodyPart(); + attachment.attachFile(new File(mailMessage.getAttachment())); + multipart.addBodyPart(attachment); + } + + message.setContent(multipart); + + Transport.send(message); + + System.out.println("Done"); + + } catch (MessagingException | IOException e) { + throw new RuntimeException(e.getMessage(), e); + } + + return null; + } +} diff --git a/power-mail/src/main/java/org/nanoboot/powerframework/mail/MailMessage.java b/power-mail/src/main/java/org/nanoboot/powerframework/mail/MailMessage.java new file mode 100644 index 0000000..47144d4 --- /dev/null +++ b/power-mail/src/main/java/org/nanoboot/powerframework/mail/MailMessage.java @@ -0,0 +1,38 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.mail; + +import lombok.Data; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@Data +public class MailMessage { + private String to; + private String subject; + private String text; + private String attachment; + private MailMessageType mailMessageType = MailMessageType.TEXT; +} diff --git a/power-mail/src/main/java/org/nanoboot/powerframework/mail/MailMessageType.java b/power-mail/src/main/java/org/nanoboot/powerframework/mail/MailMessageType.java new file mode 100644 index 0000000..6e31492 --- /dev/null +++ b/power-mail/src/main/java/org/nanoboot/powerframework/mail/MailMessageType.java @@ -0,0 +1,30 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.mail; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public enum MailMessageType { + TEXT, HTML; +} diff --git a/power-mail/src/main/java/org/nanoboot/powerframework/mail/Main.java b/power-mail/src/main/java/org/nanoboot/powerframework/mail/Main.java new file mode 100755 index 0000000..b539258 --- /dev/null +++ b/power-mail/src/main/java/org/nanoboot/powerframework/mail/Main.java @@ -0,0 +1,111 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.mail; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class Main { + private static class Keys { + + public static final String SERVER_CONF = "serverconf"; + public static final String FROM = "from"; + public static final String SERVER_URL = "serverurl"; + public static final String SERVER_PORT = "serverport"; + public static final String USERNAME = "username"; + public static final String PASSWORD = "password"; + public static final String SSL = "ssl"; + + public static final String TO = "to"; + public static final String SUBJECT = "subject"; + public static final String TEXT = "text"; + public static final String ATTACHMENT = "attachment"; + } + + //https://www.baeldung.com/java-email + + public static void main(String[] args) { + Properties argProps = makePropFromArgs(args); + SmtpServer server = new SmtpServer(); + + server.setFrom(argProps.getProperty(Keys.FROM)); + server.setServerUrl(argProps.getProperty(Keys.SERVER_URL)); + server.setServerPort(argProps.getProperty(Keys.SERVER_PORT)); + SmtpUser user = new SmtpUser(); + user.setUserName(argProps.getProperty(Keys.USERNAME)); + user.setPassword(argProps.getProperty(Keys.PASSWORD)); + server.setSsl(argProps.getProperty(Keys.SSL)); + + MailMessage target = new MailMessage(); + target.setTo(argProps.getProperty(Keys.TO)); + target.setSubject(argProps.getProperty(Keys.SUBJECT)); + target.setText(argProps.getProperty(Keys.TEXT)); + if (argProps.containsKey(Keys.ATTACHMENT)) { + target.setAttachment(argProps.getProperty(Keys.ATTACHMENT)); + } + + MailBox mailBox = new MailBox(server); + mailBox.send(target,user); + } + public static Properties makePropFromArgs(String[] args) { + Properties prop = new Properties(); + for(String arg : args) { + System.out.println(arg); + String[] array = arg.split("="); + if(array.length == 1) { + if (arg.contains(Keys.ATTACHMENT)) { + continue; + } else { + throw new RuntimeException("Parsing key and value for \"" + arg + "\" failed."); + } + } + String key = array[0]; + String value = array[1]; + prop.put(key, value); + } + if (prop.containsKey(Keys.SERVER_CONF)) { + Properties serverConfProp = loadPropFromFile(prop.getProperty(Keys.SERVER_CONF)); + prop.putAll(serverConfProp); + } + return prop; + } + + private static Properties loadPropFromFile(String filePath) { + try (InputStream input = new FileInputStream(filePath)) { + + Properties prop = new Properties(); + + // load a properties file + prop.load(input); + return prop; + } catch (IOException ex) { + ex.printStackTrace(); + throw new RuntimeException(ex.getMessage(), ex); + } + } +} diff --git a/power-mail/src/main/java/org/nanoboot/powerframework/mail/SmtpServer.java b/power-mail/src/main/java/org/nanoboot/powerframework/mail/SmtpServer.java new file mode 100644 index 0000000..e55f12a --- /dev/null +++ b/power-mail/src/main/java/org/nanoboot/powerframework/mail/SmtpServer.java @@ -0,0 +1,36 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.mail; + +import lombok.Data; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +@Data +public class SmtpServer { + private String from; + private String serverUrl; + private String serverPort; + private String ssl; + } diff --git a/power-mail/src/main/java/org/nanoboot/powerframework/mail/SmtpUser.java b/power-mail/src/main/java/org/nanoboot/powerframework/mail/SmtpUser.java new file mode 100644 index 0000000..7dd73ba --- /dev/null +++ b/power-mail/src/main/java/org/nanoboot/powerframework/mail/SmtpUser.java @@ -0,0 +1,34 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.mail; + +import lombok.Data; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +@Data +public class SmtpUser { + private String userName; + private String password; +} diff --git a/power-mail/src/main/resources/.gitkeep b/power-mail/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-mail/src/test/java/org/nanoboot/powerframework/mail/.gitkeep b/power-mail/src/test/java/org/nanoboot/powerframework/mail/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-persistence/pom.xml b/power-persistence/pom.xml new file mode 100644 index 0000000..8133dce --- /dev/null +++ b/power-persistence/pom.xml @@ -0,0 +1,69 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-persistence + jar + + Power Persistence + Persistence functionality for the Power library + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + org.nanoboot.powerframework + power-db + ${power.version} + + + org.nanoboot.powerframework + power-sql + ${power.version} + + + org.nanoboot.powerframework + power-log + ${power.version} + + + + + junit + junit + 4.12 + test + + + + diff --git a/power-persistence/src/main/java/module-info.java b/power-persistence/src/main/java/module-info.java new file mode 100644 index 0000000..136cfe5 --- /dev/null +++ b/power-persistence/src/main/java/module-info.java @@ -0,0 +1,34 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + module powerframework.persistence { + requires powerframework.json; + requires powerframework.db; + requires powerframework.log; + requires powerframework.sql; + requires powerframework.utils; + requires powerframework.core; +} diff --git a/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/AttributeType.java b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/AttributeType.java new file mode 100644 index 0000000..10b62ec --- /dev/null +++ b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/AttributeType.java @@ -0,0 +1,84 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.persistence; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import org.nanoboot.powerframework.persistence.annotations.ForeignEntity; + +/** + * Here goes the description of this class. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public enum AttributeType { + + ENTITY, + NUMBER, + REAL, + TEXT, + BOOLEAN, + BLOB; + + public static AttributeType getAttributeType(Field field) { + + String canonicalName = EntityAttribute.loadJavaType(field); + switch (canonicalName) { + case "int": + return NUMBER; + case "long": + return NUMBER; + case "byte": + return NUMBER; + case "short": + return NUMBER; + case "float": + return REAL; + case "double": + return REAL; + case "boolean": + return BOOLEAN; + case "java.lang.Integer": + return NUMBER; + case "java.lang.Long": + return NUMBER; + case "java.lang.Byte": + return NUMBER; + case "java.lang.Short": + return NUMBER; + case "java.lang.Float": + return REAL; + case "java.lang.Double": + return REAL; + case "java.lang.Boolean": + return BOOLEAN; + case "java.lang.String": + return TEXT; + } + for (Annotation a : field.getAnnotations()) { + if(a instanceof ForeignEntity) { + return ENTITY; + } + } + throw new PersistenceException(("Cannot get AttributeType from canonicalName " + canonicalName)); + } +} diff --git a/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/BaseColumns.java b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/BaseColumns.java new file mode 100644 index 0000000..b0d3461 --- /dev/null +++ b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/BaseColumns.java @@ -0,0 +1,56 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.persistence; + +/** + * Here goes the description of this class. + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class BaseColumns { + + /** + * Logger for this class. + */ + private static final org.nanoboot.powerframework.log.Logger LOG = org.nanoboot.powerframework.log.Logger.getLogger(BaseColumns.class); + + /** + * Constant description + */ + private static final String CONSTANT = "constant"; + + /** + * Field description + */ + private String name; + + /** + * Constructor + * + * Not meant to be instantiated. + */ + public BaseColumns() { + } + + public static final String UUID = "UUID"; +} diff --git a/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/EntityAttribute.java b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/EntityAttribute.java new file mode 100644 index 0000000..6fab128 --- /dev/null +++ b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/EntityAttribute.java @@ -0,0 +1,141 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.persistence; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import org.nanoboot.powerframework.persistence.annotations.Attribute; +import org.nanoboot.powerframework.persistence.annotations.AttributeName; +import org.nanoboot.powerframework.persistence.annotations.ForeignEntity; +import org.nanoboot.powerframework.persistence.annotations.UUID; +import org.nanoboot.powerframework.utils.NamingConvention; + +/** + * Here goes the description of this class. + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class EntityAttribute { + + /** + * Logger for this class. + */ + private static final org.nanoboot.powerframework.log.Logger LOG = org.nanoboot.powerframework.log.Logger.getLogger(EntityAttribute.class); + + /** + * Constant description + */ + private static final String CONSTANT = "constant"; + + static EntityAttribute create(Field fIn) { + try { + return new EntityAttribute(fIn); + } catch (PersistenceException e) { + //e.printStackTrace(); + System.out.println(fIn.getName() + " failed"); + return null; + } + + } + + private String name; + private AttributeType type; + private Class entity; + private boolean uuid = false; + private String javaName; + private String javaType; + + private EntityAttribute(Field field) { + System.out.println("Processing field " + field.getName()); + boolean isColumn = false; + String columnName = null; + Class foreignEntity = null; + + for (Annotation a : field.getDeclaredAnnotations()) { + System.out.println("Found annotation " + a.annotationType()); + if(a instanceof Attribute) { + isColumn = true; + continue; + } + if(a instanceof AttributeName) { + columnName = ((AttributeName) a).name(); + continue; + } + + if(a instanceof ForeignEntity) { + foreignEntity = ((ForeignEntity) a).clazz(); + continue; + } + if(a instanceof UUID) { + uuid = true; + continue; + } + + } + if(!isColumn) { + throw new PersistenceException("Field " + field.getName() + " in class " + field.getDeclaringClass().getName() + " is not annotated with @Column"); + } + if(columnName == null) { + columnName = org.nanoboot.powerframework.utils.NamingConventionConvertor.convert(field.getName(), NamingConvention.JAVA_FIELD, NamingConvention.DATABASE); + } + name = columnName; + type = AttributeType.getAttributeType(field); + entity = foreignEntity; + javaName = field.getName(); + javaType = loadJavaType(field); + + } + + public String getName() { + return name; + } + + public AttributeType getType() { + return type; + } + + public Class getEntity() { + + return entity; + } + + public boolean isUUID() { + return uuid; + } + + public boolean isForeignEntity() { + return entity != null; + } + + public String getJavaName() { + return javaName; + } + + public String getJavaType() { + return javaType; + } + + static String loadJavaType(Field fieldIn) { + return fieldIn.getType().getCanonicalName(); + } +} diff --git a/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/EntityManager.java b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/EntityManager.java new file mode 100644 index 0000000..f267012 --- /dev/null +++ b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/EntityManager.java @@ -0,0 +1,286 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.persistence; + +import java.util.ArrayList; +import org.nanoboot.powerframework.json.JsonObject; +import org.nanoboot.powerframework.sql.core.ColumnNameValue; +import org.nanoboot.powerframework.db.manager.Database; +import org.nanoboot.powerframework.sql.core.SqlStatementCreator; + +/** + * Here goes the description of this class. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class EntityManager { + + /** + * Logger for this class. + */ + private static final org.nanoboot.powerframework.log.Logger LOG = org.nanoboot.powerframework.log.Logger.getLogger(EntityManager.class); + + /** + * Constant description + */ + private static final String CONSTANT = "constant"; + private static final EntityStorage entityStorage = new EntityStorage(); + + /** + * Field description + */ + /** + * Constructor + * + * Not meant to be instantiated. + */ + private EntityManager() { + super(); + } + + private static Database database = null; + + public static void init(Database databaseIn) { + database = databaseIn; + } + + public static Database getDatabase() { + return database; + } + + public static Object load(Class clazz, String uid) { + if(!entityStorage.hasEntity(uid)) { + Object object = loadEntityFromDatabase(clazz, uid); + entityStorage.putEntity(object); + } + return entityStorage.getEntity(uid); + + } + + private static Object loadEntityFromDatabase(Class clazz, String uid) { + System.out.println(clazz + " " + uid); + Object object; + try { + object = clazz.newInstance(); + } catch (InstantiationException ex) { + throw new PersistenceException(ex.getMessage()); + } catch (IllegalAccessException ex) { + throw new PersistenceException(ex.getMessage()); + } + EntitySchema entitySchema = EntitySchema.getSchema(clazz); + JsonObject row = getDatabase().getRow(entitySchema.getName(), uid); + for (EntityAttribute a : entitySchema.getAttributesList()) { + String columnName = a.getName(); + String columnValue = row.getString(columnName); + AttributeType type = a.getType(); + String javaName = a.getJavaName(); + String javaType = a.getJavaType(); + System.out.println("Setting " + object.getClass().getName() + " " + javaName + " " + javaType + " " + columnValue); + setAttribute(object, type, javaName, javaType, columnValue); + + } + return object; + } + + private static void setAttribute(Object object, AttributeType attributeType, String javaName, String javaType, String valueIn) { + switch (javaType) { + + case "int": { + Integer value = Integer.valueOf(valueIn); + MethodInvocation.setInt(object, javaName, value); + } + ; + break; + case "short": { + Short value = Short.valueOf(valueIn); + MethodInvocation.setShort(object, javaName, value); + } + break; + case "byte": { + Byte value = Byte.valueOf(valueIn); + MethodInvocation.setByte(object, javaName, value); + } + break; + case "long": { + Long value = Long.valueOf(valueIn); + MethodInvocation.setLong(object, javaName, value); + } + break; + case "float": { + Float value = Float.valueOf(valueIn); + MethodInvocation.setFloat(object, javaName, value); + } + break; + case "double": { + Double value = Double.valueOf(valueIn); + MethodInvocation.setDouble(object, javaName, value); + } + break; + case "boolean": { + Boolean value = Boolean.valueOf(valueIn); + MethodInvocation.setBoolean(object, javaName, value); + } + case "java.lang.Integer": { + Integer value = Integer.valueOf(valueIn); + MethodInvocation.setInt(object, javaName, value); + } + ; + break; + case "java.lang.Short": { + Short value = Short.valueOf(valueIn); + MethodInvocation.setShort(object, javaName, value); + } + break; + case "java.lang.Byte": { + Byte value = Byte.valueOf(valueIn); + MethodInvocation.setByte(object, javaName, value); + } + break; + case "java.lang.Long": { + Long value = Long.valueOf(valueIn); + MethodInvocation.setLong(object, javaName, value); + } + break; + case "java.lang.Float": { + Float value = Float.valueOf(valueIn); + MethodInvocation.setFloat(object, javaName, value); + } + break; + case "java.lang.Double": { + Double value = Double.valueOf(valueIn); + MethodInvocation.setDouble(object, javaName, value); + } + break; + case "java.lang.Boolean": { + Boolean value = Boolean.valueOf(valueIn); + MethodInvocation.setBoolean(object, javaName, value); + } + case "java.lang.String": { + String value = valueIn; + MethodInvocation.setString(object, javaName, value); + } + break; + + case "org.nanoboot.powerframework.collections.bit.Blob": { +// Integer value = Integer.valueOf(valueIn); +// MethodInvocation.setInt(object, javaName, value); + } + break; + default: { + throw new PersistenceException("Cannot set attribute " + javaName); + } + } + + } + + public static void persist(Object object) { + EntitySchema entitySchema = EntitySchema.getSchema(object.getClass()); + + boolean existTable = getDatabase().existTable(entitySchema.getName()); + System.out.println("Table " + entitySchema.getName() + "exist?=" + existTable); + if(!existTable) { + getDatabase().execute(entitySchema.createSqlCreateStatement()); + } + + boolean insert = !EntityManager.isInDatabase(object); + boolean update = EntityManager.isInDatabase(object); + + if(insert) { + addEntityToDatabase(object, entitySchema); + } + if(update) { + updateEntityInDatabase(object, entitySchema); + } + + } + + private static void addEntityToDatabase(Object object, EntitySchema entitySchema) { + String uuid = Utils.getUUID(); + Utils.setUUIDTo(object, uuid); + String[] valuesIn = new String[entitySchema.getAttributesList().size()]; + int index = 0; + for (EntityAttribute a : entitySchema.getAttributesList()) { + String value = ""; + + value = JavaSqlConvertor.getStringFromJava(object, a); + + valuesIn[index++] = value; + } + + String sqlInsert = SqlStatementCreator.createInsert(entitySchema.getName(), valuesIn); + getDatabase().execute(sqlInsert); + + } + + private static void updateEntityInDatabase(Object object, EntitySchema entitySchema) { + JsonObject row = getDatabase().getRow(entitySchema.getName(), MethodInvocation.getString(object, entitySchema.getIdJavaName())); + ArrayList changedAttributesList = new ArrayList<>(); + for (EntityAttribute a : entitySchema.getAttributesList()) { + String stringValue = row.getString(a.getName()); + if(a.getType() == AttributeType.TEXT) { + stringValue = '\'' + stringValue + '\''; + } + String entityValue = JavaSqlConvertor.getStringFromJava(object, a); + + boolean different = !stringValue.equals(entityValue); + if(different) { + + changedAttributesList.add(a); + } + } + ColumnNameValue[] columnNameValuesArray = new ColumnNameValue[changedAttributesList.size()]; + int index = 0; + for (EntityAttribute a : changedAttributesList) { + ColumnNameValue columnNameValue = new ColumnNameValue(a.getName(), JavaSqlConvertor.getStringFromJava(object, a)); + columnNameValuesArray[index++] = columnNameValue; + } + if(!changedAttributesList.isEmpty()) { + String conditions = entitySchema.getIdJavaName() + "='" + Utils.getUUIDFrom(object) + "'"; + String sqlUpdateStatement = SqlStatementCreator.createUpdate(entitySchema.getName(), conditions, columnNameValuesArray); + getDatabase().execute(sqlUpdateStatement); + } + } + + public static void delete(Object object) { + if(!EntityManager.isInDatabase(object)) { + throw new PersistenceException("Cannot delete object " + object.toString() + "from database. The object is not in the database."); + } + EntitySchema entitySchema = EntitySchema.getSchema(object.getClass()); + + String javaName = entitySchema.getIdJavaName(); + System.out.println("javaName=" + javaName); + + getDatabase().execute("DELETE FROM " + entitySchema.getName() + " WHERE " + entitySchema.getIdName() + "='" + getId(object) + "'"); + entityStorage.deleteEntity(object); + } + + private static String getId(Object object) { + EntitySchema entitySchema = EntitySchema.getSchema(object.getClass()); + return MethodInvocation.getString(object, entitySchema.getIdJavaName()); + } + + public static boolean isInDatabase(Object object) { + EntitySchema entitySchema = EntitySchema.getSchema(object.getClass()); + + return MethodInvocation.getString(object, entitySchema.getIdJavaName()) != null; + } +} diff --git a/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/EntityPointer.java b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/EntityPointer.java new file mode 100644 index 0000000..3c5097d --- /dev/null +++ b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/EntityPointer.java @@ -0,0 +1,61 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.persistence; + +/** + * Here goes the description of this class. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class EntityPointer { + + /** + * Logger for this class. + */ + private static final org.nanoboot.powerframework.log.Logger LOG = org.nanoboot.powerframework.log.Logger.getLogger(EntityPointer.class); + + /** + * Constant description + */ + private static final String CONSTANT = "constant"; + + /** + * Field description + */ + private final Class classValue; + + private final String uuid; + + EntityPointer(Class classValueIn, String uuidIn) { + this.classValue = classValueIn; + this.uuid = uuidIn; + } + + public Class getClassValue() { + return classValue; + } + + public String getUUID() { + return uuid; + } + +} diff --git a/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/EntitySchema.java b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/EntitySchema.java new file mode 100644 index 0000000..834d8b2 --- /dev/null +++ b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/EntitySchema.java @@ -0,0 +1,216 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.persistence; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import org.nanoboot.powerframework.persistence.annotations.Entity; +import org.nanoboot.powerframework.persistence.annotations.EntityName; +import org.nanoboot.powerframework.utils.NamingConvention; +import org.nanoboot.powerframework.utils.annotations.Done; + +/** + * Here goes the description of this class. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class EntitySchema { + + /** + * Logger for this class. + */ + private static final org.nanoboot.powerframework.log.Logger LOG = org.nanoboot.powerframework.log.Logger.getLogger(EntitySchema.class); + + /** + * Constant description + */ + private static final String CONSTANT = "constant"; + private static final Map map = new HashMap<>(); + + private String name; + private String uuid = null; + private String UUIDJavaName = null; + + private final java.util.ArrayList attributesList = new java.util.ArrayList<>(); + + @Done + public static EntitySchema getSchema(Class clazz) { + + String entityName = getEntityNameFromClass(clazz); + return getSchemaByName(entityName, clazz); + } + + @Done + private static String getEntityNameFromClass(Class clazz) { + String entityName = null; + boolean isEntity = false; + for (Annotation a : clazz.getAnnotations()) { + System.out.println("Found annotation " + a.toString()); + if(a instanceof Entity) { + isEntity = true; + continue; + } + if(a instanceof EntityName) { + entityName = ((EntityName) a).name(); + continue; + } + }; + if(!isEntity) { + throw new PersistenceException("Class " + clazz + " is not annotated with @Entity. Cannot create schema from this class"); + } + if(entityName != null) { + return entityName; + } + entityName = org.nanoboot.powerframework.utils.NamingConventionConvertor.convert(clazz.getName(), NamingConvention.JAVA_FIELD, NamingConvention.DATABASE); + return entityName; + } + + @Done + private static EntitySchema getSchemaByName(String entityName, Class clazz) { + if(!map.containsKey(entityName)) { + map.put(entityName, new EntitySchema(clazz)); + } + return map.get(entityName); + } + + private EntitySchema(Class clazz) { + this.name = getEntityNameFromClass(clazz); + loadAttributesList(clazz); + for (EntityAttribute a : attributesList) { + if(a.isUUID()) { + this.uuid = a.getName(); + this.UUIDJavaName = a.getJavaName(); + } + } + if(uuid == null) { + throw new PersistenceException("Class " + clazz + " has no field annotated with @UUID. Cannot create schema from this class"); + + } + + } + + private void loadAttributesList(Class clazz) { + Field[] fields = clazz.getDeclaredFields(); + System.out.println("class " + clazz + " has " + fields.length); + for (Field f : fields) { + + EntityAttribute attribute = EntityAttribute.create(f); + System.out.println("Attribute for " + f.getName() + " is " + attribute); + if(attribute != null) { + + attributesList.add(attribute); + } + } + System.out.println("attributesList.size()=" + attributesList.size()); + + } + + public String getName() { + return name; + } + + public String getIdName() { + return uuid; + } + + public ArrayList getForeingKeys() { + ArrayList list = new ArrayList<>(); + for (EntityAttribute a : getAttributesList()) { + if(a.isForeignEntity()) { + list.add(a); + } + } + return list; + } + + /** + * Field description + */ + public ArrayList getAttributesList() { + return attributesList; + } + + public String getIdJavaName() { + return UUIDJavaName; + } + + public String createSqlCreateStatement() { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("CREATE TABLE "); + stringBuilder.append(this.getName()); + stringBuilder.append("(\n"); + + int aCount = getAttributesList().size(); + int attributeNumber = 0; + for (EntityAttribute a : getAttributesList()) { + attributeNumber++; + stringBuilder.append("\t"); + stringBuilder.append(a.getName()); + stringBuilder.append(" "); + if(a.getType() == AttributeType.ENTITY || a.getType() == AttributeType.BOOLEAN || a.getType() == AttributeType.NUMBER) { + stringBuilder.append("INTEGER"); + } else { + stringBuilder.append(a.getType().name()); + } + if(a.isUUID()) { + stringBuilder.append(" PRIMARY KEY"); + } + if(attributeNumber < aCount) { + stringBuilder.append(", "); + } + + stringBuilder.append("\n"); + } + + ArrayList foreignKeysList = getForeingKeys(); + int foreingKeysCount = foreignKeysList.size(); + if(!getForeingKeys().isEmpty()) { + attributeNumber = 0; + + for (EntityAttribute a : foreignKeysList) { + attributeNumber++; + stringBuilder.append(", \n"); + stringBuilder.append("FOREIGN KEY("); + stringBuilder.append(a.getName()); + stringBuilder.append(") REFERENCES "); + + EntitySchema foreingKeyEntitySchema = EntitySchema.getSchema(a.getEntity()); + stringBuilder.append(foreingKeyEntitySchema.getName()); + stringBuilder.append(" ("); + stringBuilder.append(foreingKeyEntitySchema.getIdName()); + stringBuilder.append(")"); + + if(attributeNumber < foreingKeysCount) { + stringBuilder.append(", "); + } + + stringBuilder.append("\n"); + } + } + stringBuilder.append(");"); + return stringBuilder.toString(); + } +} diff --git a/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/EntityStorage.java b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/EntityStorage.java new file mode 100644 index 0000000..2022eb6 --- /dev/null +++ b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/EntityStorage.java @@ -0,0 +1,86 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.persistence; + +import java.util.HashMap; +import java.util.Map; + +/** + * Here goes the description of this class. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class EntityStorage { + + /** + * Logger for this class. + */ + private static final org.nanoboot.powerframework.log.Logger LOG = org.nanoboot.powerframework.log.Logger.getLogger(EntityStorage.class); + + /** + * Constant description + */ + private static final String CONSTANT = "constant"; + + /** + * Field description + */ + private static final Map entityMap = new HashMap<>(); + + /** + * Constructor + * + * Constructor description + * + * @param nameIn + */ + public EntityStorage() { + } + + public Object getEntity(String uid) { + + if(entityMap.containsKey(uid)) { + return entityMap.get(uid); + } + return null; + + } + + public boolean hasEntity(String uid) { + return entityMap.containsKey(uid); + } + + public void putEntity(Object object) { + EntitySchema entitySchema = EntitySchema.getSchema(object.getClass()); + String uid = Utils.getUUIDFrom(object); + if(entityMap.containsKey(uid)) { + throw new PersistenceException("Cannot put entity " + entitySchema.getName() + " with uid " + uid + " There is already a entity with the class and uid in the storage."); + } + entityMap.put(uid, object); + + } + + public void deleteEntity(Object object) { + String uid = Utils.getUUIDFrom(object); + entityMap.remove(uid); + } +} diff --git a/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/JavaSqlConvertor.java b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/JavaSqlConvertor.java new file mode 100644 index 0000000..ac9e7af --- /dev/null +++ b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/JavaSqlConvertor.java @@ -0,0 +1,104 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.persistence; + +/** + * Here goes the description of this class. + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class JavaSqlConvertor { + + /** + * Logger for this class. + */ + private static final org.nanoboot.powerframework.log.Logger LOG = org.nanoboot.powerframework.log.Logger.getLogger(JavaSqlConvertor.class); + + /** + * Constant description + */ + private static final String CONSTANT = "constant"; + + /** + * Field description + */ + private String name; + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private JavaSqlConvertor() { + } + + static String getStringFromJava(Object object, EntityAttribute attribute) { + String value = ""; + if(attribute.getJavaType().equals("int")) { + value = String.valueOf(MethodInvocation.getInt(object, attribute.getJavaName())); + } + if(attribute.getJavaType().equals("byte")) { + value = String.valueOf(MethodInvocation.getByte(object, attribute.getJavaName())); + } + if(attribute.getJavaType().equals("short")) { + value = String.valueOf(MethodInvocation.getShort(object, attribute.getJavaName())); + } + if(attribute.getJavaType().equals("long")) { + value = String.valueOf(MethodInvocation.getLong(object, attribute.getJavaName())); + } + if(attribute.getJavaType().equals("float")) { + value = String.valueOf(MethodInvocation.getFloat(object, attribute.getJavaName())); + } + if(attribute.getJavaType().equals("double")) { + value = String.valueOf(MethodInvocation.getDouble(object, attribute.getJavaName())); + } + if(attribute.getJavaType().equals("boolean")) { + value = MethodInvocation.getBoolean(object, attribute.getJavaName()) ? "1" : "0"; + } + if(attribute.getJavaType().equals("java.lang.Integer")) { + value = String.valueOf(MethodInvocation.getInt(object, attribute.getJavaName())); + } + if(attribute.getJavaType().equals("java.lang.Byte")) { + value = String.valueOf(MethodInvocation.getByte(object, attribute.getJavaName())); + } + if(attribute.getJavaType().equals("java.lang.Short")) { + value = String.valueOf(MethodInvocation.getShort(object, attribute.getJavaName())); + } + if(attribute.getJavaType().equals("java.lang.Long")) { + value = String.valueOf(MethodInvocation.getLong(object, attribute.getJavaName())); + } + if(attribute.getJavaType().equals("java.lang.Float")) { + value = String.valueOf(MethodInvocation.getFloat(object, attribute.getJavaName())); + } + if(attribute.getJavaType().equals("java.lang.Double")) { + value = String.valueOf(MethodInvocation.getDouble(object, attribute.getJavaName())); + } + if(attribute.getJavaType().equals("java.lang.Boolean")) { + value = MethodInvocation.getBoolean(object, attribute.getJavaName()) ? "1" : "0"; + } + if(attribute.getJavaType().equals("java.lang.String")) { + value = '\'' + MethodInvocation.getString(object, attribute.getJavaName()) + '\''; + } + return value; + } +} diff --git a/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/MethodInvocation.java b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/MethodInvocation.java new file mode 100644 index 0000000..0f29a80 --- /dev/null +++ b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/MethodInvocation.java @@ -0,0 +1,173 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.persistence; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * Here goes the description of this class. + * + * @author Robert Vokac + * @since 0.0.0 + * + */ +public class MethodInvocation { + + /** + * Logger for this class. + */ + private static final org.nanoboot.powerframework.log.Logger LOG = org.nanoboot.powerframework.log.Logger.getLogger(MethodInvocation.class); + + /** + * Constant description + */ + private static final String CONSTANT = "constant"; + + /** + * Field description + */ + private String name; + + public static void setInt(Object object, String javaName, Integer value) { + set(object, javaName, value, Integer.class); + + } + + public static Integer getInt(Object object, String javaName) { + return (Integer) get(object, javaName); + + } + + public static void setShort(Object object, String javaName, Short value) { + set(object, javaName, value, Short.class); + + } + + public static Short getShort(Object object, String javaName) { + return (Short) get(object, javaName); + + } + + public static void setByte(Object object, String javaName, Byte value) { + set(object, javaName, value, Byte.class); + + } + + public static Byte getByte(Object object, String javaName) { + return (Byte) get(object, javaName); + + } + + public static void setLong(Object object, String javaName, Long value) { + set(object, javaName, value, Long.class); + + } + + public static Long getLong(Object object, String javaName) { + return (Long) get(object, javaName); + + } + + public static void setFloat(Object object, String javaName, Float value) { + set(object, javaName, value, float.class); + + } + + public static Float getFloat(Object object, String javaName) { + return (Float) get(object, javaName); + + } + + public static void setDouble(Object object, String javaName, Double value) { + set(object, javaName, value, double.class); + + } + + public static Double getDouble(Object object, String javaName) { + return (Double) get(object, javaName); + + } + + public static void setBoolean(Object object, String javaName, Boolean value) { + set(object, javaName, value, boolean.class); + + } + + public static Boolean getBoolean(Object object, String javaName) { + return (Boolean) get(object, javaName); + + } + + public static void setString(Object object, String javaName, String value) { + set(object, javaName, value, String.class); + + } + + public static String getString(Object object, String javaName) { + return (String) get(object, javaName); + + } + + private static Object get(Object object, String javaName) { + java.lang.reflect.Method method = getMethod(object, javaName, false); + return invokeMethod(method, object); + + } + + private static void set(Object object, String javaName, Object value, Class type) { + java.lang.reflect.Method method = getMethod(object, javaName, true, type); + invokeMethod(method, object, value); + + } + + private static Object invokeMethod(Method method, Object obj, Object... args) { + + try { + return method.invoke(obj, args); + } catch (IllegalArgumentException e) { + throw new PersistenceException(e.getMessage()); + } catch (IllegalAccessException e) { + throw new PersistenceException(e.getMessage()); + } catch (InvocationTargetException e) { + System.out.println(method.getName() + args.length); + e.printStackTrace(); + throw new PersistenceException(e.getMessage()); + } + + } + + private static Method getMethod(Object object, String javaName, boolean isSet, Class... parameterTypes) { + String getMethodName = isSet ? Utils.createSetMethodName(javaName) : Utils.createGetMethodName(javaName); + java.lang.reflect.Method method; + try { + method = object.getClass().getDeclaredMethod(getMethodName, parameterTypes); + + } catch (SecurityException e) { + throw new PersistenceException(e.getMessage()); + } catch (NoSuchMethodException e) { + e.printStackTrace(); + throw new PersistenceException(e.getMessage()); + } + return method; + } + +} diff --git a/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/PersistenceException.java b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/PersistenceException.java new file mode 100644 index 0000000..7c156ed --- /dev/null +++ b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/PersistenceException.java @@ -0,0 +1,37 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.persistence; + +import org.nanoboot.powerframework.core.PowerException; + + +/** + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class PersistenceException extends PowerException { + + public PersistenceException(String message) { + super(message); + } + +} diff --git a/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/Utils.java b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/Utils.java new file mode 100644 index 0000000..63e6926 --- /dev/null +++ b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/Utils.java @@ -0,0 +1,118 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.persistence; + +import java.util.UUID; + +/** + * Here goes the description of this class. + * + * @author Robert Vokac + * @since 0.0.0 + * + */ +public class Utils { + + /** + * Logger for this class. + */ + private static final org.nanoboot.powerframework.log.Logger LOG = org.nanoboot.powerframework.log.Logger.getLogger(Utils.class); + + /** + * Constant description + */ + private static final String SET = "set"; + private static final String GET = "get"; + /** + * Field description + */ + private String name; + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private Utils() { + } + + static String createSetMethodName(String javaName) { + return SET + makeFirstLetterUpperCase(javaName); + } + + static String createGetMethodName(String javaName) { + return GET + makeFirstLetterUpperCase(javaName); + } + + private static String makeFirstLetterUpperCase(String string) { + return string.substring(0, 1).toUpperCase() + string.substring(1, string.length()); + } + + static String getUUIDFrom(Object object) { + EntitySchema entitySchema = EntitySchema.getSchema(object.getClass()); + return MethodInvocation.getString(object, entitySchema.getIdJavaName()); + } + + static void setUUIDTo(Object object, String uuid) { + EntitySchema entitySchema = EntitySchema.getSchema(object.getClass()); + MethodInvocation.setString(object, entitySchema.getIdJavaName(), uuid); + } + + public static String getUUID() { +// MessageDigest salt; +// try { +// salt = MessageDigest.getInstance("SHA-256"); +// } catch (NoSuchAlgorithmException ex) { +// Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex); +// throw new PersistenceException(ex.getMessage()); +// } +// try { +// salt.update(UUID.randomUUID().toString().getBytes("UTF-8")); +// } catch (UnsupportedEncodingException ex) { +// Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex); +// throw new PersistenceException(ex.getMessage()); +// } +// String digest = hexEncode(salt.digest()); +// return digest; + return UUID.randomUUID().toString(); + } + + /** + * The byte[] returned by MessageDigest does not have a nice + * textual representation, so some form of encoding is usually performed. + * + * This implementation follows the example of David Flanagan's book + * "Java In A Nutshell", and converts a byte array into a String + * of hex characters. + * + * Another popular alternative is to use a "Base64" encoding. + */ + private static String hexEncode(byte[] aInput) { + StringBuilder result = new StringBuilder(); + char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; + for (int idx = 0; idx < aInput.length; ++idx) { + byte b = aInput[idx]; + result.append(digits[(b & 0xf0) >> 4]); + result.append(digits[b & 0x0f]); + } + return result.toString(); + } +} diff --git a/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/Attribute.java b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/Attribute.java new file mode 100644 index 0000000..ba30851 --- /dev/null +++ b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/Attribute.java @@ -0,0 +1,37 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.persistence.annotations; + +import java.lang.annotation.*; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +@Inherited +public @interface Attribute { + +} diff --git a/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/AttributeName.java b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/AttributeName.java new file mode 100644 index 0000000..78d8eab --- /dev/null +++ b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/AttributeName.java @@ -0,0 +1,38 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.persistence.annotations; + +import java.lang.annotation.*; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +@Inherited +public @interface AttributeName { + + String name(); +} diff --git a/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/Entity.java b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/Entity.java new file mode 100644 index 0000000..6724fa4 --- /dev/null +++ b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/Entity.java @@ -0,0 +1,38 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.persistence.annotations; + +import java.lang.annotation.*; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@Inherited +public @interface Entity { + + boolean temporary() default false; +} diff --git a/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/EntityName.java b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/EntityName.java new file mode 100644 index 0000000..b43d146 --- /dev/null +++ b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/EntityName.java @@ -0,0 +1,40 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.persistence.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface EntityName { + + String name(); +} diff --git a/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/ForeignEntity.java b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/ForeignEntity.java new file mode 100644 index 0000000..ea1b22a --- /dev/null +++ b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/ForeignEntity.java @@ -0,0 +1,40 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.persistence.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface ForeignEntity { + + Class clazz(); +} diff --git a/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/NotNull.java b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/NotNull.java new file mode 100644 index 0000000..85103d0 --- /dev/null +++ b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/NotNull.java @@ -0,0 +1,40 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.persistence.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface NotNull { + +} diff --git a/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/UUID.java b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/UUID.java new file mode 100644 index 0000000..984477e --- /dev/null +++ b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/UUID.java @@ -0,0 +1,36 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.persistence.annotations; + +import java.lang.annotation.*; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +@Inherited +public @interface UUID { + +} diff --git a/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/Unmodifiable.java b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/Unmodifiable.java new file mode 100644 index 0000000..790079c --- /dev/null +++ b/power-persistence/src/main/java/org/nanoboot/powerframework/persistence/annotations/Unmodifiable.java @@ -0,0 +1,38 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.persistence.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface Unmodifiable { + +} diff --git a/power-persistence/src/main/resources/.gitkeep b/power-persistence/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-persistence/src/test/java/org/nanoboot/powerframework/persistence/.gitkeep b/power-persistence/src/test/java/org/nanoboot/powerframework/persistence/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-random/pom.xml b/power-random/pom.xml new file mode 100644 index 0000000..2da7d87 --- /dev/null +++ b/power-random/pom.xml @@ -0,0 +1,59 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-random + jar + + Power Random + Random functionality for the Power library + + + true + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + org.projectlombok + lombok + + + org.nanoboot.powerframework + power-text + ${power.version} + compile + + + + diff --git a/power-random/src/main/java/module-info.java b/power-random/src/main/java/module-info.java new file mode 100644 index 0000000..7784023 --- /dev/null +++ b/power-random/src/main/java/module-info.java @@ -0,0 +1,37 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +module powerframework.random { + exports org.nanoboot.powerframework.random; + exports org.nanoboot.powerframework.random.generators; + exports org.nanoboot.powerframework.random.generators.linearcongruent; + exports org.nanoboot.powerframework.random.generators.linearcongruent.combined.w5; + exports org.nanoboot.powerframework.random.choicegenerators; + requires powerframework.core; + requires lombok; + requires powerframework.text; +} diff --git a/power-random/src/main/java/org/nanoboot/powerframework/random/RandomException.java b/power-random/src/main/java/org/nanoboot/powerframework/random/RandomException.java new file mode 100644 index 0000000..5b1113d --- /dev/null +++ b/power-random/src/main/java/org/nanoboot/powerframework/random/RandomException.java @@ -0,0 +1,43 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random; + +import org.nanoboot.powerframework.core.PowerException; + +/** + * Exception happening in case, something in random packages failed. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class RandomException extends PowerException { + + /** + * Constructor with message. + * + * @param message message describing the reason, + * why this exception was thrown. + */ + public RandomException(final String message) { + super(message); + } + +} diff --git a/power-random/src/main/java/org/nanoboot/powerframework/random/choicegenerators/ChoiceEntry.java b/power-random/src/main/java/org/nanoboot/powerframework/random/choicegenerators/ChoiceEntry.java new file mode 100644 index 0000000..ca9fb0a --- /dev/null +++ b/power-random/src/main/java/org/nanoboot/powerframework/random/choicegenerators/ChoiceEntry.java @@ -0,0 +1,43 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.choicegenerators; + +import lombok.AllArgsConstructor; +import lombok.Data; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@Data +@AllArgsConstructor +public class ChoiceEntry { + /** + * Choice entry value - an object. + */ + private final T object; + /** + * Frequency for the object from 0 to 100. + */ + private final int frequency; +} diff --git a/power-random/src/main/java/org/nanoboot/powerframework/random/choicegenerators/ChoiceGenerator.java b/power-random/src/main/java/org/nanoboot/powerframework/random/choicegenerators/ChoiceGenerator.java new file mode 100644 index 0000000..4f59bdb --- /dev/null +++ b/power-random/src/main/java/org/nanoboot/powerframework/random/choicegenerators/ChoiceGenerator.java @@ -0,0 +1,95 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.choicegenerators; + +import org.nanoboot.powerframework.random.RandomException; +import org.nanoboot.powerframework.random.generators.RandomGenerator; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class ChoiceGenerator { + /** + * Random for this choice generator. + */ + private final RandomGenerator random; + /** + * Choice entry array, which will be used to generate next ChoiceEntry. + */ + private final ChoiceEntry[] choiceEntries; + /** + * Internal frequency sum int array: + * contains sum of frequencies from frequency of choiceEntries[0] up to the index. + */ + private final int[] frequencySum; + + /** + * Constructor. + * @param randomArg CSRandomGenerator instance for randomness for this choice generator + * @param choiceEntriesArg array of ChoiceEntry instances + */ + public ChoiceGenerator(final RandomGenerator randomArg, final ChoiceEntry... choiceEntriesArg) { + if (choiceEntriesArg.length == 0) { + throw new RandomException("choiceEntries.length == 0"); + } + this.random = randomArg; + this.choiceEntries = choiceEntriesArg; + frequencySum = new int[choiceEntriesArg.length]; + for (int i = 0; i < choiceEntriesArg.length; i++) { + int previousFrequencySum = i == 0 ? 0 : frequencySum[i - 1]; + ChoiceEntry choiceEntry = choiceEntriesArg[i]; + frequencySum[i] = previousFrequencySum + choiceEntry.getFrequency(); + } + } + + /** + * Returns random choice entry using the frequency values of the choice entries. + * + * @return a ChoiceEntry instance- one of the instances in the array passed to the constructor. + * Which instance of ChoiceEntry will be selected depends on the random selected number and + * the frequency values in the ChoiceEntry array. + */ + public ChoiceEntry generate() { + if (this.choiceEntries.length == 1) { + return choiceEntries[0]; + } + int min = 0; + int frequencySumLastIndex = frequencySum.length - 1; + int max = frequencySum[frequencySumLastIndex]; + int randomNumber = random.nextInt(min, max); + ChoiceEntry result = null; + for (int i = 0; i < frequencySum.length; i++) { + int frequencySumItem = frequencySum[i]; + if (randomNumber <= frequencySumItem) { + result = choiceEntries[i]; + break; + } + } + if (result == null) { + throw new RandomException("ChoiceEntry not found."); + } + return result; + + } +} diff --git a/power-random/src/main/java/org/nanoboot/powerframework/random/choicegenerators/ProbabilityGenerator.java b/power-random/src/main/java/org/nanoboot/powerframework/random/choicegenerators/ProbabilityGenerator.java new file mode 100644 index 0000000..e69de77 --- /dev/null +++ b/power-random/src/main/java/org/nanoboot/powerframework/random/choicegenerators/ProbabilityGenerator.java @@ -0,0 +1,80 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.choicegenerators; + +import org.nanoboot.powerframework.random.RandomException; +import org.nanoboot.powerframework.random.generators.RandomGenerator; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class ProbabilityGenerator { + /** + * Probability minimum, which is 0. + */ + public static final int PROBABILITY_MIN = 0; + /** + * Probability maximum, which is 100. + */ + public static final int PROBABILITY_MAX = 100; + /** + * + */ + private final ChoiceGenerator choiceGenerator; + /** + * Internal flag, which is true, if the probability given in the constructor is 0. + * If alwaysFalse is true, random generator won't be used and false will be always returned. + */ + private final boolean alwaysFalse; + + /** + * Constructor. + * @param random CSRandomGenerator implementation used to generate randomness for this probability generator. + * @param probability Probability- from 0 to 100. + */ + public ProbabilityGenerator(final RandomGenerator random, final int probability) { + if (probability < PROBABILITY_MIN) { + throw new RandomException("Probability is less than minimum: " + probability); + } + if (probability > PROBABILITY_MAX) { + throw new RandomException("Probability is more than maximum: " + probability); + } + alwaysFalse = probability == PROBABILITY_MIN; + ChoiceEntry yes = new ChoiceEntry<>(Boolean.TRUE, probability); + ChoiceEntry no = new ChoiceEntry<>(Boolean.FALSE, PROBABILITY_MAX - probability); + + this.choiceGenerator = new ChoiceGenerator<>(random, yes, no); + } + + /** + * Generates true or false based on the probability. + * + * @return true or false based on the given randomness generator and probability + */ + public boolean generate() { + if (alwaysFalse) { + return false; + } + return this.choiceGenerator.generate().getObject().booleanValue(); + } +} diff --git a/power-random/src/main/java/org/nanoboot/powerframework/random/choicegenerators/package-info.java b/power-random/src/main/java/org/nanoboot/powerframework/random/choicegenerators/package-info.java new file mode 100644 index 0000000..b9f7dc2 --- /dev/null +++ b/power-random/src/main/java/org/nanoboot/powerframework/random/choicegenerators/package-info.java @@ -0,0 +1,27 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * Color Shapes Engine utils like choice generator and others. + * + * @author Robert Vokac + * @since 0.0.0 + */ +package org.nanoboot.powerframework.random.choicegenerators; diff --git a/power-random/src/main/java/org/nanoboot/powerframework/random/generators/RandomGenerator.java b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/RandomGenerator.java new file mode 100644 index 0000000..df8634c --- /dev/null +++ b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/RandomGenerator.java @@ -0,0 +1,233 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.generators; + +import org.nanoboot.powerframework.core.exceptions.UnsupportedMethodException; +import org.nanoboot.powerframework.random.RandomException; +import org.nanoboot.powerframework.random.generators.linearcongruent.combined.w5.W5RandomGenerator; +import org.nanoboot.powerframework.random.internal.RandomNumberUtils; +import org.nanoboot.powerframework.random.internal.RandomTextUtils; +import org.nanoboot.powerframework.text.CharacterType; + +import java.util.ArrayList; +import java.util.List; + +/** + * Random Generator interface with some default methods. + * @author Robert Vokac + * @since 0.0.0 + */ +public interface RandomGenerator { + + /** + * Returns next number. + * + * @return next number + */ + long next(); + + /** + * Skips next number. + */ + default void skip() { + next(); + } + + /** + * Returns current number. + * + * @return current number + */ + default long current() { + String msg = "Current number cannot be returned again."; + throw new UnsupportedMethodException(msg); + } + + /** + * Returns initial number. + * + * @return initial number + */ + default long initialSeed() { + String msg = "Initial number cannot be returned."; + throw new UnsupportedMethodException(msg); + } + + /** + * Returns number of calls of the next() method. + * + * @return initial number + */ + default long numberOfNextCalls() { + String msg = "numberOfNextCalls is not supported."; + throw new UnsupportedMethodException(msg); + } + + /** + * Returns number of calls of the next() method. + * + * @return initial number + */ + default List valuesOfNextCalls() { + String msg = "valuesOfNextCalls is not supported."; + throw new UnsupportedMethodException(msg); + } + + /** + * Returns itself. + * @return itself + */ + RandomGenerator getItself(); + + /** + * Returns next number using the range. + * + * @param from start + * @param to end + * @return next number in the range + */ + default long next(final long from, final long to) { + return RandomNumberUtils.next(getItself(), from, to); + } + + /** + * Returns next number. + * + * @return next number + */ + + default int nextInt() { + return RandomNumberUtils.nextInt(getItself()); + } + + /** + * Return number in the given range. + * + * @param from starting position + * @param to ending position + * @return pseudo random int + */ + default int nextInt(final int from, final int to) { + return RandomNumberUtils.nextInt(getItself(), from, to); + } + + /** + * @return pseudo random boolean + */ + default boolean nextBoolean() { + return RandomNumberUtils.nextBoolean(getItself()); + } + /** + * Returns random character. + * + * @return random character + */ + default char nextChar() { + return RandomTextUtils.nextChar(getItself()); + } + /** + * Returns random character. + * + * @param types type of characters to be used. + * @return random character + */ + default char nextChar(final CharacterType... types) { + return RandomTextUtils.nextChar(getItself(), types); + } + /** + * Returns random text consisting of letters or numbers. + * + * @param length the size of the return String + * @return random text using the given parameters + */ + default String nextText(final int length) { + return RandomTextUtils.nextText(getItself(), length); + } + /** + * Returns random text. + * + * @param length the size of the return String + * @param types character types + * to use for the string to be returned. + * If empty or null: lower and upper + * letters and number only will be used. + * Note: CharacterType.OTHER_NOT_PRINTABLE + * is not supported. + * @return random text using the given parameters + */ + default String nextText(final int length, + final CharacterType... types) { + return RandomTextUtils.nextText(getItself(), length, types); + } + /** + * Returns random element of an array. + * @param elements generic array + * @param type of the array and type to return + * @return random element + */ + default T randomElement(T... elements) { + int to = elements.length - 1; + int randomIndex = nextInt(0, to); + return elements[randomIndex]; + } + default List getRandomItemsFromList(List list, int itemCount) { + if (itemCount > list.size()) { + throw new RandomException("itemCount > list.size()"); + } + List listCopy = new ArrayList<>(); + for (T e : list) { + listCopy.add(e); + } + List result = new ArrayList<>(); + for (int i = 0; i < itemCount; i++) { + int randomListCopyIndex = nextInt(0, listCopy.size() - 1); + T randomItem = listCopy.get(randomListCopyIndex); + listCopy.remove(randomListCopyIndex); + result.add(randomItem); + } + return result; + } + + default T getRandomItemFromList(List list) { + if (list.isEmpty()) { + throw new RandomException("list is empty"); + } + + int randomListCopyIndex = nextInt(0, list.size() - 1); + T randomItem = list.get(randomListCopyIndex); + + return randomItem; + } + /** + * Returns W5RandomGenerator instance. + * @return instance of W5RandomGenerator + */ + static RandomGenerator getDefaultImplStatic() { + return W5RandomGenerator.getStaticInstance(); + } + + /** + * Returns unique string identification of the given random generator type. + * Instances of the same implementation should return same value. + * @return name of the implementation + */ + String getName(); +} diff --git a/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/CPlusPlus11LinearCongruentGenerator.java b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/CPlusPlus11LinearCongruentGenerator.java new file mode 100644 index 0000000..8066a90 --- /dev/null +++ b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/CPlusPlus11LinearCongruentGenerator.java @@ -0,0 +1,79 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.generators.linearcongruent; + +import org.nanoboot.powerframework.core.exceptions.UnsupportedMethodException; + +/** + * Represents a seed. Uses linear congruential function. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class CPlusPlus11LinearCongruentGenerator + extends LinearCongruentGenerator { + + /** + * multiplier constant. + */ + private static final long MULTIPLIER = 16807; + + /** + * increment constant. + */ + private static final long INCREMENT = 0; + + /** + * modulus constant. + */ + private static final long MODULUS = 2147483647; + + /** + * Constructor. + * + * @param initialSeedParam the number defining the returned numbers + */ + public CPlusPlus11LinearCongruentGenerator( + final long initialSeedParam) { + super(MULTIPLIER, INCREMENT, MODULUS, initialSeedParam); + } + + /** + * Returns current number. + * + * @return current number + */ + @Override + public long current() { + throw new UnsupportedMethodException(""); + } + + /** + * Returns initial seed. + * + * @return initial seed + */ + @Override + public long initialSeed() { + throw new UnsupportedMethodException(""); + } + +} diff --git a/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/DummyGenerator.java b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/DummyGenerator.java new file mode 100644 index 0000000..0a5767e --- /dev/null +++ b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/DummyGenerator.java @@ -0,0 +1,64 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.generators.linearcongruent; + +import org.nanoboot.powerframework.random.RandomException; +import org.nanoboot.powerframework.random.generators.RandomGenerator; +import lombok.Getter; + +import java.util.ArrayList; +import java.util.List; + +/** + * Represents a seed. Uses linear congruential function. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class DummyGenerator implements RandomGenerator { + private final List nextValues; + private int nextValueIndex = 0; + private final int maxNextValueIndex; + + public DummyGenerator(List nextValues) { + this.nextValues = nextValues; + this.maxNextValueIndex = nextValues.size() - 1; + } + @Override + public long next() { + if(nextValueIndex > maxNextValueIndex) { + throw new RandomException("There is no other value available for next() call."); + } + long next = nextValues.get(nextValueIndex); + nextValueIndex++; + return next; + } + + @Override + public RandomGenerator getItself() { + return this; + } + + @Override + public String getName() { + return this.getClass().getName(); + } +} diff --git a/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/LinearCongruentGenerator.java b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/LinearCongruentGenerator.java new file mode 100644 index 0000000..98f0f77 --- /dev/null +++ b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/LinearCongruentGenerator.java @@ -0,0 +1,123 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.generators.linearcongruent; + +import lombok.Getter; +import org.nanoboot.powerframework.random.generators.RandomGenerator; + +import java.util.ArrayList; +import java.util.List; + +/** + * Represents a seed. Uses linear congruential function. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class LinearCongruentGenerator implements RandomGenerator { + /** + * number multiplying current seed. + */ + @Getter + private final long multiplier; + + /** + * Number to add to the product. + */ + @Getter + private final long increment; + + /** + * modulus used for the total of the product and increment. + */ + @Getter + private final long modulus; + + /** + * Initial seed. + */ + private final long initialSeed; + + /** + * Current number. + */ + private long current; + + @Getter + private List nextValues = new ArrayList<>(); + + /** + * Constructor. + * + * @param multiplierParam a + * @param incrementParam c + * @param modulusParam m + * @param initialSeedParam the number defining the returned numbers + */ + public LinearCongruentGenerator( + final long multiplierParam, + final long incrementParam, + final long modulusParam, + final long initialSeedParam) { + this.multiplier = multiplierParam; + this.increment = incrementParam; + this.modulus = modulusParam; + this.initialSeed = initialSeedParam; + this.current = this.initialSeed; + } + + @Override + public final long next() { + long pseudoRandomLong = ((multiplier * current) + increment) % modulus; + this.current = pseudoRandomLong; + this.nextValues.add(pseudoRandomLong); + return pseudoRandomLong; + } + + /** + * Returns current number. + * @return current number + */ + @Override + public long current() { + return current; + } + + /** + * Returns initial seed. + * @return initial seed + */ + @Override + public long initialSeed() { + return initialSeed; + } + + @Override + public final RandomGenerator getItself() { + return this; + } + + @Override + public final String getName() { + return this.getClass().getName(); + } + +} diff --git a/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5GeneratorsFactory.java b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5GeneratorsFactory.java new file mode 100644 index 0000000..0b6f340 --- /dev/null +++ b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5GeneratorsFactory.java @@ -0,0 +1,36 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.generators.linearcongruent.combined.w5; + +import org.nanoboot.powerframework.random.generators.linearcongruent.CPlusPlus11LinearCongruentGenerator; + +/** + * W5 generator factory interface. * + * @author Robert Vokac + * @since 0.0.0 + */ +public interface W5GeneratorsFactory { + /** + * Creates W5 generators. + * @return w5 generators + */ + CPlusPlus11LinearCongruentGenerator[] getSubGenerators(); +} diff --git a/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5GeneratorsFactoryImpl.java b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5GeneratorsFactoryImpl.java new file mode 100644 index 0000000..0dedfca --- /dev/null +++ b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5GeneratorsFactoryImpl.java @@ -0,0 +1,161 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.generators.linearcongruent.combined.w5; + +import lombok.Getter; +import org.nanoboot.powerframework.random.RandomException; +import org.nanoboot.powerframework.random.generators.RandomGenerator; +import org.nanoboot.powerframework.random.generators.linearcongruent.CPlusPlus11LinearCongruentGenerator; + +import java.security.SecureRandom; + +/** + * + * @author Robert Vokac + * @since 0.0.0 + */ +final class W5GeneratorsFactoryImpl implements W5GeneratorsFactory { + + /** + * Plus character. + */ + private static final char PLUS = '+'; + /** + * Asterisk character. + */ + private static final char TIMES = '*'; + /** + *0. + */ + private static final int SEED0_INDEX = 0; + /** + * 1. + */ + private static final int SEED0_START = 1; + /** + * 3. + */ + private static final int SEED0_END = 3; + /** + * 4. + */ + private static final int SEED1_INDEX = 4; + /** + * 5. + */ + private static final int SEED1_START = 5; + /** + * 7. + */ + private static final int SEED1_END = 7; + + /** + * Count of numbers. + */ + private static final int NUMBER_COUNT = 8; + + /** + * w5 generators. + */ + @Getter + private CPlusPlus11LinearCongruentGenerator[] subGenerators; + /** + * Constructor. + */ + W5GeneratorsFactoryImpl() { + SecureRandom random = new SecureRandom(); + long[] randomNumbers = new long[NUMBER_COUNT]; + for (int i = 0; i < NUMBER_COUNT; i++) { + randomNumbers[i] = random.nextLong(); + } + process(randomNumbers); + } + + /** + * Constructor. + * @param numbers input numbers + */ + W5GeneratorsFactoryImpl(final long[] numbers) { + process(numbers); + } + + /** + * Methods processing the input numbers. + * @param randomNumbers random numbers + */ + private void process(final long[] randomNumbers) { + if (randomNumbers == null || randomNumbers.length != NUMBER_COUNT) { + String msg = "Count of numbers must be " + NUMBER_COUNT + "."; + throw new RandomException(msg); + } + long magicNumber = randomNumbers[0]; + CPlusPlus11LinearCongruentGenerator magicGenerator = + new CPlusPlus11LinearCongruentGenerator(magicNumber); + long seed0; + long seed1; + + long number1; + long number2; + long number3; + long number4; + + seed0 = randomNumbers[SEED0_INDEX]; + for (int i = SEED0_START; i <= SEED0_END; i++) { + number1 = seed0; + number2 = randomNumbers[i]; + seed0 = executeRandomPlusOrMultiply( + magicGenerator, number1, number2); + } + + CPlusPlus11LinearCongruentGenerator generator0 = + new CPlusPlus11LinearCongruentGenerator(seed0); + + seed1 = randomNumbers[SEED1_INDEX]; + for (int i = SEED1_START; i <= SEED1_END; i++) { + number3 = seed1; + number4 = randomNumbers[i]; + seed1 = executeRandomPlusOrMultiply( + magicGenerator, number3, number4); + } + CPlusPlus11LinearCongruentGenerator generator1 = + new CPlusPlus11LinearCongruentGenerator(seed1); + this.subGenerators = new CPlusPlus11LinearCongruentGenerator[]{ + magicGenerator, generator0, generator1}; + } + + /** + * Uses total or product of the two given numbers. + * @param rg random number generator + * @param number1 number 1 + * @param number2 number 2 + * @return processes the numbers using the random number generator + */ + private static long executeRandomPlusOrMultiply(final RandomGenerator rg, + final long number1, + final long number2) { + char operation = rg.nextBoolean() ? PLUS : TIMES; + if (operation == PLUS) { + return number1 + number2; + } else { + return number1 * number2; + } + } +} diff --git a/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5GeneratorsProcessor.java b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5GeneratorsProcessor.java new file mode 100644 index 0000000..c57d0a6 --- /dev/null +++ b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5GeneratorsProcessor.java @@ -0,0 +1,37 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.generators.linearcongruent.combined.w5; + +import org.nanoboot.powerframework.random.generators.linearcongruent.CPlusPlus11LinearCongruentGenerator; +/** + * W5 generator processor interface. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public interface W5GeneratorsProcessor { + /** + * Computes next long using the generators. + * @param generators generators. + * @return next long using the generators + */ + long next(CPlusPlus11LinearCongruentGenerator... generators); +} diff --git a/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5GeneratorsProcessorImpl.java b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5GeneratorsProcessorImpl.java new file mode 100644 index 0000000..920d5d0 --- /dev/null +++ b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5GeneratorsProcessorImpl.java @@ -0,0 +1,76 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.generators.linearcongruent.combined.w5; + +import org.nanoboot.powerframework.random.RandomException; +import org.nanoboot.powerframework.random.generators.linearcongruent.CPlusPlus11LinearCongruentGenerator; +/** + * W5 generator processor implementation. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class W5GeneratorsProcessorImpl implements W5GeneratorsProcessor { + + /** + * One million. + */ + private static final int MILLION = 1_000_000_000; + /** + * Expected count of generators. + */ + private static final int EXPECTED_COUNT_OF_GENERATORS = 3; + + @Override + public final long next( + final CPlusPlus11LinearCongruentGenerator... generators) { + if (generators == null) { + throw new RandomException("Generators must not be null."); + } + if (generators.length != EXPECTED_COUNT_OF_GENERATORS) { + String msg = + "Param generators is an array, which has invalid count: " + + generators.length; + throw new RandomException(msg); + } + + long[] numberFractions = new long[2]; + + CPlusPlus11LinearCongruentGenerator g0 = generators[0]; + CPlusPlus11LinearCongruentGenerator g1 = generators[1]; + CPlusPlus11LinearCongruentGenerator g2 = generators[2]; + for (int i = 0; i <= 1; i++) { + if (g0.nextBoolean()) { + g1.skip(); + } else { + g2.skip(); + } + int number1 = g2.nextInt(); + int number2 = g1.nextInt(); + if (g0.nextBoolean()) { + number2 *= (-1); + } + numberFractions[i] = (Math.abs(number1 + number2)) % MILLION; + } + + return (numberFractions[0] * MILLION) + numberFractions[1]; + } +} diff --git a/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5RandomGenerator.java b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5RandomGenerator.java new file mode 100644 index 0000000..ce87557 --- /dev/null +++ b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5RandomGenerator.java @@ -0,0 +1,112 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.generators.linearcongruent.combined.w5; + +import org.nanoboot.powerframework.random.generators.RandomGenerator; +import org.nanoboot.powerframework.random.generators.linearcongruent.CPlusPlus11LinearCongruentGenerator; + +/** + * Used to generate pseudo random values. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class W5RandomGenerator implements RandomGenerator { + + /** + * Static instance of the generator. + */ + private static final W5RandomGenerator INSTANCE; + /** + *generators. + */ + private final CPlusPlus11LinearCongruentGenerator[] generators; + + /** + * next() processor. + */ + private final W5GeneratorsProcessor processor; + + /** + * Constructor using random input parameters. + * + */ + public W5RandomGenerator() { + W5GeneratorsFactoryImpl gc = new W5GeneratorsFactoryImpl(); + this.generators = gc.getSubGenerators(); + this.processor = new W5GeneratorsProcessorImpl(); + } + + /** + * Constructor. + * + * @param numbers numbers + */ + @SuppressWarnings("checkstyle:ParameterNumber") + public W5RandomGenerator( + final long... numbers) { + this(new W5GeneratorsFactoryImpl(numbers), + new W5GeneratorsProcessorImpl() + ); + } + + /** + * Constructor. + * + * @param factory a factory + * @param processorIn a processor + */ + @SuppressWarnings("checkstyle:ParameterNumber") + public W5RandomGenerator(final W5GeneratorsFactory factory, + final W5GeneratorsProcessor processorIn) { + this.generators = factory.getSubGenerators(); + this.processor = processorIn; + } + + static { + INSTANCE = new W5RandomGenerator(); + } + + /** + * @return static instance + */ + public static W5RandomGenerator getStaticInstance() { + return INSTANCE; + } + + @Override + public final RandomGenerator getItself() { + return this; + } + + @Override + public final String getName() { + return this.getClass().getName(); + } + + /** + * @return pseudo random long + */ + public long next() { + return processor.next(generators); + } + +} diff --git a/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/package-info.java b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/package-info.java new file mode 100644 index 0000000..aa4997b --- /dev/null +++ b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/package-info.java @@ -0,0 +1,26 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * w5 random generator. + * @author Robert Vokac + * @since 0.0.0 + */ +package org.nanoboot.powerframework.random.generators.linearcongruent.combined.w5; diff --git a/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/package-info.java b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/package-info.java new file mode 100644 index 0000000..d4253e2 --- /dev/null +++ b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/linearcongruent/package-info.java @@ -0,0 +1,27 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * Classes for linear congruent generators. + * + * @author Robert Vokac + * @since 0.0.0 + */ +package org.nanoboot.powerframework.random.generators.linearcongruent; diff --git a/power-random/src/main/java/org/nanoboot/powerframework/random/generators/package-info.java b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/package-info.java new file mode 100644 index 0000000..01ab557 --- /dev/null +++ b/power-random/src/main/java/org/nanoboot/powerframework/random/generators/package-info.java @@ -0,0 +1,27 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * Generators. + * + * @author Robert Vokac + * @since 0.0.0 + */ +package org.nanoboot.powerframework.random.generators; diff --git a/power-random/src/main/java/org/nanoboot/powerframework/random/internal/RandomNumberUtils.java b/power-random/src/main/java/org/nanoboot/powerframework/random/internal/RandomNumberUtils.java new file mode 100644 index 0000000..6f560ed --- /dev/null +++ b/power-random/src/main/java/org/nanoboot/powerframework/random/internal/RandomNumberUtils.java @@ -0,0 +1,97 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.internal; + +import org.nanoboot.powerframework.random.RandomException; +import org.nanoboot.powerframework.random.generators.RandomGenerator; + +/** + * Utility for number randomness. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public final class RandomNumberUtils { + + /** + * Private constructor. + */ + private RandomNumberUtils() { + //Instantiation not needed + } + + /** + * Returns next number using the range. + * @param rg random generator + * @param from start + * @param to end + * @return random number in the range + */ + public static long next( + final RandomGenerator rg, + final long from, + final long to) { + if (from > to) { + throw new RandomException("from is greater than to."); + } + long range = to - from; + long randomLong = rg.next(); + long randomRange = randomLong % (range + 1); + long randomLongInRange; + randomLongInRange = from + randomRange; + + return randomLongInRange; + } + + /** + * Returns next number. + * + * @param rg random generator + * @return next number + */ + public static int nextInt(final RandomGenerator rg) { + return (int) (rg.next() % Integer.MAX_VALUE); + } + + /** + * Return number in the given range. + * + * @param rg random generator + * @param from start position + * @param to end position + * @return pseudo random int + */ + public static int nextInt(final RandomGenerator rg, + final int from, final int to) { + return (int) rg.next(from, to); + } + + /** + * Returns random boolean. + * + * @param rg random generator + * @return pseudo random boolean + */ + public static boolean nextBoolean(final RandomGenerator rg) { + long randomLong = rg.next(0, 1); + return randomLong == 1; + } +} diff --git a/power-random/src/main/java/org/nanoboot/powerframework/random/internal/RandomTextUtils.java b/power-random/src/main/java/org/nanoboot/powerframework/random/internal/RandomTextUtils.java new file mode 100644 index 0000000..97a2f3f --- /dev/null +++ b/power-random/src/main/java/org/nanoboot/powerframework/random/internal/RandomTextUtils.java @@ -0,0 +1,130 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.internal; + +import org.nanoboot.powerframework.random.RandomException; +import org.nanoboot.powerframework.random.generators.RandomGenerator; +import org.nanoboot.powerframework.text.CharacterRange; +import org.nanoboot.powerframework.text.CharacterType; +/** + * Utility for text randomness. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public final class RandomTextUtils { + /** + * Private constructor. + */ + private RandomTextUtils() { + //Instantiation not needed + } + /** + * Returns random character. + * + * @param rg random generator to be used + * @return random character + */ + public static char nextChar( + final RandomGenerator rg) { + return nextChar(rg, null); + } + /** + * Returns random character. + * + * @param rg random generator to be used + * @param types type of characters to be used. + * @return random character + */ + public static char nextChar( + final RandomGenerator rg, final CharacterType... types) { + CharacterType[] characterTypes; + if (types == null || types.length == 0) { + characterTypes = new CharacterType[]{ + CharacterType.NUMBER, CharacterType.LOWER_LETTER, + CharacterType.UPPER_LETTER}; + } else { + characterTypes = types; + } + + int charCount = 0; + for (CharacterType type : characterTypes) { + if (type == CharacterType.OTHER_NOT_PRINTABLE) { + String msg = + "CharacterType.OTHER_NOT_PRINTABLE is not supported"; + throw new UnsupportedOperationException(msg); + } + charCount = charCount + CharacterRange.getInstance(type).size(); + } + + int randomPosition = rg.nextInt(1, charCount); + int currentPosition = 0; + + for (CharacterType type : characterTypes) { + char[] array = CharacterRange.getInstance(type).getArray(); + for (char ch : array) { + currentPosition++; + if (currentPosition == randomPosition) { + return ch; + } + } + } + + throw new RandomException("nextChar method failed."); //NOSONAR + } + /** + * Returns random text consisting of letters or numbers. + * + * @param rg random generator to be used + * @param length the size of the return String + * @return random text using the given parameters + */ + public static String nextText( + final RandomGenerator rg, final int length) { + return nextText(rg, length, null); + } + + /** + * Returns random text. + * + * @param rg random generator to be used + * @param length the size of the return String + * @param types character types + * to use for the string to be returned. + * If empty or null: lower and upper + * letters and number only will be used. + * Note: CharacterType.OTHER_NOT_PRINTABLE + * is not supported. + * @return random text using the given parameters + */ + public static String nextText( + final RandomGenerator rg, final int length, + final CharacterType... types) { + + StringBuilder stringBuilder = new StringBuilder(); + for (int i = 0; i < length; i++) { + char ch = nextChar(rg, types); + stringBuilder.append(ch); + } + return stringBuilder.toString(); + } +} + diff --git a/power-random/src/main/java/org/nanoboot/powerframework/random/internal/package-info.java b/power-random/src/main/java/org/nanoboot/powerframework/random/internal/package-info.java new file mode 100644 index 0000000..3e9bc70 --- /dev/null +++ b/power-random/src/main/java/org/nanoboot/powerframework/random/internal/package-info.java @@ -0,0 +1,26 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * Internal classes. + * @author Robert Vokac + * @since 0.0.0 + */ +package org.nanoboot.powerframework.random.internal; diff --git a/power-random/src/main/java/org/nanoboot/powerframework/random/package-info.java b/power-random/src/main/java/org/nanoboot/powerframework/random/package-info.java new file mode 100644 index 0000000..b29fd05 --- /dev/null +++ b/power-random/src/main/java/org/nanoboot/powerframework/random/package-info.java @@ -0,0 +1,27 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * Classes used to generated some randomness. + * + * @author Robert Vokac + * @since 0.0.0 + */ +package org.nanoboot.powerframework.random; diff --git a/power-random/src/main/resources/.gitkeep b/power-random/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-random/src/test/java/org/nanoboot/powerframework/random/RandomExceptionTest.java b/power-random/src/test/java/org/nanoboot/powerframework/random/RandomExceptionTest.java new file mode 100644 index 0000000..9ff3fef --- /dev/null +++ b/power-random/src/test/java/org/nanoboot/powerframework/random/RandomExceptionTest.java @@ -0,0 +1,38 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random; + +import org.junit.Test; + +import static org.junit.Assert.*; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class RandomExceptionTest { + @Test + public void constructor_String() { + assertEquals("An error", new RandomException("An error").getMessage()); + } + +} diff --git a/power-random/src/test/java/org/nanoboot/powerframework/random/choicegenerators/ChoiceGeneratorTest.java b/power-random/src/test/java/org/nanoboot/powerframework/random/choicegenerators/ChoiceGeneratorTest.java new file mode 100644 index 0000000..7e680fa --- /dev/null +++ b/power-random/src/test/java/org/nanoboot/powerframework/random/choicegenerators/ChoiceGeneratorTest.java @@ -0,0 +1,222 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.choicegenerators; + +import org.nanoboot.powerframework.random.RandomException; +import org.nanoboot.powerframework.random.generators.RandomGenerator; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class ChoiceGeneratorTest { + private RandomGenerator random; + + @Before + public void setup() { + random = RandomGenerator.getDefaultImplStatic(); + } + + @Test(expected = RandomException.class) + public void constructor_generator_choiceEntries_choiceEntriesMustNotBeEmptyAndIsEmpty() { + //prepare + assertNotNull(new ChoiceGenerator(random)); + //execute + //assert + } + + @Test() + public void constructor_generator_choiceEntries_choiceEntriesMustNotBeEmptyAndIsNotEmpty() { + //prepare + + assertNotNull(new ChoiceGenerator(random, new ChoiceEntry<>("a", 50))); + //execute + //assert + } + + @Test() + public void constructor_generator_choiceEntries_choiceEntriesMustNotBeEmptyAndIsNotEmpty2() { + //prepare + + assertNotNull(new ChoiceGenerator(random, new ChoiceEntry<>("a", 50), new ChoiceEntry<>("b", 75))); + //execute + //assert + } + + @Test + public void generate_hasOnlyOneEntry() { + //prepare + + ChoiceGenerator choiceGenerator = new ChoiceGenerator(random, new ChoiceEntry<>("a", 50)); + //execute + + //assert + assertEquals("a", choiceGenerator.generate().getObject()); + } + + @Test + public void generate_hasTwoEntries() { + //prepare + + ChoiceGenerator choiceGenerator = new ChoiceGenerator(random, new ChoiceEntry<>("a", 50), new ChoiceEntry<>("b", 75)); + //execute + Object generatedString = choiceGenerator.generate().getObject(); + assertTrue("a".equals(generatedString) || "b".equals(generatedString)); + //assert + } + + @Test + public void generate_mockedCheck() { +// //prepare + class ARandomGeneratorImpl implements RandomGenerator { + private int[] intArray = new int[]{0, 24, 25, 26, 60, 74, 75, 76, 149, 150}; + private int nextIndex = 0; + private boolean fromToChecked = false; + + @Override + public long next() { + return 0; + } + + public int nextInt(int from, int to) { + if (!fromToChecked) { + assertEquals(0, from); + assertEquals(150, to); + fromToChecked = true; + } + if (nextIndex >= intArray.length) { + fail("next index is " + nextIndex + ", but the intArray has length " + intArray.length); + } + int result = intArray[nextIndex]; + ++nextIndex; + return result; + } + + @Override + public RandomGenerator getItself() { + return this; + } + + @Override + public String getName() { + return "choiceRandomGenerator"; + } + } + RandomGenerator randomArg = new ARandomGeneratorImpl(); + ChoiceEntry green = new ChoiceEntry<>("green", 25);//0-25 + ChoiceEntry orange = new ChoiceEntry<>("orange", 50);//26-75 + ChoiceEntry red = new ChoiceEntry<>("red", 75);//76/150 + + ChoiceGenerator choiceGenerator = new ChoiceGenerator(randomArg, green, orange, red); +// //execute +// //assert + assertTrue("green".equals(choiceGenerator.generate().getObject())); + assertTrue("green".equals(choiceGenerator.generate().getObject())); + assertTrue("green".equals(choiceGenerator.generate().getObject())); + assertTrue("orange".equals(choiceGenerator.generate().getObject())); + assertTrue("orange".equals(choiceGenerator.generate().getObject())); + assertTrue("orange".equals(choiceGenerator.generate().getObject())); + assertTrue("orange".equals(choiceGenerator.generate().getObject())); + assertTrue("red".equals(choiceGenerator.generate().getObject())); + assertTrue("red".equals(choiceGenerator.generate().getObject())); + assertTrue("red".equals(choiceGenerator.generate().getObject())); + } + @Test(expected = RandomException.class) + public void generate_entryNotFound() { +// //prepare + class ARandomGeneratorImpl implements RandomGenerator { + @Override + public long next() { + return 0; + } + + public int nextInt(int from, int to) { + return to + 1; + } + + @Override + public RandomGenerator getItself() { + return this; + } + + @Override + public String getName() { + return "choiceRandomGenerator"; + } + } + RandomGenerator randomArg = new ARandomGeneratorImpl(); + ChoiceEntry green = new ChoiceEntry<>("green", 25);//0-25 + ChoiceEntry orange = new ChoiceEntry<>("orange", 50);//26-75 + ChoiceEntry red = new ChoiceEntry<>("red", 75);//76/150 + + ChoiceGenerator choiceGenerator = new ChoiceGenerator(randomArg, green, orange, red); +// //execute + choiceGenerator.generate().getObject(); +// //assert + } +// @Test +// public void generate() { +// //todo +// +// //prepare +// ChoiceEntry colored = new ChoiceEntry<>("colored", 80); +// ChoiceEntry joker = new ChoiceEntry<>("joker", 10); +// ChoiceEntry automaticBomb = new ChoiceEntry<>("automaticBomb", 15); +// ChoiceEntry manualBomb = new ChoiceEntry<>("manualBomb", 40); +// +// //execute +// +// int coloredCount = 0; +// int jokerCount = 0; +// int automaticBombCount = 0; +// int manualBombCount = 0; +// ChoiceGenerator choiceGenerator = new ChoiceGenerator<>(random, colored, joker, automaticBomb, manualBomb); +// +// int multi = 10000; +// for (int i = 0; i < 145 * multi; i++) { +// //System.out.println(choiceGenerator.generate().getName()); +// switch (choiceGenerator.generate().getObject()) { +// case "colored": +// coloredCount++; +// break; +// case "joker": +// jokerCount++; +// break; +// case "automaticBomb": +// automaticBombCount++; +// break; +// case "manualBomb": +// manualBombCount++; +// break; +// } +// } +// System.out.println("colored=80 joker=10 automaticBomb=15 manualBomb=40"); +// System.out.println(coloredCount / multi + " " + jokerCount / multi + " " + automaticBombCount / multi + " " + manualBombCount / multi); +// //assert +// assertTrue(true); +// } +} diff --git a/power-random/src/test/java/org/nanoboot/powerframework/random/choicegenerators/ProbabilityGeneratorTest.java b/power-random/src/test/java/org/nanoboot/powerframework/random/choicegenerators/ProbabilityGeneratorTest.java new file mode 100644 index 0000000..883480b --- /dev/null +++ b/power-random/src/test/java/org/nanoboot/powerframework/random/choicegenerators/ProbabilityGeneratorTest.java @@ -0,0 +1,153 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.choicegenerators; + +import org.nanoboot.powerframework.random.RandomException; +import org.nanoboot.powerframework.random.generators.RandomGenerator; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class ProbabilityGeneratorTest { + private RandomGenerator randomGenerator; + + @Before + public void setup() { + randomGenerator = RandomGenerator.getDefaultImplStatic(); + } + + @Test(expected = RandomException.class) + public void constructor_probabilityIsLessThanMinimum() { + new ProbabilityGenerator(randomGenerator, -1); + } + @Test(expected = RandomException.class) + public void constructor_probabilityIsMoreThanMinimum() { + new ProbabilityGenerator(randomGenerator, 101); + } + @Test(expected = Test.None.class) + public void constructor_probabilityIsOK0() { + new ProbabilityGenerator(randomGenerator, 0); + } + @Test(expected = Test.None.class) + public void constructor_probabilityIsOK1() { + new ProbabilityGenerator(randomGenerator, 1); + } + @Test(expected = Test.None.class) + public void constructor_probabilityIsOK99() { + new ProbabilityGenerator(randomGenerator, 99); + } + @Test(expected = Test.None.class) + public void constructor_probabilityIsOK60() { + new ProbabilityGenerator(randomGenerator, 60); + } + @Test(expected = Test.None.class) + public void constructor_probabilityIsOK100() { + new ProbabilityGenerator(randomGenerator, 100); + } + + @Test + public void generate_alwaysFalse() { + assertEquals(false, new ProbabilityGenerator(randomGenerator, 0).generate()); + } @Test + public void generate_alwaysTrue() { + assertEquals(true, new ProbabilityGenerator(randomGenerator, 100).generate()); + } + @Test + public void generate_NotAlwaysFalse() { + boolean trueGenerated = false; + boolean falseGenerated = false; + for(int i = 0; i<100; i++) { + boolean result = new ProbabilityGenerator(randomGenerator, 40).generate(); + if(result) { + trueGenerated = true; + } else { + falseGenerated = true; + } + if(trueGenerated && falseGenerated) { + //no need for next loop + break; + } + } + assertTrue(trueGenerated && falseGenerated); + } + + + @Test + public void generate_mockedCheck() { +// //prepare + class ARandomGeneratorImpl implements RandomGenerator { + private int[] intArray = new int[]{0, 24, 25, 26, 60, 74, 75, 76, 99, 100}; + private int nextIndex = 0; + private boolean fromToChecked = false; + + @Override + public long next() { + return 0; + } + + public int nextInt(int from, int to) { + if (!fromToChecked) { + assertEquals(0, from); + assertEquals(100, to); + fromToChecked = true; + } + if (nextIndex >= intArray.length) { + fail("next index is " + nextIndex + ", but the intArray has length " + intArray.length); + } + int result = intArray[nextIndex]; + ++nextIndex; + return result; + } + + @Override + public RandomGenerator getItself() { + return this; + } + + @Override + public String getName() { + return "choiceRandomGenerator"; + } + } + RandomGenerator randomArg = new ARandomGeneratorImpl(); + + ProbabilityGenerator choiceGenerator = new ProbabilityGenerator(randomArg, 40); +// //execute +// //assert + + assertTrue(choiceGenerator.generate()); + assertTrue(choiceGenerator.generate()); + assertTrue(choiceGenerator.generate()); + assertTrue(choiceGenerator.generate()); + assertFalse(choiceGenerator.generate()); + assertFalse(choiceGenerator.generate()); + assertFalse(choiceGenerator.generate()); + assertFalse(choiceGenerator.generate()); + assertFalse(choiceGenerator.generate()); + assertFalse(choiceGenerator.generate()); + } +} diff --git a/power-random/src/test/java/org/nanoboot/powerframework/random/generators/RandomGeneratorTest.java b/power-random/src/test/java/org/nanoboot/powerframework/random/generators/RandomGeneratorTest.java new file mode 100644 index 0000000..a10bd2c --- /dev/null +++ b/power-random/src/test/java/org/nanoboot/powerframework/random/generators/RandomGeneratorTest.java @@ -0,0 +1,1379 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.generators; + +import org.nanoboot.powerframework.core.exceptions.UnsupportedMethodException; +import org.nanoboot.powerframework.random.RandomException; +import org.nanoboot.powerframework.random.generators.linearcongruent.combined.w5.W5RandomGenerator; +import org.nanoboot.powerframework.text.CharacterType; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class RandomGeneratorTest { + + private RandomGenerator randomGenerator; + + @Before + public void setUp() { + this.randomGenerator = new RandomGenerator() { + private int currentIndex = 0; + @Override + public long next() { + long toReturn = randomNumbers[currentIndex]; + currentIndex++; + if(currentIndex > (randomNumbers.length - 1)) { + currentIndex = 0; + for(int i = 0; i < randomNumbers.length; i++) { + randomNumbers[i] = RandomGenerator.getDefaultImplStatic().next(); + } + } + return toReturn; + } + + @Override + public RandomGenerator getItself() { + return this; + } + + @Override + public String getName() { + return "testGenerator"; + } + }; + } + + @Test + public void next() { + //setup + //execute + //assert + for (int i = 0; i < 10; i++) { + long randomLong = randomGenerator.next(); + assertEquals(randomNumbers[i], randomLong); + } + } + + @Test + public void skip() { + randomGenerator.skip(); + randomGenerator.skip(); + randomGenerator.skip(); + assertEquals(630129986537696031l, randomGenerator.next()); + } + + @Test(expected = UnsupportedMethodException.class) + public void current() { + randomGenerator.current(); + } + + @Test(expected = UnsupportedMethodException.class) + public void initialSeed() { + randomGenerator.initialSeed(); + } + @Test(expected = UnsupportedMethodException.class) + public void numberOfNextCalls() { + randomGenerator.numberOfNextCalls(); + } + @Test + public void getItself() { + assertEquals(this.randomGenerator.hashCode(), randomGenerator.getItself().hashCode()); + } + + @Test + public void getNext_interval() { + long min = Integer.MAX_VALUE; + long max = Integer.MIN_VALUE; + long from = 36; + long to = 418; + for(int i = 0; i < 9999; i++) { + long randomLong = randomGenerator.next(from, to); + if(randomLong < from) { + String msg = "Random number is " + randomLong +", but it should be at least " + from; + throw new AssertionError(msg); + } + if(randomLong > to) { + String msg = "Random number is " + randomLong +", but it should be at most " + to; + throw new AssertionError(msg); + } + if(randomLong < min) { + min = randomLong; + } + if(randomLong > max) { + max = randomLong; + } + } + + assertEquals(from, min); + assertEquals(to, max); + + } + + @Test(expected = RandomException.class) + public void getNext_interval_exception() { + randomGenerator.next(10, 5); + } + + @Test + public void nextInt() { + assertEquals(randomNumbers[0] % Integer.MAX_VALUE, randomGenerator.nextInt()); + } + @Test + public void nextInt_interval() { + int from = 31; + int to = 43; + assertEquals(from + (randomNumbers[0] % (to - from + 1)), randomGenerator.nextInt(from, to)); + } + @Test + public void nextBoolean() { + int from = 0; + int to = 1; + boolean expected = from + (randomNumbers[0] % (to - from + 1)) == 1; + boolean returned = randomGenerator.nextInt(from, to) == 1; + assertEquals(expected, returned); + } + @Test + public void nextChar_types_numbers() { + for(int i = 0; i < 10000; i++) { + char ch = randomGenerator.nextChar(CharacterType.NUMBER); + assertTrue(Character.isDigit(ch)); + } + } + @Test + public void nextChar_types_lower() { + for(int i = 0; i < 1000; i++) { + char ch = randomGenerator.nextChar(CharacterType.LOWER_LETTER); + assertTrue(Character.isLowerCase(ch)); + } + } + @Test + public void nextChar_types_upper() { + for(int i = 0; i < 1000; i++) { + char ch = randomGenerator.nextChar(CharacterType.UPPER_LETTER); + assertTrue(Character.isUpperCase((ch))); + } + } + @Test + public void nextChar_types_otherPrintable() { + for(int i = 0; i < 1000; i++) { + char ch = randomGenerator.nextChar(CharacterType.OTHER_PRINTABLE); + assertFalse(Character.isWhitespace(ch)); + } + } + + @Test(expected = UnsupportedOperationException.class) + public void nextChar_types_notPrintable() { + randomGenerator.nextChar(CharacterType.OTHER_NOT_PRINTABLE); + } + + @Test + public void nextChar_types_null() { + for(int i = 0; i < 1000; i++) { + char ch = randomGenerator.nextChar(null); + boolean digit = Character.isDigit((ch)); + boolean upper = Character.isLowerCase((ch)); + boolean lower = Character.isUpperCase((ch)); + assertTrue(digit || upper || lower); + } + } + @Test + public void nextChar() { + for(int i = 0; i < 1000; i++) { + char ch = randomGenerator.nextChar(); + boolean digit = Character.isDigit((ch)); + boolean upper = Character.isLowerCase((ch)); + boolean lower = Character.isUpperCase((ch)); + assertTrue(digit || upper || lower); + } + } + @Test + public void nextText() { + String returned = randomGenerator.nextText(100); + assertEquals(100, returned.length()); + + for(char ch : returned.toCharArray()) { + boolean digit = Character.isDigit((ch)); + boolean upper = Character.isLowerCase((ch)); + boolean lower = Character.isUpperCase((ch)); + assertTrue(digit || upper || lower); + } + } + @Test + public void nextText_types_numbers() { + String returned = randomGenerator.nextText(100, CharacterType.NUMBER); + assertEquals(100, returned.length()); + for(char ch : returned.toCharArray()) { + assertTrue(Character.isDigit(ch)); + } + } + @Test + public void nextText_types_lower() { + String returned = randomGenerator.nextText(100, CharacterType.LOWER_LETTER); + for(char ch : returned.toCharArray()) { + assertTrue(Character.isLowerCase(ch)); + } + } + @Test + public void nextText_types_upper() { + String returned = randomGenerator.nextText(100, CharacterType.UPPER_LETTER); + for(char ch : returned.toCharArray()) { + assertTrue(Character.isUpperCase((ch))); + } + } + @Test + public void nextText_types_otherPrintable() { + String returned = randomGenerator.nextText(100, CharacterType.OTHER_PRINTABLE); + for(char ch : returned.toCharArray()) { + assertFalse(Character.isWhitespace(ch)); + } + } + @Test + public void randomElement() { + int[] array = new int[] {5, 4, 9, 6, 7, 2, 5, 4, 3, 4}; + + int from = 0; + int to = array.length - 1; + + int expectedIndex = (int) (from + (randomNumbers[0] % (to - from + 1))); + + int expected = array[expectedIndex]; + int returned = randomGenerator.randomElement(5, 4, 9, 6, 7, 2, 5, 4, 3, 4); + assertEquals(expected, returned); + } + @Test + public void getDefaultImplStatic() { + assertEquals(W5RandomGenerator.class, RandomGenerator.getDefaultImplStatic().getClass()); + + } + @Test + public void getName() { + assertEquals("testGenerator", randomGenerator.getName()); + } + + private final long[] randomNumbers = new long[]{ + 989766495916971073l, + + 752993031226338159l, + 208354589825897774l, + 630129986537696031l, + 122750107603623909l, + 87213201598134595l, + 732467883029815946l, + 751898065858841694l, + 579435717923219006l, + 313749987799630863l, + 884714377553716529l, + + 965051149136722169l, + 421787665199259631l, + 657038602346525671l, + 644714380109667537l, + 922906928077404901l, + 126313368451040874l, + 432338839333393149l, + 964607090671253533l, + 232964735789415443l, + 980665142167025862l, + + 469480217825462263l, + 899326816885015702l, + 875906247414770612l, + 419271813568148348l, + 955628780979616049l, + 964851394856633044l, + 920402918873167315l, + 44542537047619878l, + 287326444325502099l, + 794814281028802127l, + + 859177155807759723l, + 620591375117177024l, + 589187555016189839l, + 791188474180923574l, + 73454149626876152l, + 142674074411581083l, + 585073587365940420l, + 797609949662655103l, + 175124149742874202l, + 62869744120989896l, + + 551110293305242845l, + 127931539523886339l, + 920703134552677363l, + 732981382349612211l, + 62732588721496394l, + 44561050006996382l, + 119194178707933536l, + 978123130429376315l, + 862942328036352295l, + 57296861210520041l, + + 182897743270630415l, + 13207875902886200l, + 552533674022145482l, + 488462941904442l, + 863787304545250572l, + 413189539957215648l, + 229359591670445984l, + 804030022526807608l, + 596524207037097032l, + 934443234016356922l, + + 76899063002059964l, + 658148485712861578l, + 598631015449229747l, + 393367604407414191l, + 926192250542061452l, + 674530714803093099l, + 35980063030147176l, + 30954039774891937l, + 833583092170077764l, + 587471530888374861l, + + 910416218581766388l, + 89142545784819968l, + 151420602460129151l, + 271087393304205269l, + 290597398727472261l, + 27766748062900907l, + 446097133117871237l, + 191672387717785454l, + 797842155411794101l, + 69321366131136411l, + + 196344047914946886l, + 226534298261372486l, + 490733667486015817l, + 773800494736883628l, + 780878109429919665l, + 515093295699804077l, + 357085444986459223l, + 851849805620623387l, + 867722507013561571l, + 358088420691515641l, + + 924912656888885760l, + 791137295807713442l, + 692109859097581060l, + 595235990482238397l, + 909911716524758764l, + 724164923777388510l, + 586273377500475847l, + 686482600666828362l, + 122259762435890876l, + 566175710915777957l, + + 824013986198676042l, + 245061253612931712l, + 167220601921039098l, + 434074374001348226l, + 668858174281724461l, + 453804170192441776l, + 859959205173779472l, + 853636563417799200l, + 479051589857657035l, + 557683456529024680l, + + 296261642099843803l, + 165139612823205352l, + 155787048574294110l, + 143595911615173500l, + 673657014621949249l, + 906076400428015241l, + 513670209912993763l, + 967088312580862643l, + 7774131720357429l, + 630028985223713495l, + + 25673252210732419l, + 144773850559041528l, + 439733456225171722l, + 858180869123858142l, + 211394276775897243l, + 408958963895371321l, + 423472822369839857l, + 232250260713347003l, + 180706716595929038l, + 98596496887866469l, + + 875678307360992371l, + 437677508049887441l, + 125170452011422203l, + 538873642230562466l, + 245197558852455185l, + 932439585603976220l, + 855639307352288859l, + 954348029862438234l, + 414712671173750006l, + 115793895418238465l, + + 729484834132583888l, + 640350420376446233l, + 818925474623589460l, + 364705040323764220l, + 967195943649962411l, + 303126878372263790l, + 360410707087981191l, + 387292627370779711l, + 700601266013880678l, + 356883926601879126l, + + 22583787254966927l, + 986671573053499222l, + 998723929588817991l, + 771416126519180332l, + 474486512646652781l, + 478980122430145054l, + 207722595782621257l, + 79453748112027572l, + 527397308782140854l, + 585044216263462538l, + + 125397053030499187l, + 366348072275664491l, + 77735524260232115l, + 495683911214898558l, + 589156015838720909l, + 467920113868761777l, + 162071785283760169l, + 231818370419047340l, + 64307278747146290l, + 47784451860387975l, + + 980055089222892624l, + 764895420560925155l, + 507748042124615833l, + 187837301351429921l, + 161726553994583475l, + 151422489191956904l, + 995805250100891082l, + 805765551492075924l, + 779377962936816736l, + 714449863347865272l, + + 204015610543644036l, + 800804416286176830l, + 646873902118250214l, + 940547022409709067l, + 355335675726436202l, + 326830247048130605l, + 343704151019838190l, + 656205611304404762l, + 877236490577055500l, + 446537683901693422l, + + 451209390817813316l, + 11157320132649709l, + 140467946119304817l, + 625342666087475024l, + 342673456876050403l, + 315569879245239626l, + 207968007467613588l, + 977052991039833138l, + 277741169924035053l, + 469100868042333879l, + + 210908198788613658l, + 854488919399758838l, + 3288187261221639l, + 494117930374517280l, + 731270158063398126l, + 848080613499701383l, + 358143826050226673l, + 485357819668739357l, + 994980436445591452l, + 76293103128952918l, + + 778136068861694776l, + 670025736323147161l, + 352721274969489950l, + 485187894208110493l, + 702706773816545161l, + 44707306458740608l, + 944417111189439331l, + 894057190523044627l, + 30682149482009118l, + 76878633081476039l, + + 553790321773052068l, + 314230667439537839l, + 177236046084452338l, + 122014325466816562l, + 161909702213081218l, + 591811608817332520l, + 217450796035684001l, + 735138186156364486l, + 681433260907839992l, + 418486890410244753l, + + 680797495071076289l, + 747074640063267196l, + 970128954640424935l, + 749293492114586858l, + 11728511685421992l, + 262723921643718347l, + 52511438356285514l, + 906980307982728909l, + 714879316279668660l, + 221738484375496833l, + + 623442200780086407l, + 251366198355718391l, + 369497919802436634l, + 20566205275807771l, + 122283743988898264l, + 815446371346272803l, + 316726822909350586l, + 790134832122644904l, + 501226775853693784l, + 1337249705074813l, + + 453262610930759038l, + 646409148301283422l, + 115579604842016905l, + 33123012565546311l, + 978401269339561507l, + 44559377343909176l, + 19514897145295274l, + 147732651075503554l, + 62477757530514553l, + 260280421539621771l, + + 324238700214102842l, + 647134533413426639l, + 667861750635862171l, + 420689767461447978l, + 772352145109448446l, + 796179608438897262l, + 775193349127889400l, + 941347947779866031l, + 584282451615184212l, + 941377827111057142l, + + 96189303582019295l, + 116554265264888383l, + 64574525242522589l, + 107193428552434739l, + 245510251765329105l, + 166731170493188357l, + 809949044924133275l, + 758446436914795159l, + 703043770138182890l, + 954111788081599515l, + + 136859390487133799l, + 229398128019805757l, + 651047768724581987l, + 623470636016241482l, + 442548529015475022l, + 728985363468126656l, + 601534825724343989l, + 598462429001189524l, + 14767637168520017l, + 110164501031113217l, + + 2267313487106505l, + 602846630066870040l, + 942742593948916153l, + 257204231220552883l, + 41928825432205789l, + 776312071726565063l, + 684333501541382594l, + 63285132045891152l, + 522617064506888728l, + 399087258085430322l, + + 369335162042873576l, + 957670343495191416l, + 894002800673663108l, + 741978997518334019l, + 128424383495722946l, + 57080626670556024l, + 485987359155298593l, + 720571698380414156l, + 316090628021588845l, + 721320013932672383l, + + 616724893214386955l, + 107069018902912492l, + 335684669220671881l, + 439953298090264365l, + 668766344826342757l, + 574744557050893533l, + 837492715859226581l, + 939289420759255103l, + 98903495101419241l, + 441715606911262548l, + + 711796137250653774l, + 934294998305577754l, + 197739857572958523l, + 961031575986889814l, + 330389633371653429l, + 199423454318381389l, + 992806915531521002l, + 752430128263180102l, + 762067171884748509l, + 868397567289449078l, + + 978131695000691716l, + 832128538091881692l, + 332557797779603829l, + 394456793413733508l, + 180261204826305843l, + 376912355571214015l, + 699324587358673569l, + 23664544583454006l, + 327974511279267901l, + 120073261092787575l, + + 563426405452397018l, + 539285614539978334l, + 785159842287844887l, + 835395581519794346l, + 304538904528755810l, + 355722924067394933l, + 872021767601702295l, + 567818208391267105l, + 58356714335016452l, + 189908048834163l, + + 343501795801836652l, + 488363327236059203l, + 740530667847012558l, + 242398605490351338l, + 662829190349084673l, + 387176771976134318l, + 535572586279439811l, + 226785219604563426l, + 883971137296029526l, + 463867511805352267l, + + 225406583424538674l, + 767143254638275960l, + 627578036627621188l, + 25194585179292536l, + 159276033783105316l, + 533166587231767915l, + 195503830999903877l, + 143548530694574858l, + 586403308472695038l, + 251461295483424073l, + + 778235211474807028l, + 974511127821538962l, + 234351427339669293l, + 674903609403754570l, + 269821646330066486l, + 10514582197647671l, + 310058695603171887l, + 692680666938759459l, + 219702762257174799l, + 394327857010791187l, + + 104120696002956785l, + 932035253132951222l, + 705303760596228724l, + 168109021472592056l, + 908473434800454594l, + 633342640675753663l, + 196262077066269791l, + 130870864471689386l, + 269052619107011939l, + 945989485807845083l, + + 167108829297904344l, + 512431642627242657l, + 53724341864043852l, + 558641630923859339l, + 556959743803390749l, + 631425063603427402l, + 259979605773105171l, + 429845634788551705l, + 244769122315885960l, + 68536687575157864l, + + 688477984888810823l, + 733667124080264275l, + 881307008976788145l, + 85557557143709570l, + 547241936295049024l, + 608170667337476859l, + 58957920476606510l, + 966060963172955950l, + 867800335117402924l, + 67375619265528809l, + + 190969923528632347l, + 425149549991394157l, + 538334572515114711l, + 708307525017999452l, + 25983085084983815l, + 672261026943582858l, + 219667292242148547l, + 121957383179923845l, + 77600241275319820l, + 216862167739468905l, + + 606810218542445629l, + 943507623528873810l, + 969116817300440475l, + 12294116326297464l, + 6701016055162488l, + 624148164468923139l, + 78300069444424190l, + 19339949012001435l, + 165626331279732152l, + 535298529150864448l, + + 342297987067286266l, + 76712730862205265l, + 677273670705782858l, + 365940154344684371l, + 869554945670002296l, + 143520586808279523l, + 50570344277958922l, + 516182849234970511l, + 841581438239588733l, + 411495218013677191l, + + 672042442089442583l, + 388189082933141721l, + 532413363660096075l, + 245694872166351121l, + 173457735056327844l, + 55738952212441330l, + 685288240200814731l, + 473032558397903901l, + 943476816171477314l, + 672789553202097285l, + + 805925063742429491l, + 124678068431134300l, + 13921407309531118l, + 830591085998177448l, + 677885221100759302l, + 11585222315953622l, + 394914761078378599l, + 909884684182383685l, + 563688113563876970l, + 42694141238573193l, + + 419578667557172439l, + 147566640180796541l, + 346803738847761056l, + 378264395597132729l, + 930271350665310527l, + 437581192162885448l, + 299930128325228815l, + 240538700114345918l, + 259199844081041850l, + 874083841019950255l, + + 72260965305822261l, + 368038336038653535l, + 714122594498963544l, + 967513072020571246l, + 484984100291969771l, + 9452592082712525l, + 131894126687948613l, + 816971684689577237l, + 719491956090110547l, + 184818342461202456l, + + 789755232122159266l, + 8086343656007639l, + 26699760340096952l, + 781284894742592836l, + 25114915695064791l, + 685759569040742267l, + 226989427089149728l, + 520659265356096853l, + 526051806884389203l, + 781488870876163849l, + + 645865087449340773l, + 809989057949122731l, + 991235493762324907l, + 404707747203463395l, + 217109962102321421l, + 925147721894965627l, + 245797411148608332l, + 37234179444654375l, + 949620603085483027l, + 461465260728668501l, + + 188139378599779749l, + 943884429997790515l, + 554924935592323568l, + 155486103337003356l, + 98429650840068725l, + 744643263103143420l, + 217347355647296224l, + 34408212331573531l, + 987662457879222179l, + 557453354831676008l, + + 552194949301514231l, + 498679200317988091l, + 96173410445840903l, + 470259390124137059l, + 918846869428290795l, + 527541280515626944l, + 60266896027091098l, + 803321185229952136l, + 673869040626721885l, + 938647849874098059l, + + 230922827820056946l, + 112461300772429907l, + 879634712004775205l, + 598816372145594026l, + 24781318238269431l, + 799861815797916440l, + 549153933444765585l, + 877992147843679864l, + 651571788003265307l, + 442367527434582550l, + + 178372288197305720l, + 826839327598528358l, + 98774413195253460l, + 816432291769633027l, + 647962124566255034l, + 559374089603489176l, + 544605736920583258l, + 817024743564487677l, + 529396216145379263l, + 967712267561680183l, + + 504376644759607435l, + 446026341255411979l, + 695828899771876248l, + 835953376807091163l, + 26855908735118584l, + 238447183576881932l, + 993827408015672199l, + 833930996349911951l, + 173076358439417285l, + 657629865761042316l, + + 895867636891618365l, + 168944231763094742l, + 781190513685739063l, + 623214154683127617l, + 70075004308400680l, + 18443229148102777l, + 116932247227716414l, + 256057517353843325l, + 968929032552610408l, + 207014180855464275l, + + 816936789295741802l, + 882995528260035433l, + 926023904722708169l, + 412566385816249322l, + 525718689734642016l, + 46920823614039094l, + 721803959992601933l, + 898168692225347300l, + 934485935477344407l, + 575677109964718533l, + + 831409923501333949l, + 227533115045760681l, + 290666692630857576l, + 738134833093141619l, + 490488525842458863l, + 746816333196754644l, + 566021160371491180l, + 708616607887178478l, + 128659096747965617l, + 970839065344320588l, + + 566062071670423991l, + 584278724241763662l, + 32552672364919489l, + 37866008535922086l, + 472450513414112684l, + 696409119018293313l, + 115075911937425774l, + 424621772752312046l, + 511569662923999567l, + 92880606000027127l, + + 670098169072435269l, + 558056450072881022l, + 933378835959842396l, + 976604733923728806l, + 130322919640592354l, + 580712134609707403l, + 709037719269642214l, + 662262438038865940l, + 470453514500829867l, + 207366963580530330l, + + 793214185522905948l, + 51852989050826915l, + 808587861629563903l, + 432136681955100363l, + 186653579520578302l, + 282860108445159829l, + 445767399365275146l, + 907762598905806393l, + 193073464810090860l, + 360915499408439905l, + + 437807875937094684l, + 342704281471250858l, + 772853776000997108l, + 910808026239666144l, + 750773510093713546l, + 294650426417174248l, + 239395454575084931l, + 988245372995882576l, + 116788160781815856l, + 260427803867176874l, + + 160765275244852731l, + 457421767272628860l, + 954387940750518382l, + 663009953334137662l, + 635210353908427372l, + 202191859706540593l, + 730592613929605495l, + 560114800359292146l, + 118680166891048312l, + 37945444124052740l, + + 82561837702781039l, + 670968171275271971l, + 249762040649479013l, + 426742960251642201l, + 140131797903050209l, + 185585888977431133l, + 802883946492614673l, + 375966331892328518l, + 678515968858488398l, + 980554004646091626l, + + 271282266915421027l, + 713566381108325971l, + 195484642496969703l, + 937837809451789980l, + 116587593283362818l, + 12326068884729358l, + 311248065455402864l, + 268537300065713148l, + 830395257050669915l, + 517717524945941475l, + + 594706781477047517l, + 683514718104875033l, + 71811944144373759l, + 549184158793550316l, + 743962980344436770l, + 342815229646475244l, + 91820024504045781l, + 942183429383424182l, + 634567154658953208l, + 880813552161194772l, + + 937450136245659108l, + 359216376088709535l, + 86868034556739793l, + 278428450887175865l, + 548644880526995838l, + 468965562244484588l, + 853471036651405927l, + 8707407169342708l, + 749597355229463749l, + 824330701508242834l, + + 333814657130019606l, + 979058204952438795l, + 462673809227471775l, + 536914299306206417l, + 971285548245198442l, + 784544499996793098l, + 121899926051377836l, + 500200468001370135l, + 863713040769516555l, + 149374448127027320l, + + 195968112763074517l, + 875555620594003339l, + 87922904524696016l, + 6167146666167473l, + 750019279660004038l, + 793059668144961967l, + 313591420157104300l, + 291353638706672805l, + 34005427496032037l, + 404306311566585712l, + + 982104925320434595l, + 621802565491163415l, + 380546341802334942l, + 282624560308059338l, + 332765931735475715l, + 54875760860716960l, + 184820261436826411l, + 298338878388543994l, + 74076826076886381l, + 49573770474794851l, + + 973395222473939314l, + 64651430740271251l, + 929010958483401561l, + 37911712122731241l, + 632987115622895492l, + 782598739454753832l, + 64661505976924920l, + 789897433985290804l, + 27464097941226613l, + 123510101443062121l, + + 33498761022578628l, + 468710335459633953l, + 438430699110659170l, + 850870972391715098l, + 339812322380229534l, + 523007559257421888l, + 263416253899555937l, + 132523463308547710l, + 24838429221983195l, + 300869548000262289l, + + 343418926622874467l, + 30181716442445862l, + 529364455337554114l, + 292068669069465220l, + 64769173797843942l, + 249469622904871477l, + 234469028566604888l, + 735530319785919659l, + 917242500339529288l, + 616037710995254445l, + + 749129146363729104l, + 778125197706617057l, + 508374702704627684l, + 72638011840510682l, + 484654969086851340l, + 950681819081366290l, + 405552770893024111l, + 120788073807664024l, + 240225181610043759l, + 756173519263400684l, + + 13886814190793329l, + 431811651361404368l, + 785644429323050469l, + 265083669668502313l, + 733468396640565119l, + 372535991695630142l, + 24818311402075021l, + 521896835131504122l, + 392125133711207535l, + 193359056782367881l, + + 56285603302444520l, + 226057805358921359l, + 643195421142563932l, + 104039098798909983l, + 626861113096363266l, + 84979886179949074l, + 486561880501439802l, + 619593458713206099l, + 225357170894458053l, + 35456814333125993l, + + 721058429053269174l, + 307576443080026683l, + 476143167247863238l, + 659345640009293086l, + 985001803816353351l, + 38729588081549534l, + 813458085650668800l, + 570847499633521267l, + 660108714578144950l, + 661225024935217344l, + + 42748541343135302l, + 542409368779631480l, + 528124190371792375l, + 713468453464772935l, + 484088995075370541l, + 981866214702501659l, + 666616968432354481l, + 915366435818397300l, + 874789585783968537l, + 370682054020070752l, + + 62400492067982047l, + 499850828608660586l, + 937308826652753434l, + 128558027742649386l, + 515758774554168845l, + 418916546792152877l, + 117458158181369773l, + 49562168386073568l, + 807699418958763493l, + 742145797937476656l, + + 658882936116031548l, + 204462546453824419l, + 902445336976128875l, + 92692847289431172l, + 704173225059386342l, + 66639290013818113l, + 410809876283803885l, + 35952706968093473l, + 759178465001909493l, + 704067752087811350l, + + 986846122776679407l, + 688733536926677107l, + 856981725890032261l, + 988531073663474807l, + 713944308475162539l, + 118847362753841156l, + 732154169724665416l, + 19005988695596513l, + 832967922377006760l, + 973672108375451327l, + + 725363671507632935l, + 718391433167648827l, + 352442795126799491l, + 784366612685799127l, + 903475113629207005l, + 687344358628029044l, + 931153086939207082l, + 104622912997824952l, + 82734710816696367l, + 442945641213286735l, + + 466668555176155455l, + 323463885452719651l, + 188346511024345667l, + 766367939017272210l, + 965557189722432799l, + 230021363393593477l, + 929823950768692802l, + 252119831032411121l, + 8663957261501470l, + 113678441668172265l, + + 346067535048822494l, + 611852318957245790l, + 143506956345691962l, + 298077130751139726l, + 30362893522113816l, + 584809401672606297l, + 970507405565942077l, + 651371758660525390l, + 621096534538655650l, + 913256556326717871l, + + 648137154880192988l, + 225633300626096742l, + 566328830294529543l, + 224653110464048130l, + 934793514428492485l, + 368669206081879487l, + 492047566736472873l, + 55677597207791273l, + 511090860495737174l, + 805179231181087093l, + + 579465450607118895l, + 943178320920110013l, + 444370234898293122l, + 85402155273287473l, + 362296626894728546l, + 904433285064260477l, + 190330319436502780l, + 59222297912696625l, + 408990860335567709l, + 589474956992376535l, + + 612081053822594602l, + 273841370377697349l, + 272219993018871562l, + 790440816539391295l, + 181577768978858005l, + 239045710732833793l, + 427305914448398239l, + 810713867022076074l, + 422004697986874870l, + 61779602162057360l, + + 980850466579786024l, + 897408269714821783l, + 619814398120106912l, + 210645472288950922l, + 588031623554562447l, + 577816781653286458l, + 597096829305673645l, + 303263549224049320l, + 156355604966014545l, + 999940201019640042l, + + 545864139992129854l, + 349017325128116083l, + 312747275210422873l, + 769921140030237021l, + 583681481462832740l, + 876665826353151013l, + 958730437530779530l, + 388741443686872468l, + 549591630978958697l, + 443407922528477935l, + + 82305770875576464l, + 302021456870308996l, + 116477878113900295l, + 856679918251291335l, + 974226342944969019l, + 694139457609844063l, + 726774949030800224l, + 86877842882273743l, + 23661131870341092l, + 519961257582540181l, + + 124870722812351703l, + 297797906052041293l, + 529300884305730318l, + 743823006938836829l, + 693356820954784852l, + 70200457779735722l, + 557950436116202181l, + 178048064580575228l, + 745694808225018793l, + 505492689124300290l, + + 40688677867063716l, + 906029319339783317l, + 723220762979849441l, + 800464128881487142l, + 16347017065781833l, + 569886286729488306l, + 325425109670718805l, + 799442369608504858l, + 517422685398994930l, + 483902362458877314l, + + 343944156351081038l, + 263401490344217325l, + 891805550054649417l, + 549964066230638103l, + 114442932252102499l, + 640299083036361103l, + 341716062024968086l, + 680156879554562369l, + 33197732406536887l, + 662573057092916456l, + + 23166250889366276l, + 439588424130385671l, + 976147149098943410l, + 966634459881083697l, + 955059511573997874l, + 602113383584625957l, + 873746183951302433l, + 106714649853262351l, + 266085001547779077l, + 602087418558089717l, + + 771162091195456127l, + 998022611394638150l, + 578861073290344770l, + 13953259172769202l, + 263059390252436849l, + 713849611657917124l, + 278753817441368442l, + 209565289634712522l, + 86628925891496630l, + 498675700983612899l, + + 352975355046283550l, + 807496683264729873l, + 757414973431593798l, + 624901866090760637l, + 431198654617222493l, + 223908778956608211l, + 992095795763587040l, + 371430120032038210l, + 895172486004081377l, + 512169660024349480l, + + 767660901924081084l, + 7567310010434317l, + 493691704503907170l, + 651819017168740877l, + 419256610638853952l, + 476464930284074251l, + 250867234483595881l, + 96309592020475526l, + 167816615939027947l, + 964084605323017643l, + + 78696641868548689l, + 619677965603222936l, + 867538832840647115l, + 708534737809458263l, + 528951692596349161l, + 410702275077305522l, + 98861683128847623l, + 685470552066531037l, + 102158622587431874l, + 892742832708342987l, + + 276250292240003760l, + 239000555803703746l, + 41085552660210325l, + 104036952726091280l, + 35294919829298821l, + 642288598713607316l, + 655668230261877292l, + 256750121560967030l, + 51978151194127888l, + 168586225957102212l, + + 721423574237200365l, + 591127759846196563l, + 160139061303914939l, + 85049184808387624l, + 448955483195415375l, + 828466296971252038l, + 16440113349605274l, + 287422461146256705l, + 695577615454841932l + }; +} diff --git a/power-random/src/test/java/org/nanoboot/powerframework/random/generators/linearcongruent/CPlusPlus11LinearCongruentGeneratorTest.java b/power-random/src/test/java/org/nanoboot/powerframework/random/generators/linearcongruent/CPlusPlus11LinearCongruentGeneratorTest.java new file mode 100644 index 0000000..e2544c8 --- /dev/null +++ b/power-random/src/test/java/org/nanoboot/powerframework/random/generators/linearcongruent/CPlusPlus11LinearCongruentGeneratorTest.java @@ -0,0 +1,53 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.generators.linearcongruent; + +import org.nanoboot.powerframework.core.exceptions.UnsupportedMethodException; +import org.junit.Before; +import org.junit.Test; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class CPlusPlus11LinearCongruentGeneratorTest { + /** + * initial seed. + */ + private static final long INITIAL_SEED = 100000; + + private CPlusPlus11LinearCongruentGenerator g; + @Before + public void setup() { + g = new CPlusPlus11LinearCongruentGenerator(INITIAL_SEED); + } + @Test(expected = UnsupportedMethodException.class) + public void current() { + g.current(); + } + + @Test(expected = UnsupportedMethodException.class) + public void initialSeed() { + g.initialSeed(); + } +} diff --git a/power-random/src/test/java/org/nanoboot/powerframework/random/generators/linearcongruent/LinearCongruentGeneratorTest.java b/power-random/src/test/java/org/nanoboot/powerframework/random/generators/linearcongruent/LinearCongruentGeneratorTest.java new file mode 100644 index 0000000..f2f0d37 --- /dev/null +++ b/power-random/src/test/java/org/nanoboot/powerframework/random/generators/linearcongruent/LinearCongruentGeneratorTest.java @@ -0,0 +1,103 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.generators.linearcongruent; + +import org.junit.Before; +import org.junit.Test; + +import java.util.stream.IntStream; + +import static org.junit.Assert.*; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class LinearCongruentGeneratorTest { + + /** + * multiplier constant. + */ + private static final long MULTIPLIER = 16807; + + /** + * increment constant. + */ + private static final long INCREMENT = 0; + + /** + * modulus constant. + */ + private static final long MODULUS = 2147483647; + /** + * initial seed. + */ + private static final long INITIAL_SEED = 100000; + + private LinearCongruentGenerator g; + @Before + public void setup() { + g = new LinearCongruentGenerator(MULTIPLIER, INCREMENT, MODULUS, INITIAL_SEED); + } + @Test + public void next() { + assertEquals(((MULTIPLIER * INITIAL_SEED) + INCREMENT) % MODULUS, g.next()); + } + + @Test + public void current() { + g.next(); + assertEquals(((MULTIPLIER * INITIAL_SEED) + INCREMENT) % MODULUS, g.current()); + } + + @Test + public void initialSeed() { + IntStream.range(0, 100).forEach(i -> g.next()); + assertEquals(INITIAL_SEED, g.initialSeed()); + } + + @Test + public void getItself() { + assertEquals(g, g.getItself()); + } + + @Test + public void getName() { + assertEquals(g.getClass().getName(), g.getName()); + } + + @Test + public void getMultiplier() { + assertEquals(MULTIPLIER, g.getMultiplier()); + } + + @Test + public void getIncrement() { + assertEquals(INCREMENT, g.getIncrement()); + } + + @Test + public void getModulus() { + assertEquals(MODULUS, g.getModulus()); + } +} diff --git a/power-random/src/test/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5GeneratorsFactoryImplTest.java b/power-random/src/test/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5GeneratorsFactoryImplTest.java new file mode 100644 index 0000000..793d8fb --- /dev/null +++ b/power-random/src/test/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5GeneratorsFactoryImplTest.java @@ -0,0 +1,59 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.generators.linearcongruent.combined.w5; + +import org.nanoboot.powerframework.random.RandomException; +import org.nanoboot.powerframework.random.generators.linearcongruent.CPlusPlus11LinearCongruentGenerator; +import org.junit.Test; + +import static junit.framework.TestCase.assertEquals; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class W5GeneratorsFactoryImplTest { + + private W5GeneratorsFactoryImpl g; + + @Test(expected = RandomException.class) + public void constructor2() { + new W5GeneratorsFactoryImpl(null); + } + @Test(expected = RandomException.class) + public void constructor3() { + new W5GeneratorsFactoryImpl(new long[] {1,2,3,4,5,6,7}); + } + + @Test + public void getSubGenerators() { + W5GeneratorsFactoryImpl w5GeneratorsFactory = new W5GeneratorsFactoryImpl(new long[] {1l,2l,3l,4l,5l,6l,7l,8l}); + CPlusPlus11LinearCongruentGenerator[] array = w5GeneratorsFactory.getSubGenerators(); + StringBuilder sb = new StringBuilder(); + for(CPlusPlus11LinearCongruentGenerator e : array) { + sb.append(e.nextInt(0,9)).append(","); + sb.append(e.nextInt(0,9)).append(","); + sb.append(e.nextInt(0,9)).append(","); + } + assertEquals("4,8,3,0,3,1,0,0,7,", sb.toString()); + } +} diff --git a/power-random/src/test/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5GeneratorsProcessorImplTest.java b/power-random/src/test/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5GeneratorsProcessorImplTest.java new file mode 100644 index 0000000..1757ee9 --- /dev/null +++ b/power-random/src/test/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5GeneratorsProcessorImplTest.java @@ -0,0 +1,51 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.generators.linearcongruent.combined.w5; + +import org.nanoboot.powerframework.random.RandomException; +import org.nanoboot.powerframework.random.generators.linearcongruent.CPlusPlus11LinearCongruentGenerator; +import org.junit.Before; +import org.junit.Test; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class W5GeneratorsProcessorImplTest { + + private W5GeneratorsProcessorImpl p; + @Before + public void setup() { + p = new W5GeneratorsProcessorImpl(); + } + @Test(expected = RandomException.class) + public void next() { + p.next(null); + } + @Test(expected = RandomException.class) + public void next2() { + p.next( + new CPlusPlus11LinearCongruentGenerator(20), + new CPlusPlus11LinearCongruentGenerator(30) + ); + } +} diff --git a/power-random/src/test/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5RandomGeneratorTest.java b/power-random/src/test/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5RandomGeneratorTest.java new file mode 100644 index 0000000..cf85e4c --- /dev/null +++ b/power-random/src/test/java/org/nanoboot/powerframework/random/generators/linearcongruent/combined/w5/W5RandomGeneratorTest.java @@ -0,0 +1,59 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.generators.linearcongruent.combined.w5; + +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class W5RandomGeneratorTest { + + W5RandomGenerator g; + @Before + public void setup() { + g = new W5RandomGenerator(); + } + @Test + public void getStaticInstance() { + assertNotNull(W5RandomGenerator.getStaticInstance()); + } + + @Test + public void getItself() { + assertEquals(g, g.getItself()); + } + + @Test + public void getName() { + assertEquals(g.getClass().getName(), g.getName()); + } + + @Test + public void next() { + assertNotNull(g.next()); + } +} diff --git a/power-random/src/test/java/org/nanoboot/powerframework/random/internal/RandomTextUtilsTest.java b/power-random/src/test/java/org/nanoboot/powerframework/random/internal/RandomTextUtilsTest.java new file mode 100644 index 0000000..7096879 --- /dev/null +++ b/power-random/src/test/java/org/nanoboot/powerframework/random/internal/RandomTextUtilsTest.java @@ -0,0 +1,49 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.random.internal; + +import org.nanoboot.powerframework.random.generators.RandomGenerator; +import org.nanoboot.powerframework.text.CharacterType; +import org.junit.Test; + +import static org.junit.Assert.*; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class RandomTextUtilsTest { + + @Test + public void nextChar() { + RandomGenerator rg = RandomGenerator.getDefaultImplStatic(); + char ch = RandomTextUtils.nextChar(rg, null); + assertTrue(Character.isDigit(ch) || Character.isUpperCase(ch) || Character.isLowerCase(ch)); + ch = RandomTextUtils.nextChar(rg, new CharacterType[] {}); + assertTrue(Character.isDigit(ch) || Character.isUpperCase(ch) || Character.isLowerCase(ch)); + ch = RandomTextUtils.nextChar(rg, CharacterType.LOWER_LETTER); + assertTrue(Character.isLowerCase(ch)); + ch = RandomTextUtils.nextChar(rg, CharacterType.LOWER_LETTER, CharacterType.NUMBER); + assertTrue(Character.isDigit(ch) || Character.isLowerCase(ch)); + + } +} diff --git a/power-redmond/pom.xml b/power-redmond/pom.xml new file mode 100644 index 0000000..b874caf --- /dev/null +++ b/power-redmond/pom.xml @@ -0,0 +1,58 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-redmond + jar + + Power Redmond + Redmond for the Power library + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + org.nanoboot.powerframework + power-log + ${power.version} + + + + + junit + junit + 4.12 + test + + + diff --git a/power-redmond/src/main/java/module-info.java b/power-redmond/src/main/java/module-info.java new file mode 100644 index 0000000..f99825e --- /dev/null +++ b/power-redmond/src/main/java/module-info.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +module powerframework.template { + requires powerframework.core; + requires powerframework.log; + requires powerframework.utils; +} diff --git a/power-redmond/src/main/java/org/nanoboot/powerframework/redmond/.gitkeep b/power-redmond/src/main/java/org/nanoboot/powerframework/redmond/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-redmond/src/main/resources/.gitkeep b/power-redmond/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-redmond/src/test/java/org/nanoboot/powerframework/redmond/.gitkeep b/power-redmond/src/test/java/org/nanoboot/powerframework/redmond/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-reflection/pom.xml b/power-reflection/pom.xml new file mode 100644 index 0000000..70eceae --- /dev/null +++ b/power-reflection/pom.xml @@ -0,0 +1,57 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-reflection + jar + + Power Reflection + Reflection functionality for the Power library + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + + junit + junit + 4.12 + test + + + org.projectlombok + lombok + + + + diff --git a/power-reflection/src/main/java/module-info.java b/power-reflection/src/main/java/module-info.java new file mode 100644 index 0000000..77ace08 --- /dev/null +++ b/power-reflection/src/main/java/module-info.java @@ -0,0 +1,31 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +module powerframework.reflection { + requires lombok; + requires powerframework.core; + exports org.nanoboot.powerframework.reflection; +} diff --git a/power-reflection/src/main/java/org/nanoboot/powerframework/reflection/BeanMethod.java b/power-reflection/src/main/java/org/nanoboot/powerframework/reflection/BeanMethod.java new file mode 100644 index 0000000..e6a4f35 --- /dev/null +++ b/power-reflection/src/main/java/org/nanoboot/powerframework/reflection/BeanMethod.java @@ -0,0 +1,51 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.reflection; + +import lombok.Getter; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public enum BeanMethod { + /** + * Getter - get prefix. + */ + GETTER("get"), + /** + * Setter - set prefix. + */ + + SETTER("set"); + + /** + * Bean method prefix. + */ + @Getter + private final String prefix; + + BeanMethod(final String prefixIn) { + this.prefix = prefixIn; + } +} diff --git a/power-reflection/src/main/java/org/nanoboot/powerframework/reflection/ReflectionUtils.java b/power-reflection/src/main/java/org/nanoboot/powerframework/reflection/ReflectionUtils.java new file mode 100644 index 0000000..88e116b --- /dev/null +++ b/power-reflection/src/main/java/org/nanoboot/powerframework/reflection/ReflectionUtils.java @@ -0,0 +1,211 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.reflection; + +import org.nanoboot.powerframework.core.PowerException; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public final class ReflectionUtils { + /** + * Constructor. + */ + private ReflectionUtils() { + //Not needed to be instantiated. + } + + /** + * @param classFullName class full name + * @return Class instance with the given name + * @throws PowerException, if there is found no such class + */ + public static Class getClassForName(final String classFullName) { + Class clazz = null; + try { + clazz = Class.forName(classFullName); + } catch (ClassNotFoundException e) { + throw new PowerException(e); + } + return clazz; + } + /** + * @param clazz Class instance + * @param parameterTypes parameter types + * + * @return Constructor instance with the given parameter types + * @throws PowerException, if there is found no such class + */ + public static Constructor getConstructor( + final Class clazz, final Class... parameterTypes) { + Constructor constructor; + try { + constructor = clazz.getConstructor(parameterTypes); + } catch (NoSuchMethodException e) { + StringBuilder sb = new StringBuilder(); + for (Class c :parameterTypes) { + sb.append(c.getName()); + sb.append(", "); + } + String msg = "Class " + clazz + + " has no constructor with parameters \"" + + sb.toString() + "\" " + e.toString(); + throw new PowerException(msg); + } + + return constructor; + } + + /** + * @param constructor constructor + * @param parameters parameters + * + * @return Object instance for the given constructor + * @throws PowerException, if instantiation failed + */ + public static Object newInstance( + final Constructor constructor, + final Object... parameters) { + Object o; + try { + o = constructor.newInstance(parameters); + } catch (InstantiationException + | IllegalAccessException | InvocationTargetException e) { + throw new PowerException(e); + } + return o; + + } + /** + * @param forClass class + * @param methodName method name + * @param parameterTypes parameter types + * + * @return Constructor instance with the given parameter types + * @throws PowerException, if there is found no such method + */ + public static Method getMethod( + final Class forClass, + final String methodName, + final Class... parameterTypes) { + Method method; + try { + method = forClass.getMethod(methodName, parameterTypes); + } catch (NoSuchMethodException e) { + throw new PowerException(e); + } + + return method; + } + + /** + * Invokes a method. + * @param method method + * @param o object + * @param args arguments + * @return Return object, if there is one + */ + public static Object invokeMethod( + final Method method, + final Object o, + final Object... args) { + try { + return method.invoke(o, args); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new PowerException(e); + } + + } + + /** + * @param beanName bean name + * @return getter name + */ + public static String getGetterMethodName(final String beanName) { + return getBeanMethodName(beanName, BeanMethod.GETTER); + } + /** + * @param beanName bean name + * @return setter name + */ + public static String getSetterMethodName(final String beanName) { + return getBeanMethodName(beanName, BeanMethod.SETTER); + } + + /** + * @param beanName bean name + * @param beanMethod bean method + * @return bean method name + */ + private static String getBeanMethodName( + final String beanName, + final BeanMethod beanMethod) { + return beanMethod.getPrefix() + + makeFirstLetterUpperCase(beanName); + } + + /** + * Makes the first letter upper case. + * @param string input string + * @return modified string + */ + private static String makeFirstLetterUpperCase(final String string) { + return string.substring(0, 1) + .toUpperCase() + string.substring(1, string.length()); + } + + /** + * Invoke setter of a object for a bean. + * + * @param object object + * @param beanName bean name + * @param bean bean + */ + public static void setBean( + final Object object, final String beanName, final Object bean) { + Method method = getMethod( + object.getClass(), + getSetterMethodName(beanName), + bean.getClass()); + invokeMethod(method, object, bean); + } + /** + * Invoke getter of a object for a bean. + * + * @param object object + * @param beanName bean name + * @return bean + */ + public static Object getBean( + final Object object, + final String beanName) { + Method method = getMethod( + object.getClass(), getGetterMethodName(beanName)); + return invokeMethod(method, object); + } +} diff --git a/power-reflection/src/main/resources/.gitkeep b/power-reflection/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-reflection/src/test/java/org/nanoboot/powerframework/reflection/ReflectionUtilsTest.java b/power-reflection/src/test/java/org/nanoboot/powerframework/reflection/ReflectionUtilsTest.java new file mode 100644 index 0000000..fff5b72 --- /dev/null +++ b/power-reflection/src/test/java/org/nanoboot/powerframework/reflection/ReflectionUtilsTest.java @@ -0,0 +1,131 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.reflection; + +import org.nanoboot.powerframework.core.PowerException; +import org.junit.Test; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; + +import static org.junit.Assert.assertEquals; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class ReflectionUtilsTest { + + @Test(expected = PowerException.class) + public void getClassForName() { + //prepare + //execute + ReflectionUtils.getClassForName("abc.Def"); + //verify + } + + @Test(expected = PowerException.class) + public void getConstructor() { + //prepare + //execute + ReflectionUtils.getConstructor(Integer.class, Boolean.class); + //verify + } + + @Test(expected = PowerException.class) + public void newInstance() { + //prepare + + //execute + Constructor constructor; + try { + constructor = TestClassWithBadConstructorAndMethods.class.getConstructor(); + } catch (NoSuchMethodException e) { + throw new AssertionError(e); + } + ReflectionUtils.newInstance(constructor); + //verify + } + + @Test(expected = PowerException.class) + public void getMethod() { + //prepare + //execute + ReflectionUtils.getMethod(Integer.class, "abc"); + //assert + } + + @Test(expected = PowerException.class) + public void invokeMethod() { + //prepare + TestClassWithBadConstructorAndMethods testClassWithBadConstructorAndMethods = + new TestClassWithBadConstructorAndMethods(true); + //execute + Method method = ReflectionUtils.getMethod( + TestClassWithBadConstructorAndMethods.class, + "throwIllegalAccessException"); + ReflectionUtils.invokeMethod(method, testClassWithBadConstructorAndMethods); + //assert + } + + @Test + public void getGetterMethodName() { + //prepare + //execute + //assert + assertEquals("getMyName", ReflectionUtils.getGetterMethodName("myName")); + } + + @Test + public void getSetterMethodName() { + //prepare + //execute + //assert + assertEquals("setMyName", ReflectionUtils.getSetterMethodName("myName")); + } + + @Test + public void setBean() { + //prepare + TestClassWithBadConstructorAndMethods testClassWithBadConstructorAndMethods = + new TestClassWithBadConstructorAndMethods(true); + //execute + //assert + ReflectionUtils. + setBean(testClassWithBadConstructorAndMethods, "name", "testName"); + String returned = testClassWithBadConstructorAndMethods.getName(); + assertEquals("testName", returned); + } + + @Test + public void getBean() { + //prepare + TestClassWithBadConstructorAndMethods testClassWithBadConstructorAndMethods = + new TestClassWithBadConstructorAndMethods(true); + testClassWithBadConstructorAndMethods.setName("testName"); + //execute + //assert + Object returned = ReflectionUtils. + getBean(testClassWithBadConstructorAndMethods, "name"); + assertEquals("testName",returned); + } +} diff --git a/power-reflection/src/test/java/org/nanoboot/powerframework/reflection/TestClassWithBadConstructorAndMethods.java b/power-reflection/src/test/java/org/nanoboot/powerframework/reflection/TestClassWithBadConstructorAndMethods.java new file mode 100644 index 0000000..d7d8deb --- /dev/null +++ b/power-reflection/src/test/java/org/nanoboot/powerframework/reflection/TestClassWithBadConstructorAndMethods.java @@ -0,0 +1,46 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.reflection; + +import lombok.Getter; +import lombok.Setter; + +/** + * Testing class with bad constructor throwing a RuntimeException. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class TestClassWithBadConstructorAndMethods { + @Getter + @Setter + private String name; + + public TestClassWithBadConstructorAndMethods() { + throw new RuntimeException("test exception"); + } + //OK constructor + public TestClassWithBadConstructorAndMethods(boolean booleanForOkConstructor) { + } + public void throwIllegalAccessException() throws IllegalAccessException { + throw new IllegalAccessException("test IllegalAccessException"); + } +} diff --git a/power-security/pom.xml b/power-security/pom.xml new file mode 100644 index 0000000..2c0901c --- /dev/null +++ b/power-security/pom.xml @@ -0,0 +1,51 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-security + jar + + Power Security + security + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + + + org.projectlombok + lombok + + + diff --git a/power-security/src/main/java/module-info.java b/power-security/src/main/java/module-info.java new file mode 100644 index 0000000..50f96f8 --- /dev/null +++ b/power-security/src/main/java/module-info.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +module powerframework.security { + exports org.nanoboot.powerframework.security.hash.api; + exports org.nanoboot.powerframework.security.hash.locator; + requires lombok; + requires powerframework.core; +} diff --git a/power-security/src/main/java/org/nanoboot/powerframework/security/SecurityException.java b/power-security/src/main/java/org/nanoboot/powerframework/security/SecurityException.java new file mode 100644 index 0000000..1fb2d89 --- /dev/null +++ b/power-security/src/main/java/org/nanoboot/powerframework/security/SecurityException.java @@ -0,0 +1,34 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.security; + +import org.nanoboot.powerframework.core.PowerException; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class SecurityException extends PowerException { + public SecurityException(String msg) { + super(msg); + } +} diff --git a/power-security/src/main/java/org/nanoboot/powerframework/security/hash/api/HashCalculator.java b/power-security/src/main/java/org/nanoboot/powerframework/security/hash/api/HashCalculator.java new file mode 100644 index 0000000..0d38fb8 --- /dev/null +++ b/power-security/src/main/java/org/nanoboot/powerframework/security/hash/api/HashCalculator.java @@ -0,0 +1,114 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.security.hash.api; + +import java.io.UnsupportedEncodingException; +import java.math.BigInteger; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public interface HashCalculator { + String UTF_8 = "UTF-8"; + + String hash(byte[] dataToHash); + + default String hash(String dataToHash) { + byte[] byteArray = new byte[0]; + try { + byteArray = dataToHash.getBytes(UTF_8); + } catch (UnsupportedEncodingException e) { + throw new SecurityException(e.getMessage()); + } + return hash(byteArray); + } + + String getName(); + int getLength(); + + default String convertHexStringToDecString(String hex) { + return new BigInteger(hex, 16).toString(); + } + + default String convertDecStringToHexString(String dec) { + String str = convertDecStringToBigInteger(dec).toString(16); + ; + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < (getLength() - str.length()); i++) { + sb.append("0"); + } + sb.append(str); + return sb.toString(); + } + + default BigInteger convertDecStringToBigInteger(String dec) { + return new BigInteger(dec, 10); + } + + default String convertBigIntegerToDecString(BigInteger bi) { + return bi.toString(10); + } + + /** + * @param hex1 + * @param hex2 + * @return if 0, then hex1=hex2. if -1, then hex1hex2. + */ + default int compareHexNumbers(String hex1, String hex2) { + int result = hex1.compareTo(hex2); + if (result == 0) { + return 0; + } + if (result < 0) { + return -1; + } else { + return 1; + } + } + + public static void main(String[] args) { + System.out.println("convertHexToDec(F)=" + new BigInteger("F", 16).toString()); + System.out.println("convertDecToHex(15)=" + new BigInteger("15", 10).toString(16)); + HashCalculator hc = new HashCalculator() { + @Override + public String hash(byte[] dataToHash) { + return null; + } + + @Override + public String getName() { + return null; + } + + @Override + public int getLength() { + return 0; + } + }; + System.out.println("compareHexNumbers(c,c)=" + hc.compareHexNumbers("c", "c")); + System.out.println("compareHexNumbers(c,e)=" + hc.compareHexNumbers("c", "e")); + System.out.println("compareHexNumbers(e,c)=" + hc.compareHexNumbers("e", "c")); + } +} diff --git a/power-security/src/main/java/org/nanoboot/powerframework/security/hash/impl/AbstractShaHashCalculator.java b/power-security/src/main/java/org/nanoboot/powerframework/security/hash/impl/AbstractShaHashCalculator.java new file mode 100644 index 0000000..f3e7f49 --- /dev/null +++ b/power-security/src/main/java/org/nanoboot/powerframework/security/hash/impl/AbstractShaHashCalculator.java @@ -0,0 +1,59 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.security.hash.impl; + +import org.nanoboot.powerframework.security.hash.api.HashCalculator; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public abstract class AbstractShaHashCalculator implements HashCalculator { + + @Override + public String hash(byte[] dataToHash) { + MessageDigest digest = null; + byte[] bytes = null; + try { + digest = MessageDigest.getInstance(getName()); + digest.reset(); + bytes = digest.digest(dataToHash); + } catch (NoSuchAlgorithmException ex) { + throw new SecurityException(ex.getMessage()); + } + StringBuffer buffer = new StringBuffer(); + for (byte b : bytes) { + buffer.append(String.format("%02x", b)); + } +// if (Math.random() < 0.1) +// try { +// Thread.sleep(3); +// } catch (InterruptedException e) { +// e.printStackTrace(); +// } + return buffer.toString(); + } +} diff --git a/power-security/src/main/java/org/nanoboot/powerframework/security/hash/impl/Sha1HashCalculator.java b/power-security/src/main/java/org/nanoboot/powerframework/security/hash/impl/Sha1HashCalculator.java new file mode 100644 index 0000000..1ecfa0a --- /dev/null +++ b/power-security/src/main/java/org/nanoboot/powerframework/security/hash/impl/Sha1HashCalculator.java @@ -0,0 +1,41 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.security.hash.impl; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public final class Sha1HashCalculator extends AbstractShaHashCalculator { + + public static final String SHA_1 = "SHA-1"; + + @Override + public String getName() { + return SHA_1; + } + + @Override + public int getLength() { + return 40; + } +} diff --git a/power-security/src/main/java/org/nanoboot/powerframework/security/hash/impl/Sha256HashCalculator.java b/power-security/src/main/java/org/nanoboot/powerframework/security/hash/impl/Sha256HashCalculator.java new file mode 100644 index 0000000..f202d4c --- /dev/null +++ b/power-security/src/main/java/org/nanoboot/powerframework/security/hash/impl/Sha256HashCalculator.java @@ -0,0 +1,41 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.security.hash.impl; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public final class Sha256HashCalculator extends AbstractShaHashCalculator { + + public static final String SHA_256 = "SHA-256"; + + @Override + public String getName() { + return SHA_256; + } + + @Override + public int getLength() { + return 64; + } +} diff --git a/power-security/src/main/java/org/nanoboot/powerframework/security/hash/locator/HashCalculatorLocator.java b/power-security/src/main/java/org/nanoboot/powerframework/security/hash/locator/HashCalculatorLocator.java new file mode 100644 index 0000000..f79b84c --- /dev/null +++ b/power-security/src/main/java/org/nanoboot/powerframework/security/hash/locator/HashCalculatorLocator.java @@ -0,0 +1,66 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.security.hash.locator; + +import org.nanoboot.powerframework.security.hash.api.HashCalculator; +import org.nanoboot.powerframework.security.hash.impl.Sha256HashCalculator; + +import java.util.HashMap; +import java.util.Map; +import org.nanoboot.powerframework.security.hash.impl.Sha1HashCalculator; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class HashCalculatorLocator { + + private static final Map map = new HashMap<>(); + + public static HashCalculator locate(String hashImplname) { + return locate(HashImpl.valueOf(hashImplname)); + } + + public static HashCalculator locate(HashImpl hashImpl) { + String name = hashImpl.getName(); + if (!map.containsKey(name)) { + switch (name) { + case "SHA-1": + map.put(name, new Sha1HashCalculator()); + break; + case "SHA-256": + map.put(name, new Sha256HashCalculator()); + break; + default: { + //nothing to do + } + } + } + HashCalculator hashCalculator = map.get(name); + if (hashCalculator == null) { + String msg = "HashCalculator with name " + name + " was not found."; + throw new SecurityException(msg); + } + return hashCalculator; + } +} diff --git a/power-security/src/main/java/org/nanoboot/powerframework/security/hash/locator/HashImpl.java b/power-security/src/main/java/org/nanoboot/powerframework/security/hash/locator/HashImpl.java new file mode 100644 index 0000000..3af0b2c --- /dev/null +++ b/power-security/src/main/java/org/nanoboot/powerframework/security/hash/locator/HashImpl.java @@ -0,0 +1,42 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.security.hash.locator; + +import lombok.Getter; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public enum HashImpl { + SHA_1("SHA-1"), + SHA_256("SHA-256"); + + HashImpl(String nameIn) { + this.name = nameIn; + } + @Getter + private final String name; + +} diff --git a/power-security/src/main/resources/.gitkeep b/power-security/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-security/src/test/java/org/nanoboot/powerframework/security/.gitkeep b/power-security/src/test/java/org/nanoboot/powerframework/security/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-shark/pom.xml b/power-shark/pom.xml new file mode 100644 index 0000000..4b7471b --- /dev/null +++ b/power-shark/pom.xml @@ -0,0 +1,52 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-shark + jar + + Power Shark + Shark programming language + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + org.projectlombok + ${lombok.version} + lombok + provided + + + + diff --git a/power-shark/src/main/java/module-info.java b/power-shark/src/main/java/module-info.java new file mode 100644 index 0000000..b2f639e --- /dev/null +++ b/power-shark/src/main/java/module-info.java @@ -0,0 +1,33 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +//TODO: collections should have methods returning this + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +module powerframework.shark { + requires powerframework.core; + requires lombok; +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/compiler/ByteCode.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/compiler/ByteCode.java new file mode 100644 index 0000000..c9152cc --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/compiler/ByteCode.java @@ -0,0 +1,33 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.compiler; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class ByteCode { + + private final byte[] byteArray = new byte[1024]; +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/compiler/Compiler.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/compiler/Compiler.java new file mode 100644 index 0000000..effc11c --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/compiler/Compiler.java @@ -0,0 +1,42 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.compiler; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Compiler { + /* + * ByteCode byteCode = Compiler.compile("//some code"); + * + * MoleCode moleCode= new MoleCode(); + * + * Function functionMultiplyAndAddOne= new Function("multiplyAndAddOne", "num", new VariableDeclaration("arg1","num"), new VariableDeclaration("arg2","num")); + * functionMultiplyAndAddOne.addStatement(new Return(new IncrementByOne(new Multiply(arg1,arg2)))); + * moleCode.addStatement(functionMultiplyAndAddOne); + * mole.addFunctionCall("multiplyAndAddOne",4, 6); + * ByteCode byteCode2 = Compiler.compile(moleCode); + */ +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/MoleCode.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/MoleCode.java new file mode 100644 index 0000000..f960d4e --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/MoleCode.java @@ -0,0 +1,31 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class MoleCode { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/expressions/FunctionCall.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/expressions/FunctionCall.java new file mode 100644 index 0000000..8a901ef --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/expressions/FunctionCall.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.expressions; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class FunctionCall { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/keywords/KeyWords.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/keywords/KeyWords.java new file mode 100644 index 0000000..05c471a --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/keywords/KeyWords.java @@ -0,0 +1,169 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.keywords; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public enum KeyWords { + + /** + * + */ + IMPORT("import"), + + /** + * + */ + NUM("num"), + + /** + * + */ + BIGNUM("bignum"), + + /** + * + */ + DEC("dec"), + + /** + * + */ + BIGDEC("bigdec"), + + /** + * + */ + CHAR("char"), + + /** + * + */ + BOOL("bool"), + + /** + * + */ + FUN("fun"), + + /** + * + */ + ENDFUN("endfun"), + + /** + * + */ + STRUCT("struct"), + + /** + * + */ + ENDSTRUCT("endstruct"), + + /** + * + */ + FIN("fin"), + + /** + * + */ + IF("if"), + + /** + * + */ + THEN("then"), + + /** + * + */ + ELSE("else"), + + /** + * + */ + DO("do"), + + /** + * + */ + ENDDO("enddo"), + + /** + * + */ + SWITCH("switch"), + + /** + * + */ + CASE("case"), + + /** + * + */ + DEFAULT("default"), + + /** + * + */ + BREAK("break"), + + /** + * + */ + CONTINUE("continue"), + + /** + * + */ + GOTO("goto"), + + /** + * + */ + LABEL("label"), + + /** + * + */ + RETURN("return"); + private final String value; + + KeyWords(String value) { + this.value = value; + } + + /** + * + * @return + */ + public String getValue() { + return value; + } +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/literals/BigDec.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/literals/BigDec.java new file mode 100644 index 0000000..ba6399d --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/literals/BigDec.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.literals; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class BigDec { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/literals/BigNum.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/literals/BigNum.java new file mode 100644 index 0000000..df9b966 --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/literals/BigNum.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.literals; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class BigNum { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/literals/Bool.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/literals/Bool.java new file mode 100644 index 0000000..26441f6 --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/literals/Bool.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.literals; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Bool { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/literals/Char.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/literals/Char.java new file mode 100644 index 0000000..c120315 --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/literals/Char.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.literals; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Char { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/literals/Dec.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/literals/Dec.java new file mode 100644 index 0000000..952721e --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/literals/Dec.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.literals; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Dec { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/literals/Num.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/literals/Num.java new file mode 100644 index 0000000..b2b29a9 --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/literals/Num.java @@ -0,0 +1,33 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.literals; + +/** + * + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Num { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/literals/Str.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/literals/Str.java new file mode 100644 index 0000000..a83f3aa --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/literals/Str.java @@ -0,0 +1,31 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.literals; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class Str { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/Add.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/Add.java new file mode 100644 index 0000000..66ffd7a --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/Add.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.operators; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Add { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/And.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/And.java new file mode 100644 index 0000000..5b63fef --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/And.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.operators; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class And { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/DecrementByOne.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/DecrementByOne.java new file mode 100644 index 0000000..31f9d91 --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/DecrementByOne.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.operators; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class DecrementByOne { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/Divide.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/Divide.java new file mode 100644 index 0000000..eec8e74 --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/Divide.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.operators; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Divide { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/IncrementByOne.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/IncrementByOne.java new file mode 100644 index 0000000..d20cc9c --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/IncrementByOne.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.operators; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class IncrementByOne { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/Multiply.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/Multiply.java new file mode 100644 index 0000000..9693cb1 --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/Multiply.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.operators; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Multiply { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/Not.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/Not.java new file mode 100644 index 0000000..2385af8 --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/Not.java @@ -0,0 +1,33 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.operators; + +/** + * + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Not { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/Or.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/Or.java new file mode 100644 index 0000000..5ff3a01 --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/operators/Or.java @@ -0,0 +1,31 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.operators; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class Or { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/Break.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/Break.java new file mode 100644 index 0000000..ea689e3 --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/Break.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.statements; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Break { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/Continue.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/Continue.java new file mode 100644 index 0000000..ffb22fa --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/Continue.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.statements; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Continue { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/DoBlock.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/DoBlock.java new file mode 100644 index 0000000..0123a3d --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/DoBlock.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.statements; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class DoBlock { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/Function.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/Function.java new file mode 100644 index 0000000..1f03fd1 --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/Function.java @@ -0,0 +1,37 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.statements; + +import java.util.*; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Function { + + private String returnType; + private String name; + private ArrayList arguments = null; +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/IfBlock.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/IfBlock.java new file mode 100644 index 0000000..19d3975 --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/IfBlock.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.statements; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class IfBlock { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/Import.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/Import.java new file mode 100644 index 0000000..372e2b3 --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/Import.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.statements; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Import { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/Return.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/Return.java new file mode 100644 index 0000000..62bd14d --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/Return.java @@ -0,0 +1,30 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.statements; + +/** + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class Return { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/StatementParser.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/StatementParser.java new file mode 100644 index 0000000..1f7d446 --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/StatementParser.java @@ -0,0 +1,31 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.statements; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class StatementParser { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/Struct.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/Struct.java new file mode 100644 index 0000000..635c057 --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/Struct.java @@ -0,0 +1,31 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.statements; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class Struct { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/SwitchBlock.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/SwitchBlock.java new file mode 100644 index 0000000..9c505c5 --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/SwitchBlock.java @@ -0,0 +1,31 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.statements; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class SwitchBlock { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/VariableAssignment.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/VariableAssignment.java new file mode 100644 index 0000000..758287c --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/VariableAssignment.java @@ -0,0 +1,31 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.statements; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class VariableAssignment { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/VariableDeclaration.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/VariableDeclaration.java new file mode 100644 index 0000000..5bc88f4 --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/VariableDeclaration.java @@ -0,0 +1,33 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.statements; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class VariableDeclaration { + + private String type; + private String name; +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/WhileBlock.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/WhileBlock.java new file mode 100644 index 0000000..eaa8167 --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/statements/WhileBlock.java @@ -0,0 +1,31 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.statements; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class WhileBlock { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/syntax/SharkFunction.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/syntax/SharkFunction.java new file mode 100644 index 0000000..0aac312 --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/syntax/SharkFunction.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.syntax; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class SharkFunction { + private String name; + + private String body; +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/syntax/SharkFunctionArgument.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/syntax/SharkFunctionArgument.java new file mode 100644 index 0000000..54e393c --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/language/syntax/SharkFunctionArgument.java @@ -0,0 +1,34 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.language.syntax; + +import lombok.Data; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +@Data +public class SharkFunctionArgument { + private String name; + private String type; +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/todo.txt b/power-shark/src/main/java/org/nanoboot/powerframework/shark/todo.txt new file mode 100644 index 0000000..db7fb2a --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/todo.txt @@ -0,0 +1 @@ + //num bignum dec bigdec bool str enum list map set queue stack diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/virtualmachine/VirtualMachine.java b/power-shark/src/main/java/org/nanoboot/powerframework/shark/virtualmachine/VirtualMachine.java new file mode 100644 index 0000000..959e004 --- /dev/null +++ b/power-shark/src/main/java/org/nanoboot/powerframework/shark/virtualmachine/VirtualMachine.java @@ -0,0 +1,31 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.shark.virtualmachine; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class VirtualMachine { + +} diff --git a/power-shark/src/main/java/org/nanoboot/powerframework/shark/virtualmachine/instructions/.gitkeep b/power-shark/src/main/java/org/nanoboot/powerframework/shark/virtualmachine/instructions/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-shark/src/main/resources/.gitkeep b/power-shark/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-shark/src/test/java/org/nanoboot/powerframework/shark/.gitkeep b/power-shark/src/test/java/org/nanoboot/powerframework/shark/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-sound/pom.xml b/power-sound/pom.xml new file mode 100644 index 0000000..0820bda --- /dev/null +++ b/power-sound/pom.xml @@ -0,0 +1,58 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-sound + jar + + Power Sound + Sound for the Power library + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + org.nanoboot.powerframework + power-log + ${power.version} + + + + + junit + junit + 4.12 + test + + + diff --git a/power-sound/src/main/java/module-info.java b/power-sound/src/main/java/module-info.java new file mode 100644 index 0000000..3b72ce0 --- /dev/null +++ b/power-sound/src/main/java/module-info.java @@ -0,0 +1,31 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + module powerframework.template { + requires powerframework.core; + requires powerframework.log; + requires powerframework.utils; +} diff --git a/power-sound/src/main/java/org/nanoboot/powerframework/sound/.gitkeep b/power-sound/src/main/java/org/nanoboot/powerframework/sound/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-sound/src/main/resources/.gitkeep b/power-sound/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-sound/src/test/java/org/nanoboot/powerframework/sound/.gitkeep b/power-sound/src/test/java/org/nanoboot/powerframework/sound/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-sql/pom.xml b/power-sql/pom.xml new file mode 100644 index 0000000..528c4f4 --- /dev/null +++ b/power-sql/pom.xml @@ -0,0 +1,64 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-sql + jar + + Power SQL + SQL functionality for the Power library + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + org.nanoboot.powerframework + power-json + ${power.version} + + + + org.projectlombok + lombok + + + + + junit + junit + 4.12 + test + + + + diff --git a/power-sql/src/main/java/module-info.java b/power-sql/src/main/java/module-info.java new file mode 100644 index 0000000..d392fc6 --- /dev/null +++ b/power-sql/src/main/java/module-info.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +module powerframework.sql { + exports org.nanoboot.powerframework.sql.core; + exports org.nanoboot.powerframework.sql.filter; + requires lombok; + requires powerframework.json; +} diff --git a/power-sql/src/main/java/org/nanoboot/powerframework/sql/core/ColumnNameValue.java b/power-sql/src/main/java/org/nanoboot/powerframework/sql/core/ColumnNameValue.java new file mode 100644 index 0000000..de60c80 --- /dev/null +++ b/power-sql/src/main/java/org/nanoboot/powerframework/sql/core/ColumnNameValue.java @@ -0,0 +1,57 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.sql.core; + +import lombok.Getter; +import lombok.Setter; + +/** + * Here goes the description of this class. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class ColumnNameValue { + + /** + * Field description + */ + @Getter + @Setter + private String name; + /** + * Field description + */ + @Getter + @Setter + private String value; + + public ColumnNameValue(String nameIn, String valueIn) { + this.name = nameIn; + this.value = valueIn; + } + + + + public String toString() { + return name + '=' + value; + } +} diff --git a/power-sql/src/main/java/org/nanoboot/powerframework/sql/core/OrderBy.java b/power-sql/src/main/java/org/nanoboot/powerframework/sql/core/OrderBy.java new file mode 100644 index 0000000..8d84c6d --- /dev/null +++ b/power-sql/src/main/java/org/nanoboot/powerframework/sql/core/OrderBy.java @@ -0,0 +1,57 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.sql.core; + +import org.nanoboot.powerframework.json.JsonObject; +import lombok.Getter; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class OrderBy { + @Getter + private final String property; + @Getter + private final OrderByType orderByType; + + public OrderBy(JsonObject jo) { + this.property = jo.getString("property"); + this.orderByType = OrderByType.valueOf(jo.getString("orderByType")); + } + + public OrderBy(String property, OrderByType orderByType) { + this.property = property; + this.orderByType = orderByType; + } + + public OrderBy(String property) { + this(property, OrderByType.DEFAULT); + } + + public JsonObject toJsonObject() { + JsonObject jo = new JsonObject(); + jo.addString("property", property); + jo.addString("orderByType", orderByType.name()); + return jo; + } +} diff --git a/power-sql/src/main/java/org/nanoboot/powerframework/sql/core/OrderByType.java b/power-sql/src/main/java/org/nanoboot/powerframework/sql/core/OrderByType.java new file mode 100644 index 0000000..82aca54 --- /dev/null +++ b/power-sql/src/main/java/org/nanoboot/powerframework/sql/core/OrderByType.java @@ -0,0 +1,31 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.sql.core; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public enum OrderByType { + ASC, DESC; + public static final OrderByType DEFAULT=OrderByType.ASC; +} diff --git a/power-sql/src/main/java/org/nanoboot/powerframework/sql/core/SqlStatementCreator.java b/power-sql/src/main/java/org/nanoboot/powerframework/sql/core/SqlStatementCreator.java new file mode 100644 index 0000000..401af3f --- /dev/null +++ b/power-sql/src/main/java/org/nanoboot/powerframework/sql/core/SqlStatementCreator.java @@ -0,0 +1,130 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.sql.core; + +/** + * Here goes the description of this class. + * + * @author Robert Vokac + * @since 0.0.0 + * + */ +public class SqlStatementCreator { + + /** + * Constant description + */ + private static final String SELECT_ALL_FROM = "SELECT * FROM "; + private static final String SELECT_UUID_FROM = "SELECT UUID FROM "; + private static final String INSERT_INTO_TEMPLATE = "INSERT INTO %s VALUES (%s);"; + private static final String UPDATE_TEMPLATE = "UPDATE %s SET "; + private static final String WHERE = "WHERE"; + + /** + * Field description + */ + private String name; + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private SqlStatementCreator() { + } + + /** + * Setter for name. + * + * @param nameIn + */ + public static String createSelect(String tableName, String conditions) { + String sql = SELECT_ALL_FROM + tableName + (conditions != null ? (" WHERE " + conditions) : ""); + //System.out.println(sql); + return sql; + } + + /** + * Setter for name. + * + * @param nameIn + */ + public static String createSelectUuids(String tableName, String conditions) { + String sql = SELECT_UUID_FROM + tableName + (conditions != null ? (" WHERE " + conditions) : ""); + //System.out.println(sql); + return sql; + } + + /** + * Setter for name. + * + * @param nameIn + */ + public static String createInsert(String tableName, String... valuesIn) { + String valuesAsString; + StringBuilder stringBuilder = new StringBuilder(); + int valuesInMaxIndex = valuesIn.length - 1; + + for (int i = 0; i <= valuesInMaxIndex; i++) { + String e = valuesIn[i]; + stringBuilder.append(e); + if(i < valuesInMaxIndex) { + stringBuilder.append(',').append(' '); + } + + } + valuesAsString = stringBuilder.toString(); + String sql = String.format(INSERT_INTO_TEMPLATE, tableName, valuesAsString); + //System.out.println(sql); + return sql; + } + + /** + * Setter for name. + * + * @param nameIn + */ + public static String createUpdate(String tableName, String conditions, ColumnNameValue... columnNameValues) { + + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append(String.format(UPDATE_TEMPLATE, tableName)); + int columnNameValuesStringMaxIndex = columnNameValues.length - 1; + + for (int i = 0; i <= columnNameValuesStringMaxIndex; i++) { + String e = columnNameValues[i].toString(); + stringBuilder.append(e); + if(i < columnNameValuesStringMaxIndex) { + stringBuilder.append(',').append(' '); + } + + } + if(conditions != null) { + stringBuilder.append(' '); + stringBuilder.append(WHERE); + stringBuilder.append(' '); + stringBuilder.append(conditions); + } + String sql = stringBuilder.toString(); + //System.out.println(sql); + return sql; + } + +} diff --git a/power-sql/src/main/java/org/nanoboot/powerframework/sql/filter/AbstractFilter.java b/power-sql/src/main/java/org/nanoboot/powerframework/sql/filter/AbstractFilter.java new file mode 100755 index 0000000..74cf3d6 --- /dev/null +++ b/power-sql/src/main/java/org/nanoboot/powerframework/sql/filter/AbstractFilter.java @@ -0,0 +1,40 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.sql.filter; + +/** + * AbstractFilter Class. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public abstract class AbstractFilter { + protected String result; + + @Override + public String toString() { + return this.getResult(); + } + + public String getResult() { + return this.result; + } +} diff --git a/power-sql/src/main/java/org/nanoboot/powerframework/sql/filter/SqlConjunction.java b/power-sql/src/main/java/org/nanoboot/powerframework/sql/filter/SqlConjunction.java new file mode 100755 index 0000000..0c27545 --- /dev/null +++ b/power-sql/src/main/java/org/nanoboot/powerframework/sql/filter/SqlConjunction.java @@ -0,0 +1,69 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.sql.filter; + +/** + * SqlConjunction Class. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class SqlConjunction extends AbstractFilter { + + public static final String AND = "AND"; + public static final String OR = "OR"; + + public SqlConjunction(final String conjunction, final Object... object) { + + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append('('); + int operationCount = object.length; + if (operationCount == 0) { + this.result = ""; + return; + } + if (operationCount == 1) { + this.result = object.toString(); + return; + } + int index = 0; + final int maxIndex = object.length - 1; + for (Object o : object) { + stringBuilder.append(o); + + if (index++ != maxIndex) { + stringBuilder.append(' '); + stringBuilder.append(conjunction); + stringBuilder.append(' '); + } + } + stringBuilder.append(')'); + this.result = stringBuilder.toString(); + + } + + public SqlConjunction(final String raw) { + + this.result = raw; + + } + +} diff --git a/power-sql/src/main/java/org/nanoboot/powerframework/sql/filter/SqlFilter.java b/power-sql/src/main/java/org/nanoboot/powerframework/sql/filter/SqlFilter.java new file mode 100755 index 0000000..344d8fd --- /dev/null +++ b/power-sql/src/main/java/org/nanoboot/powerframework/sql/filter/SqlFilter.java @@ -0,0 +1,43 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.sql.filter; + +/** + * SqlFilter Class. + *

+ * Used to generate the WHERE part of a SQL statement. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class SqlFilter extends AbstractFilter { + + public SqlFilter(final SqlConjunction sqlConjunction) { + this.result = sqlConjunction.toString(); + System.out.println("SqlFilter generated WHERE part:\n\t" + this.result); + } + + public SqlFilter(final SqlOperation sqlOperation) { + this.result = sqlOperation.toString(); + System.out.println("SqlFilter generated WHERE part:\n\t" + this.result); + } + +} diff --git a/power-sql/src/main/java/org/nanoboot/powerframework/sql/filter/SqlOperation.java b/power-sql/src/main/java/org/nanoboot/powerframework/sql/filter/SqlOperation.java new file mode 100755 index 0000000..5df54d4 --- /dev/null +++ b/power-sql/src/main/java/org/nanoboot/powerframework/sql/filter/SqlOperation.java @@ -0,0 +1,92 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.sql.filter; + +/** + * SqlOperation Class. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class SqlOperation extends AbstractFilter { + public static final String EQUAL = "="; + public static final String GREATER_OR_EQUAL = ">="; + public static final String GREATER = ">"; + public static final String LESS_OR_EQUAL = "<="; + public static final String LESS = "<"; + + private static final String IN = " IN "; + private static final String NOT_IN = " NOT IN "; + + public static SqlOperation createNotInSqlOperation(final String what, final Object[] where) { + return createInSqlOperation(what, where, true); + } + + public static SqlOperation createInSqlOperation(final String what, final Object[] where) { + return createInSqlOperation(what, where, false); + } + + private static SqlOperation createInSqlOperation(final String what, final Object[] where, final boolean not) { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("("); + stringBuilder.append(what); + stringBuilder.append(not ? NOT_IN : IN); + stringBuilder.append("("); + int index = 0; + int maxIndex = where.length - 1; + for (Object e : where) { + stringBuilder.append(e); + if (index != maxIndex) { + stringBuilder.append(", "); + } + + index++; + } + stringBuilder.append("))"); + SqlOperation sqlOperation = new SqlOperation(); + sqlOperation.result = stringBuilder.toString(); + return sqlOperation; + } + + private SqlOperation() { + + } + + public SqlOperation(final String operation, final Object object1, final Object object2) { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append('('); + stringBuilder.append(object1); + stringBuilder.append(' '); + stringBuilder.append(operation); + stringBuilder.append(' '); + stringBuilder.append(object2); + stringBuilder.append(')'); + this.result = stringBuilder.toString(); + } + + public SqlOperation(final String raw) { + this.result = raw; + } + + public static String quote(final String string) { + return '\'' + string + '\''; + } +} diff --git a/power-sql/src/main/resources/.gitkeep b/power-sql/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-sql/src/test/java/.gitkeep b/power-sql/src/test/java/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-stat/pom.xml b/power-stat/pom.xml new file mode 100644 index 0000000..8c05969 --- /dev/null +++ b/power-stat/pom.xml @@ -0,0 +1,58 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-stat + jar + + Power Stat + Stat for the Power library + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + org.nanoboot.powerframework + power-log + ${power.version} + + + + + junit + junit + 4.12 + test + + + diff --git a/power-stat/src/main/java/module-info.java b/power-stat/src/main/java/module-info.java new file mode 100644 index 0000000..3001755 --- /dev/null +++ b/power-stat/src/main/java/module-info.java @@ -0,0 +1,31 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * @author Robert Vokac + * @since 0.0.0 + */ + +module powerframework.template { + requires powerframework.core; + requires powerframework.log; + requires powerframework.utils; +} diff --git a/power-stat/src/main/java/org/nanoboot/powerframework/stat/.gitkeep b/power-stat/src/main/java/org/nanoboot/powerframework/stat/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-stat/src/main/resources/.gitkeep b/power-stat/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-stat/src/test/java/org/nanoboot/powerframework/stat/.gitkeep b/power-stat/src/test/java/org/nanoboot/powerframework/stat/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-svg/pom.xml b/power-svg/pom.xml new file mode 100644 index 0000000..3035f65 --- /dev/null +++ b/power-svg/pom.xml @@ -0,0 +1,58 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-svg + jar + + Power SVG + SVG for the Power library + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + org.nanoboot.powerframework + power-log + ${power.version} + + + + + junit + junit + 4.12 + test + + + diff --git a/power-svg/src/main/java/module-info.java b/power-svg/src/main/java/module-info.java new file mode 100644 index 0000000..f99825e --- /dev/null +++ b/power-svg/src/main/java/module-info.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +module powerframework.template { + requires powerframework.core; + requires powerframework.log; + requires powerframework.utils; +} diff --git a/power-svg/src/main/java/org/nanoboot/powerframework/svg/.gitkeep b/power-svg/src/main/java/org/nanoboot/powerframework/svg/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-svg/src/main/resources/.gitkeep b/power-svg/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-svg/src/test/java/org/nanoboot/powerframework/svg/.gitkeep b/power-svg/src/test/java/org/nanoboot/powerframework/svg/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-template/.gitkeep b/power-template/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-template/pom.xml b/power-template/pom.xml new file mode 100644 index 0000000..2e1b6f2 --- /dev/null +++ b/power-template/pom.xml @@ -0,0 +1,58 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-template + jar + + Power Template + Template for the Power library + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + org.nanoboot.powerframework + power-log + ${power.version} + + + + + junit + junit + 4.12 + test + + + diff --git a/power-template/src/main/java/module-info.java b/power-template/src/main/java/module-info.java new file mode 100644 index 0000000..f99825e --- /dev/null +++ b/power-template/src/main/java/module-info.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +module powerframework.template { + requires powerframework.core; + requires powerframework.log; + requires powerframework.utils; +} diff --git a/power-template/src/main/java/org/nanoboot/powerframework/template/.gitkeep b/power-template/src/main/java/org/nanoboot/powerframework/template/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-template/src/main/resources/.gitkeep b/power-template/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-template/src/test/java/org/nanoboot/powerframework/template/.gitkeep b/power-template/src/test/java/org/nanoboot/powerframework/template/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-text/pom.xml b/power-text/pom.xml new file mode 100644 index 0000000..8317b5c --- /dev/null +++ b/power-text/pom.xml @@ -0,0 +1,54 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-text + jar + + Power Text + Text functionality for the Power library + + + false + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + + org.projectlombok + lombok + + + + diff --git a/power-text/src/main/java/module-info.java b/power-text/src/main/java/module-info.java new file mode 100644 index 0000000..4d52fc9 --- /dev/null +++ b/power-text/src/main/java/module-info.java @@ -0,0 +1,31 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +module powerframework.text { + exports org.nanoboot.powerframework.text; + requires powerframework.core; + requires lombok; +} diff --git a/power-text/src/main/java/org/nanoboot/powerframework/text/AsciiCharacter.java b/power-text/src/main/java/org/nanoboot/powerframework/text/AsciiCharacter.java new file mode 100644 index 0000000..ba35461 --- /dev/null +++ b/power-text/src/main/java/org/nanoboot/powerframework/text/AsciiCharacter.java @@ -0,0 +1,623 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.text; + +import lombok.Getter; + +/** + * Enumeration for Ascii characters. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public enum AsciiCharacter { + /** + * Constant for ascii character constant ' '. + */ + SPACE(32, "space", CharacterType.OTHER_NOT_PRINTABLE), + /** + * Constant for ascii character constant '!'. + */ + EXCLAMATION_MARK(33, "exclamation mark", CharacterType.OTHER_PRINTABLE, + '?'), + /** + * Constant for ascii character constant '"'. + */ + QUOTATION_MARK(34, "quotation mark", + CharacterType.OTHER_PRINTABLE, + '\''), + /** + * Constant for ascii character constant '#'. + */ + NUMBER_SIGN(35, "number sign", CharacterType.OTHER_PRINTABLE), + /** + * Constant for ascii character constant '$'. + */ + DOLLAR_SIGN(36, "dollar sign", CharacterType.OTHER_PRINTABLE), + /** + * Constant for ascii character constant '%'. + */ + PERCENT_SIGN(37, "percent sign", CharacterType.OTHER_PRINTABLE), + /** + * Constant for ascii character constant '&'. + */ + AMPERSAND(38, "ampersand", CharacterType.OTHER_PRINTABLE), + /** + * Constant for ascii character constant '''. + */ + APOSTROPHE(39, "apostrophe", CharacterType.OTHER_PRINTABLE, + '"'), + /** + * Constant for ascii character constant '('. + */ + ROUND_BRACKET_START(40, "round bracket start", + CharacterType.OTHER_PRINTABLE, + ')'), + /** + * Constant for ascii character constant ')'. + */ + ROUND_BRACKET_END(41, "round bracket end", + CharacterType.OTHER_PRINTABLE, + '('), + /** + * Constant for ascii character constant '*'. + */ + ASTERISK(42, "asterisk", + CharacterType.OTHER_PRINTABLE), + /** + * Constant for ascii character constant '+'. + */ + PLUS_SIGN(43, "plus sign", + CharacterType.OTHER_PRINTABLE, + '-'), + /** + * Constant for ascii character constant ','. + */ + COMMA(44, "comma", + CharacterType.OTHER_PRINTABLE, + '.'), + /** + * Constant for ascii character constant '-'. + */ + MINUS_SIGN(45, "minus sign", + CharacterType.OTHER_PRINTABLE, + '+'), + /** + * Constant for ascii character constant '.'. + */ + FULL_STOP(46, "full stop", + CharacterType.OTHER_PRINTABLE, + ','), + /** + * Constant for ascii character constant '/'. + */ + SLASH(47, "slash", + CharacterType.OTHER_PRINTABLE, + '\\'), + /** + * Constant for ascii character constant '0'. + */ + ZERO(48, "zero", + CharacterType.NUMBER), + /** + * Constant for ascii character constant '1'. + */ + ONE(49, "one", + CharacterType.NUMBER), + /** + * Constant for ascii character constant '2'. + */ + TWO(50, "two", + CharacterType.NUMBER), + /** + * Constant for ascii character constant '3'. + */ + THREE(51, "three", + CharacterType.NUMBER), + /** + * Constant for ascii character constant '4'. + */ + FOUR(52, "four", + CharacterType.NUMBER), + /** + * Constant for ascii character constant '5'. + */ + FIVE(53, "five", + CharacterType.NUMBER), + /** + * Constant for ascii character constant '6'. + */ + SIX(54, "six", + CharacterType.NUMBER), + /** + * Constant for ascii character constant '7'. + */ + SEVEN(55, "seven", + CharacterType.NUMBER), + /** + * Constant for ascii character constant '8'. + */ + EIGHT(56, "eight", + CharacterType.NUMBER), + /** + * Constant for ascii character constant '9'. + */ + NINE(57, "nine", + CharacterType.NUMBER), + /** + * Constant for ascii character constant ':'. + */ + COLON(58, "colon", + CharacterType.OTHER_PRINTABLE, + ';'), + /** + * Constant for ascii character constant ';'. + */ + SEMICOLON(59, "semicolon", + CharacterType.OTHER_PRINTABLE, + ':'), + /** + * Constant for ascii character constant '<'. + */ + LESS_THAN_SIGN(60, "less than sign", + CharacterType.OTHER_PRINTABLE, + '>'), + /** + * Constant for ascii character constant '='. + */ + EQUALS_SIGN(61, "equals sign", + CharacterType.OTHER_PRINTABLE), + /** + * Constant for ascii character constant '>'. + */ + GREATER_THAN_SIGN(62, "greater than sign", + CharacterType.OTHER_PRINTABLE, + '<'), + /** + * Constant for ascii character constant '?'. + */ + QUESTION_MARK(63, "question mark", + CharacterType.OTHER_PRINTABLE, + '!'), + /** + * Constant for ascii character constant '@'. + */ + AT_SIGN(64, "at sign", + CharacterType.OTHER_PRINTABLE), + /** + * Constant for ascii character constant 'A'. + */ + A_UPPER(65, "a upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'B'. + */ + B_UPPER(66, "b upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'C'. + */ + C_UPPER(67, "c upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'D'. + */ + D_UPPER(68, "d upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'E'. + */ + E_UPPER(69, "e upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'F'. + */ + F_UPPER(70, "f upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'G'. + */ + G_UPPER(71, "g upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'H'. + */ + H_UPPER(72, "h upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'I'. + */ + I_UPPER(73, "i upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'J'. + */ + J_UPPER(74, "j upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'K'. + */ + K_UPPER(75, "k upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'L'. + */ + L_UPPER(76, "l upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'M'. + */ + M_UPPER(77, "m upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'N'. + */ + N_UPPER(78, "n upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'O'. + */ + O_UPPER(79, "o upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'P'. + */ + P_UPPER(80, "p upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'Q'. + */ + Q_UPPER(81, "q upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'R'. + */ + R_UPPER(82, "r upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'S'. + */ + S_UPPER(83, "s upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'T'. + */ + T_UPPER(84, "t upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'U'. + */ + U_UPPER(85, "u upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'V'. + */ + V_UPPER(86, "v upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'W'. + */ + W_UPPER(87, "w upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'X'. + */ + X_UPPER(88, "x upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'Y'. + */ + Y_UPPER(89, "y upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant 'Z'. + */ + Z_UPPER(90, "z upper", + CharacterType.UPPER_LETTER), + /** + * Constant for ascii character constant '['. + */ + SQUARE_BRACKET_START(91, + "square bracket start", + CharacterType.OTHER_PRINTABLE, + ']'), + /** + * Constant for ascii character constant '\'. + */ + BACKSLASH(92, "backslash", + CharacterType.OTHER_PRINTABLE, + '/'), + /** + * Constant for ascii character constant ']'. + */ + SQUARE_BRACKET_END(93, "square bracket end", + CharacterType.OTHER_PRINTABLE, + '['), + /** + * Constant for ascii character constant '^'. + */ + CARET(94, "caret", + CharacterType.OTHER_PRINTABLE), + /** + * Constant for ascii character constant '_'. + */ + UNDERSCORE(95, "underscore", + CharacterType.OTHER_PRINTABLE, + '|'), + /** + * Constant for ascii character constant '`'. + */ + GRAVE_ACCENT(96, "grave accent", + CharacterType.OTHER_PRINTABLE), + /** + * Constant for ascii character constant 'a'. + */ + A_LOWER(97, "a lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'b'. + */ + B_LOWER(98, "b lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'c'. + */ + C_LOWER(99, "c lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'd'. + */ + D_LOWER(100, "d lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'e'. + */ + E_LOWER(101, "e lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'f'. + */ + F_LOWER(102, "f lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'g'. + */ + G_LOWER(103, "g lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'h'. + */ + H_LOWER(104, "h lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'i'. + */ + I_LOWER(105, "i lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'j'. + */ + J_LOWER(106, "j lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'k'. + */ + K_LOWER(107, "k lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'l'. + */ + L_LOWER(108, "l lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'm'. + */ + M_LOWER(109, "m lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'n'. + */ + N_LOWER(110, "n lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'o'. + */ + O_LOWER(111, "o lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'p'. + */ + P_LOWER(112, "p lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'q'. + */ + Q_LOWER(113, "q lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'r'. + */ + R_LOWER(114, "r lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 's'. + */ + S_LOWER(115, "s lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 't'. + */ + T_LOWER(116, "t lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'u'. + */ + U_LOWER(117, "u lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'v'. + */ + V_LOWER(118, "v lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'w'. + */ + W_LOWER(119, "w lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'x'. + */ + X_LOWER(120, "x lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'y'. + */ + Y_LOWER(121, "y lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant 'z'. + */ + Z_LOWER(122, "z lower", + CharacterType.LOWER_LETTER), + /** + * Constant for ascii character constant '{'. + */ + CURLY_BRACKET_START(123, + "curly bracket start", + CharacterType.OTHER_PRINTABLE, + '}'), + /** + * Constant for ascii character constant '|'. + */ + VERTICAL_BAR(124, "vertical bar", + CharacterType.OTHER_PRINTABLE, + '_'), + /** + * Constant for ascii character constant '}'. + */ + CURLY_BRACKET_END(125, "curly bracket end", + CharacterType.OTHER_PRINTABLE, + '{'); + /** + * The position of the character. + */ + @Getter + private final int asciiPosition; + + /** + * The character. + */ + @Getter + private final Character character; + /** + * Description of the character. + */ + @Getter + private final String description; + + /** + * Character type. + */ + @Getter + private final CharacterType characterType; + + /** + * Opposite character. + */ + @Getter + private final Character oppositeCharacter; + + /** + * Constructor. + * + * @param asciiPositionIn position in ascii + * @param descriptionIn description of the character + * @param characterTypeIn character type + * asciiCharacter + * @param oppositeCharIn opposite ascii character + */ + AsciiCharacter(final int asciiPositionIn, final String descriptionIn, + final CharacterType characterTypeIn, + final Character oppositeCharIn) { + this.asciiPosition = asciiPositionIn; + this.description = descriptionIn; + this.character = (char) asciiPositionIn; + this.characterType = characterTypeIn; + + if (oppositeCharIn == null) { + if (this.characterType == CharacterType.UPPER_LETTER) { + this.oppositeCharacter = Character.toLowerCase(character); + } else if (this.characterType == CharacterType.LOWER_LETTER) { + this.oppositeCharacter = Character.toUpperCase(character); + } else { + this.oppositeCharacter = null; + } + } else { + this.oppositeCharacter = oppositeCharIn; + } + } + + /** + * Constructor. + * + * @param asciiPositionIn position in ascii + * @param descriptionIn name of the character + * @param characterTypeIn character type + * asciiCharacter + */ + AsciiCharacter(final int asciiPositionIn, final String descriptionIn, + final CharacterType characterTypeIn) { + this(asciiPositionIn, descriptionIn, characterTypeIn, null); + } + + /** + * Returns character. + * + * @return character + */ + public char toChar() { + return getCharacter(); + } + /** + * Returns string. + * + * @return string + */ + public String asString() { + return String.valueOf(toChar()); + } + + /** + * Returns AsciiCharacter based on the ch parameter, if possible, + * otherwise returns null. + * + * @param ch input character + * @return AsciiCharacter, if possible, otherwise null + */ + public static AsciiCharacter ofCharacter(final char ch) { + for (AsciiCharacter ac : AsciiCharacter.values()) { + if (ac.getCharacter() == ch) { + return ac; + } + } + return null; + } +} diff --git a/power-text/src/main/java/org/nanoboot/powerframework/text/CharacterRange.java b/power-text/src/main/java/org/nanoboot/powerframework/text/CharacterRange.java new file mode 100644 index 0000000..bdca8c5 --- /dev/null +++ b/power-text/src/main/java/org/nanoboot/powerframework/text/CharacterRange.java @@ -0,0 +1,186 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.text; + +import lombok.Getter; + +import java.util.Arrays; + +/** + * Representing ascii characters of a type. + * + * @author Robert Vokac + * @since 0.0.0 + */ +@Getter +public final class CharacterRange { + /** + * Ascii starting position for number characters. + */ + private static final int NUMERIC_CHARS_FROM = 48; + /** + * Ascii ending position for number characters. + */ + private static final int NUMERIC_CHARS_TO = 57; + /** + * Ascii starting position for lower letter characters. + */ + private static final int LOWER_LETTERS_CHARS_FROM = 97; + /** + * Ascii ending position for lower letter characters. + */ + private static final int LOWER_LETTERS_CHARS_TO = 122; + /** + * Ascii starting position for upper letter characters. + */ + private static final int UPPER_LETTERS_CHARS_FROM = 65; + /** + * Ascii ending position for upper letter characters. + */ + private static final int UPPER_LETTERS_CHARS_TO = 90; + /** + * Ascii starting position for printable characters. + */ + private static final int PRINTABLE_ASCII_CHARS_FROM = 33; + /** + * Ascii ending position for printable characters. + */ + private static final int PRINTABLE_ASCII_CHARS_TO = 126; + + /** + * Range for numbers. + */ + public static final CharacterRange NUMBERS; + /** + * Range for lower letters. + */ + public static final CharacterRange LOWER_LETTERS; + /** + * Range for upper letters. + */ + public static final CharacterRange UPPER_LETTERS; + /** + * Range for printable characters. + */ + public static final CharacterRange PRINTABLE_CHARACTERS_LETTERS; + + /** + * Character type. + */ + private final CharacterType type; + + /** + * Ascii starting position. + */ + private final int asciiFrom; + + /** + * Ascii ending position. + */ + private final int asciiTo; + + /** + * Char array of the character of this type. + */ + private final char[] array; + + static { + NUMBERS = new CharacterRange( + CharacterType.NUMBER, NUMERIC_CHARS_FROM, NUMERIC_CHARS_TO + ); + LOWER_LETTERS = new CharacterRange( + CharacterType.LOWER_LETTER, + LOWER_LETTERS_CHARS_FROM, LOWER_LETTERS_CHARS_TO + ); + UPPER_LETTERS = new CharacterRange( + CharacterType.UPPER_LETTER, + UPPER_LETTERS_CHARS_FROM, UPPER_LETTERS_CHARS_TO + ); + PRINTABLE_CHARACTERS_LETTERS = new CharacterRange( + CharacterType.OTHER_PRINTABLE, + PRINTABLE_ASCII_CHARS_FROM, PRINTABLE_ASCII_CHARS_TO + ); + } + + /** + * Returns instance of CharacterRange + * based on the given type. + * + * @param type type of the character range to return + * Note: printable characters + * are not supported. + * @return CharacterRange instance + */ + public static CharacterRange getInstance( + final CharacterType type) { + switch (type) { + case NUMBER: return NUMBERS; + case LOWER_LETTER: return LOWER_LETTERS; + case UPPER_LETTER: return UPPER_LETTERS; + case OTHER_PRINTABLE: return PRINTABLE_CHARACTERS_LETTERS; + default: + String msg = "Type " + type + " is not supported."; + throw new TextException(msg); + } + } + + /** + * Constructor. + * @param characterType type of the character range to return + * * Note: printable characters + * * are not supported. + * @param asciiFromParam starting position + * @param asciiToParam ending position + */ + private CharacterRange(final CharacterType characterType, + final int asciiFromParam, final int asciiToParam) { + boolean numbersAreInRange = asciiFromParam <= asciiToParam; + if (!numbersAreInRange) { + String msg = "asciiFromParam must be less or equal to asciiToParam"; + throw new TextException(msg); + } + this.type = characterType; + this.asciiFrom = asciiFromParam; + this.asciiTo = asciiToParam; + this.array = new char[this.size()]; + int index = 0; + for (int i = asciiFrom; i <= asciiTo; i++) { + char ch = (char) i; + array[index++] = ch; + } + } + + /** + * Returns size of the range. + * @return size of the characters in the range + */ + public int size() { + return asciiTo - asciiFrom + 1; + } + + /** + * Returns the character array. + * @return array + */ + public char[] getArray() { + return Arrays.copyOf(this.array, this.array.length); + } +} diff --git a/power-text/src/main/java/org/nanoboot/powerframework/text/CharacterType.java b/power-text/src/main/java/org/nanoboot/powerframework/text/CharacterType.java new file mode 100644 index 0000000..a0d057c --- /dev/null +++ b/power-text/src/main/java/org/nanoboot/powerframework/text/CharacterType.java @@ -0,0 +1,54 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.text; + +/** + * Enumeration for character types. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public enum CharacterType { + /** + * 0-9. + */ + NUMBER, + + /** + * a-z. + */ + LOWER_LETTER, + + /** + * A-Z. + */ + UPPER_LETTER, + + /** + * For example: !@#$%^&*()~?. + */ + OTHER_PRINTABLE, + + /** + * For example: spaces, tabs. + */ + OTHER_NOT_PRINTABLE; +} diff --git a/power-text/src/main/java/org/nanoboot/powerframework/text/TextException.java b/power-text/src/main/java/org/nanoboot/powerframework/text/TextException.java new file mode 100644 index 0000000..732eebb --- /dev/null +++ b/power-text/src/main/java/org/nanoboot/powerframework/text/TextException.java @@ -0,0 +1,44 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.text; + +import org.nanoboot.powerframework.core.PowerException; + +/** + * Exception happening in case, something in random packages failed. + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class TextException extends PowerException { + + /** + * Constructor with message. + * + * @param message message describing the reason, + * why this exception was thrown. + */ + public TextException(final String message) { + super(message); + } + +} diff --git a/power-text/src/main/java/org/nanoboot/powerframework/text/package-info.java b/power-text/src/main/java/org/nanoboot/powerframework/text/package-info.java new file mode 100644 index 0000000..819de4e --- /dev/null +++ b/power-text/src/main/java/org/nanoboot/powerframework/text/package-info.java @@ -0,0 +1,27 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * Classes used to operate with texts. + * + * @author Robert Vokac + * @since 0.0.0 + */ +package org.nanoboot.powerframework.text; diff --git a/power-text/src/main/resources/.gitkeep b/power-text/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-text/src/test/java/org/nanoboot/powerframework/text/.gitkeep b/power-text/src/test/java/org/nanoboot/powerframework/text/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-text/src/test/java/org/nanoboot/powerframework/text/AsciiCharacterTest.java b/power-text/src/test/java/org/nanoboot/powerframework/text/AsciiCharacterTest.java new file mode 100644 index 0000000..9f30a22 --- /dev/null +++ b/power-text/src/test/java/org/nanoboot/powerframework/text/AsciiCharacterTest.java @@ -0,0 +1,103 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.text; + +import org.junit.Test; + +import static org.junit.Assert.*; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class AsciiCharacterTest { + + @Test + public void toChar() { + for (AsciiCharacter e : AsciiCharacter.values()) { + char ch = e.toChar(); + AsciiCharacter ac = AsciiCharacter.ofCharacter(ch); + assertEquals(ch, ac.toChar()); + } + } + + @Test + public void ofCharacter() { + assertEquals(AsciiCharacter.CARET, AsciiCharacter.ofCharacter('^')); + assertEquals(null, AsciiCharacter.ofCharacter('‣')); + } + + @Test + public void getAsciiPosition() { + int position = 100; + char ch = (char) position; + assertEquals(position, AsciiCharacter.ofCharacter(ch).getAsciiPosition()); + } + + @Test + public void getCharacter() { + char ch = '3'; + AsciiCharacter ac = AsciiCharacter.ofCharacter(ch); + assertEquals(ch, ac.toChar()); + } + + @Test + public void getDescription() { + for (AsciiCharacter e : AsciiCharacter.values()) { + assertNotNull(e.getDescription()); + assertFalse(e.getDescription().isEmpty()); + } + } + + @Test + public void getCharacterType() { + assertEquals(CharacterType.NUMBER, AsciiCharacter.ofCharacter('5').getCharacterType()); + assertEquals(CharacterType.LOWER_LETTER, AsciiCharacter.ofCharacter('g').getCharacterType()); + assertEquals(CharacterType.UPPER_LETTER, AsciiCharacter.ofCharacter('M').getCharacterType()); + assertEquals(CharacterType.OTHER_NOT_PRINTABLE, AsciiCharacter.ofCharacter(' ').getCharacterType()); + assertEquals(CharacterType.OTHER_PRINTABLE, AsciiCharacter.ofCharacter('*').getCharacterType()); + } + + @Test + public void getOppositeCharacter() { + for (AsciiCharacter ac : AsciiCharacter.values()) { + if (ac.getOppositeCharacter() != null) { + Character character = ac.getCharacter(); + Character oppositeCharacter = ac.getOppositeCharacter(); + Character expected = character; + Character returned = AsciiCharacter.ofCharacter(oppositeCharacter).getOppositeCharacter(); + assertEquals(expected, returned); + } + } + assertEquals(AsciiCharacter.ROUND_BRACKET_START.getCharacter(), + AsciiCharacter.ROUND_BRACKET_END.getOppositeCharacter()); + } + + @Test + public void asString() { + String expected = "3"; + AsciiCharacter ac = AsciiCharacter.ofCharacter('3'); + assertEquals(expected, ac.asString()); + } + +} diff --git a/power-text/src/test/java/org/nanoboot/powerframework/text/CharacterRangeTest.java b/power-text/src/test/java/org/nanoboot/powerframework/text/CharacterRangeTest.java new file mode 100644 index 0000000..b214d57 --- /dev/null +++ b/power-text/src/test/java/org/nanoboot/powerframework/text/CharacterRangeTest.java @@ -0,0 +1,150 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.text; + +import org.junit.Test; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; + +import static org.junit.Assert.*; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class CharacterRangeTest { + + @Test(expected = AssertionError.class) + public void constructor() { + Constructor constructor= (Constructor) CharacterRange.class.getDeclaredConstructors()[0]; + constructor.setAccessible(true); + try { + CharacterRange obj = constructor.newInstance(CharacterType.OTHER_PRINTABLE, 10, 5); + } catch (InstantiationException e) { + e.printStackTrace(); + throw new AssertionError("UnexpectedException: " + e); + } catch (IllegalAccessException e) { + e.printStackTrace(); + throw new AssertionError("UnexpectedException: " + e); + } catch (InvocationTargetException e) { + e.printStackTrace(); + throw new AssertionError("UnexpectedException: " + e); + } + } + + @Test + public void constructor2() { + Constructor constructor= (Constructor) CharacterRange.class.getDeclaredConstructors()[0]; + constructor.setAccessible(true); + try { + CharacterRange obj = constructor.newInstance(CharacterType.OTHER_PRINTABLE, 10, 15); + } catch (InstantiationException e) { + e.printStackTrace(); + throw new AssertionError("UnexpectedException: " + e); + } catch (IllegalAccessException e) { + e.printStackTrace(); + throw new AssertionError("UnexpectedException: " + e); + } catch (InvocationTargetException e) { + e.printStackTrace(); + throw new AssertionError("UnexpectedException: " + e); + } + assertTrue("passed", true); + } + @Test + public void getInstance() { + assertEquals(CharacterRange.NUMBERS, + CharacterRange.getInstance(CharacterType.NUMBER)); + assertEquals(CharacterRange.LOWER_LETTERS, + CharacterRange.getInstance(CharacterType.LOWER_LETTER)); + assertEquals(CharacterRange.UPPER_LETTERS, + CharacterRange.getInstance(CharacterType.UPPER_LETTER)); + assertEquals(CharacterRange.PRINTABLE_CHARACTERS_LETTERS, + CharacterRange.getInstance(CharacterType.OTHER_PRINTABLE)); + + try { + CharacterRange.getInstance(CharacterType.OTHER_NOT_PRINTABLE); + String msg = + "Exception TextException expected, because the following type is not supported: " + + CharacterType.OTHER_NOT_PRINTABLE; + throw new AssertionError(msg); + } catch (TextException e) { + //passed + } + } + + @Test + public void size() { + int expected = CharacterRange.NUMBERS.getAsciiTo() - CharacterRange.NUMBERS.getAsciiFrom() + 1; + int returned = CharacterRange.NUMBERS.size(); + assertEquals(expected, returned); + } + + @Test + public void getArray_numbers() { + char[] expected = new char[] {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; + char[] returned = CharacterRange.NUMBERS.getArray(); + + assertArrayEquals(expected, returned); + } + @Test + public void getArray_lowerLetters() { + char[] expected = new char[] {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; + char[] returned = CharacterRange.UPPER_LETTERS.getArray(); + + assertArrayEquals(expected, returned); + } + @Test + public void getArray_upperLetters() { + char[] expected = new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; + char[] returned = CharacterRange.LOWER_LETTERS.getArray(); + + assertArrayEquals(expected, returned); + } + @Test + public void getArray_printableCharacters() { + char[] expected = new char[] {'!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~'}; + char[] returned = CharacterRange.PRINTABLE_CHARACTERS_LETTERS.getArray(); + + assertArrayEquals(expected, returned); + } + + @Test + public void getType() { + assertEquals(CharacterType.NUMBER, CharacterRange.NUMBERS.getType()); + assertEquals(CharacterType.LOWER_LETTER, CharacterRange.LOWER_LETTERS.getType()); + assertEquals(CharacterType.UPPER_LETTER, CharacterRange.UPPER_LETTERS.getType()); + assertEquals(CharacterType.OTHER_PRINTABLE, CharacterRange.PRINTABLE_CHARACTERS_LETTERS.getType()); + } + + @Test + public void getAsciiFrom() { + assertEquals(48, CharacterRange.NUMBERS.getAsciiFrom()); + } + + @Test + public void getAsciiTo() { + assertEquals(57, CharacterRange.NUMBERS.getAsciiTo()); + } + +} diff --git a/power-text/src/test/java/org/nanoboot/powerframework/text/TextExceptionTest.java b/power-text/src/test/java/org/nanoboot/powerframework/text/TextExceptionTest.java new file mode 100644 index 0000000..407b2e7 --- /dev/null +++ b/power-text/src/test/java/org/nanoboot/powerframework/text/TextExceptionTest.java @@ -0,0 +1,39 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.text; + +import org.junit.Test; + +import static org.junit.Assert.*; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class TextExceptionTest { + + @Test + public void constructor_String() { + assertEquals("An error", new TextException("An error").getMessage()); + } + +} diff --git a/power-time/pom.xml b/power-time/pom.xml new file mode 100644 index 0000000..b652c73 --- /dev/null +++ b/power-time/pom.xml @@ -0,0 +1,84 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-time + jar + + Power Time + Time functionality for the Power library + + + true + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + ${checkstyle.skip} + + + + + + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + org.nanoboot.powerframework + power-random + ${power.version} + + + org.nanoboot.powerframework + power-utils + ${power.version} + + + + + org.projectlombok + lombok + + + junit + junit + 4.12 + test + + + + diff --git a/power-time/src/main/java/module-info.java b/power-time/src/main/java/module-info.java new file mode 100644 index 0000000..1bcaa4d --- /dev/null +++ b/power-time/src/main/java/module-info.java @@ -0,0 +1,35 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +module powerframework.time { + exports org.nanoboot.powerframework.time.duration; + exports org.nanoboot.powerframework.time.moment; + exports org.nanoboot.powerframework.time.utils; + requires powerframework.random; + requires powerframework.utils; + requires powerframework.core; + requires lombok; +} diff --git a/power-time/src/main/java/org/nanoboot/powerframework/time/SimpleDateTimeFormatByTimeZone.java b/power-time/src/main/java/org/nanoboot/powerframework/time/SimpleDateTimeFormatByTimeZone.java new file mode 100644 index 0000000..243490d --- /dev/null +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/SimpleDateTimeFormatByTimeZone.java @@ -0,0 +1,43 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.time; + +import java.text.*; +import org.nanoboot.powerframework.time.moment.TimeZone; + +/** + * + * @author Robert Vokac + * @since 0.0.0 + */ +class SimpleDateTimeFormatByTimeZone extends SimpleDateFormat { + + /** + * + * @param timeZone + * @param formatText + */ + SimpleDateTimeFormatByTimeZone(TimeZone timeZone, + String formatText) { + super(formatText); + setTimeZone(java.util.TimeZone.getTimeZone(timeZone.toString())); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/datetime/TimeSource.java b/power-time/src/main/java/org/nanoboot/powerframework/time/TimeSource.java similarity index 68% rename from src/main/java/org/nanoboot/powerframework/datetime/TimeSource.java rename to power-time/src/main/java/org/nanoboot/powerframework/time/TimeSource.java index 9992e1c..22e0317 100644 --- a/src/main/java/org/nanoboot/powerframework/datetime/TimeSource.java +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/TimeSource.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,28 +18,40 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.datetime; +package org.nanoboot.powerframework.time; -import java.text.DateFormat; -import java.util.Calendar; -import java.util.Date; +import java.text.*; +import java.util.*; +import org.nanoboot.powerframework.time.moment.UniversalDateTime; +import org.nanoboot.powerframework.time.moment.TimeZone; /** * Is used to get current universal date and time. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * + * @author Robert Vokac + * @since 0.0.0 */ -class TimeSource { +public class TimeSource { - private static final org.nanoboot.powerframework.datetime.TimeZone universalTimeZone = new org.nanoboot.powerframework.datetime.TimeZone("GMT"); + private static final TimeZone universalTimeZone = new TimeZone("GMT"); - private static final DateFormat yearFormat = new DateTime.SimpleDateTimeFormatByTimeZone(universalTimeZone, "yyyy"); - private static final DateFormat monthFormat = new DateTime.SimpleDateTimeFormatByTimeZone(universalTimeZone, "MM"); - private static final DateFormat dayFormat = new DateTime.SimpleDateTimeFormatByTimeZone(universalTimeZone, "dd"); - private static final DateFormat hourFormat = new DateTime.SimpleDateTimeFormatByTimeZone(universalTimeZone, "HH"); - private static final DateFormat minuteFormat = new DateTime.SimpleDateTimeFormatByTimeZone(universalTimeZone, "mm"); - private static final DateFormat secondFormat = new DateTime.SimpleDateTimeFormatByTimeZone(universalTimeZone, "ss"); - private static final DateFormat millisecondFormat = new DateTime.SimpleDateTimeFormatByTimeZone(universalTimeZone, "S"); + private static final DateFormat yearFormat = new SimpleDateTimeFormatByTimeZone(universalTimeZone, "yyyy"); + private static final DateFormat monthFormat = new SimpleDateTimeFormatByTimeZone(universalTimeZone, "MM"); + private static final DateFormat dayFormat = new SimpleDateTimeFormatByTimeZone(universalTimeZone, "dd"); + private static final DateFormat hourFormat = new SimpleDateTimeFormatByTimeZone(universalTimeZone, "HH"); + private static final DateFormat minuteFormat = new SimpleDateTimeFormatByTimeZone(universalTimeZone, "mm"); + private static final DateFormat secondFormat = new SimpleDateTimeFormatByTimeZone(universalTimeZone, "ss"); + private static final DateFormat millisecondFormat = new SimpleDateTimeFormatByTimeZone(universalTimeZone, "S"); + + /** + * + * @return current universal date time + */ + public static UniversalDateTime getCurrentUniversalDateTimeInstance() { + TimeSource timeSource = new TimeSource(); + return timeSource.getCurrentUniversalDateTime(); + } /** * Represents source for current universal date time. @@ -57,15 +69,6 @@ class TimeSource { this.universalDateTime = this.buildCurrentUniversalDateTime(); } - /** - * - * @return current universal date time - */ - public static UniversalDateTime getCurrentUniversalDateTimeInstance() { - TimeSource timeSource = new TimeSource(); - return timeSource.getCurrentUniversalDateTime(); - } - /** * * @return Date instance for current universal date and time @@ -98,7 +101,7 @@ class TimeSource { * * @return current universal date time */ - UniversalDateTime getCurrentUniversalDateTime() { + private UniversalDateTime getCurrentUniversalDateTime() { return this.universalDateTime; } } diff --git a/power-time/src/main/java/org/nanoboot/powerframework/time/duration/Duration.java b/power-time/src/main/java/org/nanoboot/powerframework/time/duration/Duration.java new file mode 100644 index 0000000..a5af6fe --- /dev/null +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/duration/Duration.java @@ -0,0 +1,429 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.time.duration; + +import org.nanoboot.powerframework.random.generators.RandomGenerator; +import org.nanoboot.powerframework.time.utils.TimeException; +import org.nanoboot.powerframework.time.utils.TimeUnit; +import org.nanoboot.powerframework.time.utils.TimeUnitConvertor; +import org.nanoboot.powerframework.time.utils.TimeUnitsValidator; +import org.nanoboot.powerframework.time.moment.UniversalDateTime; +import org.nanoboot.powerframework.time.moment.ZonedDateTime; +import org.nanoboot.powerframework.utils.StringUtils; + +/** + * Is used to do arithmetics with Date and Time. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public final class Duration { + + private static final Duration zeroDuration = new Duration(0); + + private static final String PLUS = "+"; + private static final String MINUS = "-"; + private static final String COLON = ":"; + + /** + * + * @return Duration instance + */ + public static Duration getZeroDuration() { + return zeroDuration; + } + + /** + * + * @return random duration + */ + public static Duration createRandomDuration() { + Duration duration; + RandomGenerator pseudoRandomNumberGenerator = RandomGenerator.getDefaultImplStatic(); + long days = pseudoRandomNumberGenerator.nextInt(0, 6000); + int hours = pseudoRandomNumberGenerator.nextInt(0, 23); + int minutes = pseudoRandomNumberGenerator.nextInt(0, 59); + int seconds = pseudoRandomNumberGenerator.nextInt(0, 59); + int milliseconds = pseudoRandomNumberGenerator.nextInt(0, 999); + duration = new Duration(days, hours, minutes, seconds, milliseconds); + return duration; + } + + /** + * + * @param value value of count of the unit + * @param timeUnit TimeUnit instance + * + * @return an instance of Duration class with the given count of days + */ + public static Duration of(long value, TimeUnit timeUnit) { + return new Duration(convertToMilliseconds(value, timeUnit)); + } + + /** + * Converts the value (timeUnit) to count of milliseconds. + * + * @param value value of count of the unit + * @param timeUnit TimeUnit instance for the value + * + * @return count of milliseconds of the count of the timeUnits + */ + private static long convertToMilliseconds(long value, TimeUnit timeUnit) { + return value * getMillisecondsPerTimeUnit(timeUnit); + } + + /** + * + * @param timeUnit TimeUnit instance + * + * @return count of milliseconds of one timeUnit + */ + private static int getMillisecondsPerTimeUnit(TimeUnit timeUnit) { + return (int) TimeUnitConvertor.convert(1, timeUnit, TimeUnit.MILLISECOND); + + } + + /** + * + * @param universalDateTime UniversalDateTime instance + * @param duration Duration instance to add to the time + * + * @return add to universalDateTime duration and return result + */ + public static UniversalDateTime fromUniversalDateTimePlusDurationCreateNewUniversalDateTime(UniversalDateTime universalDateTime, Duration duration) { + return addToUniversalDateTimeDuration(universalDateTime, duration, true); + } + + /** + * + * @param universalDateTime UniversalDateTime instance + * @param duration Duration instance to remove from the time + * + * @return subtract from universalDateTime duration and return result + */ + public static UniversalDateTime fromUniversalDateTimeMinusDurationCreateNewUniversalDateTime( + UniversalDateTime universalDateTime, + Duration duration) { + return addToUniversalDateTimeDuration(universalDateTime, duration, false); + } + + private static UniversalDateTime addToUniversalDateTimeDuration( + UniversalDateTime universalDateTime, + Duration duration, + boolean trueForAddingFalseForSubtracting) { + java.time.LocalDateTime javaLocalDateTime = universalDateTime.removeUniversalTimeZone().toJavaLocalDateTime(); + java.time.Duration javaDuration = duration.toJavaDuration(); + java.time.LocalDateTime newJavaLocalDateTime; + if(trueForAddingFalseForSubtracting) { + newJavaLocalDateTime = javaLocalDateTime.plus(javaDuration); + } else { + newJavaLocalDateTime = javaLocalDateTime.minus(javaDuration); + } + + int year = newJavaLocalDateTime.getYear(); + int day = newJavaLocalDateTime.getDayOfMonth(); + int month = newJavaLocalDateTime.getMonth().getValue(); + int hour = newJavaLocalDateTime.getHour(); + int minute = newJavaLocalDateTime.getMinute(); + int second = newJavaLocalDateTime.getSecond(); + final int nanosecondspermillisecond; + nanosecondspermillisecond = 1000000; + int millisecond = newJavaLocalDateTime.getNano() / nanosecondspermillisecond; + + return new UniversalDateTime(year, month, day, hour, minute, second, millisecond); + } + + /** + * + * @param zonedDateTime ZonedDateTime instance + * @param duration Duration instance to add to the time + * + * @return add to zonedDateTime duration and return result + */ + public static ZonedDateTime fromZonedDateTimePlusDurationCreateNewZonedDateTime(ZonedDateTime zonedDateTime, Duration duration) { + return addToZonedDateTimeDuration(zonedDateTime, duration, true); + } + + /** + * + * @param zonedDateTime ZonedDateTime instance + * @param duration Duration instance to remove from the time + * + * @return subtract from zonedDateTime duration and return result + */ + public static ZonedDateTime fromZonedDateTimeMinusDurationCreateNewZonedDateTime( + ZonedDateTime zonedDateTime, + Duration duration) { + return addToZonedDateTimeDuration(zonedDateTime, duration, false); + } + + private static ZonedDateTime addToZonedDateTimeDuration( + ZonedDateTime zonedDateTime, + Duration duration, + boolean trueForAddingFalseForSubtracting) { + UniversalDateTime universalDateTime = zonedDateTime.toUniversalDateTime(); + UniversalDateTime newUniversalDateTime; + if(trueForAddingFalseForSubtracting) { + newUniversalDateTime = fromUniversalDateTimePlusDurationCreateNewUniversalDateTime(universalDateTime, duration); + } else { + newUniversalDateTime = fromUniversalDateTimeMinusDurationCreateNewUniversalDateTime(universalDateTime, duration); + } + + return newUniversalDateTime.convertToZonedDateTimeWithUniversalTimeZone().toZonedDateTime(zonedDateTime.getTimeZone()); + } + + private final long countOfTotalMilliseconds; + private final int days; + private final int hours; + private final int minutes; + private final int seconds; + private final int milliseconds; + private final boolean positive; + + /** + * Constructor + * + * Creates new Duration with duration 0 milliseconds. + * + */ + public Duration() { + this(0); + } + + /** + * Constructor + * + * Creates new Duration from count of milliseconds. + * + * @param countOfMilliseconds milliseconds representing the new Duration + */ + public Duration(long countOfMilliseconds) { + + positive = countOfMilliseconds >= 0; + + this.countOfTotalMilliseconds = Math.abs(countOfMilliseconds); + this.days = (int) Math.floor(this.toTotal(TimeUnit.DAY)); + this.hours = (int) Math.floor(this.toTotal(TimeUnit.HOUR) - TimeUnitConvertor.convert(days, TimeUnit.DAY, TimeUnit.HOUR)); + this.minutes = (int) (Math.floor(this.toTotal(TimeUnit.MINUTE)) - TimeUnitConvertor.convert(days, TimeUnit.DAY, TimeUnit.MINUTE) - TimeUnitConvertor.convert(hours, TimeUnit.HOUR, TimeUnit.MINUTE)); + this.seconds = (int) Math.floor(this.toTotal(TimeUnit.SECOND) - TimeUnitConvertor.convert(days, TimeUnit.DAY, TimeUnit.SECOND) - TimeUnitConvertor.convert(hours, TimeUnit.HOUR, TimeUnit.SECOND) - TimeUnitConvertor.convert(minutes, TimeUnit.MINUTE, TimeUnit.SECOND)); + this.milliseconds = (int) (this.toTotal(TimeUnit.MILLISECOND) - TimeUnitConvertor.convert(days, TimeUnit.DAY, TimeUnit.MILLISECOND) - TimeUnitConvertor.convert(hours, TimeUnit.HOUR, TimeUnit.MILLISECOND) - TimeUnitConvertor.convert(minutes, TimeUnit.MINUTE, TimeUnit.MILLISECOND) - TimeUnitConvertor.convert(seconds, TimeUnit.SECOND, TimeUnit.MILLISECOND)); + + } + + /** + * Constructor + * + * Creates new Duration from the given values. + * + * @param days value + * @param hours value + * @param minutes value + * @param seconds value + * @param milliseconds value + */ + public Duration(long days, int hours, int minutes, int seconds, int milliseconds) { + this(true, days, hours, minutes, seconds, milliseconds); + } + + /** + * Constructor + * + * Creates new Duration from the given values. + * + * @param positive true, if this duration is greater than 0, otherwise false + * @param days value + * @param hours value + * @param minutes value + * @param seconds value + * @param milliseconds value + */ + public Duration(boolean positive, long days, int hours, int minutes, int seconds, int milliseconds) { + this( + (positive ? 1 : (-1)) + * (convertToMilliseconds(days, TimeUnit.DAY) + + convertToMilliseconds(hours, TimeUnit.HOUR) + + convertToMilliseconds(minutes, TimeUnit.MINUTE) + + convertToMilliseconds(seconds, TimeUnit.SECOND) + + milliseconds) + ); + TimeUnitsValidator.validate(hours, minutes, seconds, milliseconds); + } + + /** + * Constructor + * + * Creates new Duration from the String. + * + * @param string representing the new Duration + */ + public Duration(String string) { + String[] splitString = string.split("\\:+"); + if(splitString.length != 5) { + throw new TimeException("Input String has wrong format."); + } + try { + this.days = Integer.parseInt(splitString[0]); + this.hours = Integer.parseInt(splitString[1]); + this.minutes = Integer.parseInt(splitString[2]); + this.seconds = Integer.parseInt(splitString[3]); + this.milliseconds = Integer.parseInt(splitString[4]); + this.countOfTotalMilliseconds = convertToMilliseconds(days, TimeUnit.DAY) + + convertToMilliseconds(hours, TimeUnit.HOUR) + + convertToMilliseconds(minutes, TimeUnit.MINUTE) + + convertToMilliseconds(seconds, TimeUnit.SECOND) + + milliseconds; + this.positive = string.charAt(0) != '-'; + } catch (NumberFormatException e) {//NOSONAR + throw new TimeException("Input String has wrong format."); + } + TimeUnitsValidator.validate(hours, minutes, seconds, milliseconds); + } + + /** + * + * @param timeUnit TimeUnit instance + * + * @return value + */ + public long get(TimeUnit timeUnit) { + switch (timeUnit) { + case DAY: + return this.days; + case HOUR: + return this.hours; + case MINUTE: + return this.minutes; + case SECOND: + return this.seconds; + case MILLISECOND: + return this.milliseconds; + default: + throw new UnsupportedOperationException(); + } + } + + /** + * + * @return result of this control + */ + public boolean isPositive() { + return this.positive; + } + + /** + * + * @return new Duration instance created from negated this object + */ + public Duration negated() { + return new Duration((int) this.toTotal(TimeUnit.MILLISECOND) * (-1)); + } + + /** + * + * @return new Duration instance created from this object, if this object is + * negative, returned Duration is not negative + */ + public Duration abs() { + long absCountOfTotalMilliseconds; + absCountOfTotalMilliseconds = this.countOfTotalMilliseconds >= 0 ? countOfTotalMilliseconds : (countOfTotalMilliseconds * (-1)); + return new Duration(absCountOfTotalMilliseconds); + } + + /** + * + * @param durationToAdd Duration instance to add + * + * @return new Duration by adding the two Duration instance together + */ + public Duration plus(Duration durationToAdd) { + return plus((long) durationToAdd.toTotal(TimeUnit.MILLISECOND), TimeUnit.MILLISECOND); + } + + /** + * + * @param value value + * @param timeUnit TimeUnit instance + * + * @return new Duration instance + */ + public Duration plus(long value, TimeUnit timeUnit) { + return new Duration((int) this.toTotal(TimeUnit.MILLISECOND) + convertToMilliseconds(value, timeUnit)); + } + + /** + * + * @param durationToSubtract Duration instance + * + * @return from this object plus the given durationToAdd new Duration + */ + public Duration minus(Duration durationToSubtract) { + //TODO A bug is probably here. + return minus((long) durationToSubtract.toTotal(TimeUnit.MILLISECOND), TimeUnit.MILLISECOND); + } + + /** + * + * @param value value + * @param timeUnit TimeUnit instance + * + * @return new Duration instance + */ + public Duration minus(long value, + TimeUnit timeUnit) { + return new Duration((int) this.toTotal(TimeUnit.MILLISECOND) - convertToMilliseconds(value, timeUnit)); + } + + /** + * + * @param timeUnit DAY,HOUR,MINUTE,SECOND, MILLISECOND + * + * @return number of the timeUnit representing this duration + */ + public double toTotal(TimeUnit timeUnit) { + int divisor = 0; + divisor = getMillisecondsPerTimeUnit(timeUnit); + return countOfTotalMilliseconds / divisor; + + } + + /** + * + * @return java.time.duration representation of this object + */ + java.time.Duration toJavaDuration() { + java.time.Duration javaDuration = java.time.Duration.ofMillis((int) this.toTotal(TimeUnit.MILLISECOND)); + return this.isPositive() ? javaDuration : javaDuration.negated(); + } + + @Override + public String toString() { + return StringUtils.appendObjects(this.isPositive() ? PLUS : MINUS, + get(TimeUnit.DAY), + COLON, + get(TimeUnit.HOUR), + COLON, + get(TimeUnit.MINUTE), + COLON, + get(TimeUnit.SECOND), + COLON, + get(TimeUnit.MILLISECOND)); + } +} diff --git a/power-time/src/main/java/org/nanoboot/powerframework/time/duration/Period.java b/power-time/src/main/java/org/nanoboot/powerframework/time/duration/Period.java new file mode 100644 index 0000000..f2a9116 --- /dev/null +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/duration/Period.java @@ -0,0 +1,182 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.time.duration; + +import org.nanoboot.powerframework.time.moment.LocalDateTime; +import org.nanoboot.powerframework.time.utils.TimeException; +import org.nanoboot.powerframework.time.utils.TimeUnit; +import org.nanoboot.powerframework.time.moment.UniversalDateTime; +import org.nanoboot.powerframework.time.moment.ZonedDateTime; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class Period { + + private static Duration getDuration(UniversalDateTime startUniversalDateTime, + UniversalDateTime endUniversalDateTime) { + java.time.LocalDateTime javaStartLocalDateTime = startUniversalDateTime.removeUniversalTimeZone().toJavaLocalDateTime(); + java.time.LocalDateTime javaEndLocalDateTime = endUniversalDateTime.removeUniversalTimeZone().toJavaLocalDateTime(); + java.time.Duration javaDuration = java.time.Duration.between(javaStartLocalDateTime, javaEndLocalDateTime); + return new Duration(javaDuration.toMillis()); + } + + private final UniversalDateTime startUniversalDateTime; + private final UniversalDateTime endUniversalDateTime; + private final ZonedDateTime startZonedDateTime; + private final ZonedDateTime endZonedDateTime; + private final Duration duration; + + /** + * + * @param startUniversalDateTime UniversalDateTime instance + * @param endUniversalDateTime UniversalDateTime instance + */ + public Period(UniversalDateTime startUniversalDateTime, + UniversalDateTime endUniversalDateTime) { + this.startUniversalDateTime = startUniversalDateTime; + this.endUniversalDateTime = endUniversalDateTime; + this.startZonedDateTime = null; + this.endZonedDateTime = null; + this.duration = getDuration(startUniversalDateTime, endUniversalDateTime); + } + + /** + * + * @param startZonedDateTime + * @param endZonedDateTime + */ + public Period(ZonedDateTime startZonedDateTime, + ZonedDateTime endZonedDateTime) { + this.startUniversalDateTime = null; + this.endUniversalDateTime = null; + this.startZonedDateTime = startZonedDateTime; + this.endZonedDateTime = endZonedDateTime; + this.duration = getDuration(startZonedDateTime.toUniversalDateTime(), endZonedDateTime.toUniversalDateTime()); + } + + /** + * + * @param startUniversalDateTime UniversalDateTime instance + * @param plusDuration Duration to add + */ + public Period(UniversalDateTime startUniversalDateTime, + Duration plusDuration) { + this.startUniversalDateTime = startUniversalDateTime; + + java.time.LocalDateTime javaStartLocalDateTime = startUniversalDateTime.removeUniversalTimeZone().toJavaLocalDateTime(); + this.endUniversalDateTime = new UniversalDateTime(LocalDateTime.toPowerLocalDateTime(javaStartLocalDateTime.plusNanos((long) plusDuration.toTotal(TimeUnit.MILLISECOND) * 1000000))); + + this.startZonedDateTime = null; + this.endZonedDateTime = null; + + this.duration = getDuration(startUniversalDateTime, endUniversalDateTime); + } + + /** + * + * @param startZonedDateTime ZonedDateTime instance + * @param plusDuration Duration instance to add + */ + public Period(ZonedDateTime startZonedDateTime, + Duration plusDuration) { + this.startUniversalDateTime = null; + this.endUniversalDateTime = null; + + this.startZonedDateTime = startZonedDateTime; + + java.time.LocalDateTime javaStartLocalDateTime = startUniversalDateTime.removeUniversalTimeZone().toJavaLocalDateTime(); + this.endZonedDateTime = new UniversalDateTime(LocalDateTime.toPowerLocalDateTime(javaStartLocalDateTime.plusNanos((long) plusDuration.toTotal(TimeUnit.MILLISECOND) * 1000000))).convertToZonedDateTimeWithUniversalTimeZone(); + + this.duration = getDuration(startZonedDateTime.toUniversalDateTime(), endZonedDateTime.toUniversalDateTime()); + } + + /** + * + * @return Duration instance counted of this period + */ + public Duration getDuration() { + return duration; + } + + /** + * + * @return true, if this period uses universalDateTime, otherwise false + */ + public boolean usesUniversalTime() { + return startUniversalDateTime != null; + } + + /** + * + * @return true, if this period uses zonedDateTime, otherwise false + */ + public boolean usesZonedTime() { + return startZonedDateTime != null; + } + + /** + * + * @return UniversalDateTime instance + */ + public UniversalDateTime getStartUniversalDateTime() { + if(startUniversalDateTime == null) { + throw new TimeException("This period has no start universal date time."); + } + return startUniversalDateTime; + } + + /** + * + * @return UniversalDateTime instance + */ + public UniversalDateTime getEndUniversalDateTime() { + if(endUniversalDateTime == null) { + throw new TimeException("This period has no start universal date time."); + } + return endUniversalDateTime; + } + + /** + * + * @return ZonedDateTime instance + */ + public ZonedDateTime getStartZonedDateTime() { + if(startZonedDateTime == null) { + new TimeException("This period has no start universal date time."); + } + return startZonedDateTime; + } + + /** + * + * @return ZonedDateTime instance + */ + public ZonedDateTime getEndZonedDateTime() { + if(endZonedDateTime == null) { + new TimeException("This period has no start universal date time."); + } + return endZonedDateTime; + } +} diff --git a/power-time/src/main/java/org/nanoboot/powerframework/time/duration/SimpleStopWatch.java b/power-time/src/main/java/org/nanoboot/powerframework/time/duration/SimpleStopWatch.java new file mode 100644 index 0000000..16d914e --- /dev/null +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/duration/SimpleStopWatch.java @@ -0,0 +1,141 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.time.duration; +//TODO: Simple stop watch- Power- if running multiple times- there is an error - it is thrown - StopWatch was already started- to be fixed + +import org.nanoboot.powerframework.time.utils.TimeException; + + +/** + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class SimpleStopWatch { + + final static long MILLISECONDHASNANOSECONDS = 1000000; + final static long SECONDHASMILLISECONDS = 1000; + final static long MINUTEHASSECONDS = 60; + final static long MINUTEHASMILLISECONDS = MINUTEHASSECONDS * SECONDHASMILLISECONDS; + + private long timeStart; + private long timeEnd; + + private long totalNanoseconds; + + private long totalMilliseconds; + private long runningTimeInMinutes; + private long runningTimeInSeconds; + private long runningTimeInMilliseconds; + + private boolean started = false; + private boolean stopped = false; + + public SimpleStopWatch() { + + } + + public void start() { + if(this.started) { + throw new TimeException("The stop watch was already started."); + } + this.timeStart = System.nanoTime(); + this.started = true; + } + + public void stop() { + if(!this.started) { + throw new TimeException("The stop watch was not started."); + } + + if(this.stopped) { + throw new TimeException("The stop watch was already stopped."); + } + + this.timeEnd = System.nanoTime(); + this.stopped = true; + this.computeTime(); + } + + private void computeTime() { + + this.throwExceptionIfWasNotStopped(); + + this.totalNanoseconds = this.timeEnd - this.timeStart; + this.totalMilliseconds = this.totalNanoseconds / MILLISECONDHASNANOSECONDS; + + long remainingMilliseconds = this.totalMilliseconds; + + this.runningTimeInMinutes = remainingMilliseconds / MINUTEHASMILLISECONDS; + remainingMilliseconds = remainingMilliseconds - (this.runningTimeInMinutes * MINUTEHASMILLISECONDS); + + this.runningTimeInSeconds = remainingMilliseconds / SECONDHASMILLISECONDS; + remainingMilliseconds = remainingMilliseconds - (this.runningTimeInSeconds * SECONDHASMILLISECONDS); + + this.runningTimeInMilliseconds = remainingMilliseconds; + + } + + public boolean isStarted() { + return this.started; + } + + public boolean isStopped() { + return this.stopped; + } + + public long getTotalNanoseconds() { + this.throwExceptionIfWasNotStopped(); + return this.totalNanoseconds; + } + + public long getTotalMilliseconds() { + this.throwExceptionIfWasNotStopped(); + return this.totalMilliseconds; + } + + public long getRunningTimeInMinutes() { + this.throwExceptionIfWasNotStopped(); + return this.runningTimeInMinutes; + } + + public long getRunningTimeInSeconds() { + this.throwExceptionIfWasNotStopped(); + return this.runningTimeInSeconds; + } + + public long getRunningTimeInMilliseconds() { + this.throwExceptionIfWasNotStopped(); + return this.runningTimeInMilliseconds; + } + + public String createMessage() { + this.throwExceptionIfWasNotStopped(); + return "The running time was " + this.runningTimeInMinutes + " minutes, " + this.runningTimeInSeconds + " seconds and " + this.runningTimeInMilliseconds + " milliseconds (" + this.totalNanoseconds + " nanoseconds in total)."; + } + + private void throwExceptionIfWasNotStopped() { + if(!this.stopped) { + throw new TimeException("The stop watch was not stopped."); + } + } + +} diff --git a/power-time/src/main/java/org/nanoboot/powerframework/time/duration/StopWatch.java b/power-time/src/main/java/org/nanoboot/powerframework/time/duration/StopWatch.java new file mode 100644 index 0000000..f20f452 --- /dev/null +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/duration/StopWatch.java @@ -0,0 +1,128 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.time.duration; + +import org.nanoboot.powerframework.time.utils.TimeException; +import org.nanoboot.powerframework.time.utils.TimeUnit; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class StopWatch { + + private static final int NANOSECONDHASMILlISECONDS = 1000000; + + private static long convertNanosecondsToMilliSeconds(long nanoseconds) { + return nanoseconds / NANOSECONDHASMILlISECONDS; + } + private Duration currentDuration = Duration.getZeroDuration(); + private StopWatchState stopWatchState = StopWatchState.CLEAR; + + private long startFlag = 0; + private long endFlag = 0; + + /** + * + * @return + */ + public StopWatchState getStopWatchState() { + return this.stopWatchState; + } + + /** + * + */ + public void clear() { + this.stopWatchState = StopWatchState.CLEAR; + this.currentDuration = Duration.getZeroDuration(); + } + + /** + * + */ + public void start() { + if(this.stopWatchState == StopWatchState.RUNNING) { + return; + } + startFlag = this.getCurrentFlagInNanoseconds(); + stopWatchState = StopWatchState.RUNNING; + } + + /** + * + */ + public void stop() { + if(this.stopWatchState == StopWatchState.RUNNING) { + endFlag = this.getCurrentFlagInNanoseconds(); + this.currentDuration = this.currentDuration.plus(getElapsedTimeInMillisecondsFromFlags(), TimeUnit.MILLISECOND); + startFlag = 0; + endFlag = 0; + this.stopWatchState = StopWatchState.STOPPED; + } + } + + private long getElapsedTimeInMillisecondsFromFlags() { + return StopWatch.convertNanosecondsToMilliSeconds(endFlag - startFlag); + } + + /** + * + * @return + */ + public Duration getCurrentDuration() { + if(this.stopWatchState == StopWatchState.RUNNING) { + throw new TimeException("Can't get the duration, becuae the StopWatch is running. Stop StopWatch before getting duration"); + } + + return this.currentDuration; + } + + private long getCurrentFlagInNanoseconds() { + return System.nanoTime(); + } + + /** + * + * @return + */ + public boolean isClear() { + return this.stopWatchState == StopWatchState.CLEAR; + } + + /** + * + * @return + */ + public boolean isRunning() { + return this.stopWatchState == StopWatchState.RUNNING; + } + + /** + * + * @return + */ + public boolean isStopped() { + return this.stopWatchState == StopWatchState.STOPPED; + } +} diff --git a/power-time/src/main/java/org/nanoboot/powerframework/time/duration/StopWatchState.java b/power-time/src/main/java/org/nanoboot/powerframework/time/duration/StopWatchState.java new file mode 100644 index 0000000..840fbf2 --- /dev/null +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/duration/StopWatchState.java @@ -0,0 +1,45 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.time.duration; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public enum StopWatchState { + + /** + * + */ + CLEAR, + + /** + * + */ + RUNNING, + + /** + * + */ + STOPPED; +} diff --git a/power-time/src/main/java/org/nanoboot/powerframework/time/module-info.java.txt b/power-time/src/main/java/org/nanoboot/powerframework/time/module-info.java.txt new file mode 100644 index 0000000..e316d2c --- /dev/null +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/module-info.java.txt @@ -0,0 +1,7 @@ +module powerframework.datetime { +requires powerframework.json; +requires powerframework.pseudorandom; +exports powerframework.datetime.elapsed; +exports powerframework.datetime.moment; +exports powerframework.datetime.utilities; +} diff --git a/power-time/src/main/java/org/nanoboot/powerframework/time/moment/DateTime.java b/power-time/src/main/java/org/nanoboot/powerframework/time/moment/DateTime.java new file mode 100644 index 0000000..913193d --- /dev/null +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/moment/DateTime.java @@ -0,0 +1,261 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.time.moment; + +import org.nanoboot.powerframework.time.utils.TimeException; + +/** + * This class represents date and time and is immutable. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public abstract class DateTime implements Comparable { + + private final LocalDate date; + private final LocalTime time; + + /** + * Constructor + *

+ * Sets all values. + * + * @param localDate Represents a date. + * @param localTime Represents a time. + */ + DateTime(LocalDate localDate, + LocalTime localTime) { + this.date = localDate; + this.time = localTime; + } + + /** + * Constructor + *

+ * Sets all values. + * + * @param year Represents a year. + * @param month Represents a month. + * @param day Represents a day. + * @param hour24Format Represents an hour. + * @param minute Represents a minute + * @param second Represents a second. + * @param millisecond Represents a millisecond. + */ + DateTime(int year, + int month, + int day, + int hour24Format, + int minute, + int second, + int millisecond) { + this.date = new LocalDate(year, month, day); + this.time = new LocalTime(hour24Format, minute, second, millisecond); + } + + /** + * Constructor + *

+ * Sets all values from another object. + * + * @param dateTimeIn instance of a object extending the DateTime class, which values of this object will be set from + */ + protected DateTime(DateTime dateTimeIn) { + int year = dateTimeIn.getYear(); + int month = dateTimeIn.getMonth(); + int day = dateTimeIn.getDay(); + date = new LocalDate(year, month, day); + + int hour24Format = dateTimeIn.getHour(); + int minute = dateTimeIn.getMinute(); + int second = dateTimeIn.getSecond(); + int millisecond = dateTimeIn.getMillisecond(); + time = new LocalTime(hour24Format, minute, second, millisecond); + } + + /** + * Constructor + *

+ * Sets all values from String + * + * @param dateTimeInString This String has following format: 2016-12-31 + * 24:45:14:453 yyyy-MM-dd HH:mm:ss:SSS + */ + public DateTime(String dateTimeInString) { + String[] array=dateTimeInString.split(" "); + if(array.length!= 2){ + throw new TimeException("Wrong Date Time format: " + dateTimeInString); + } + date = new LocalDate(array[0]); + + time = new LocalTime(array[1]); + } + /** + * Constructor + *

+ * Sets all values from String + * + * @param dateTimeInString This String has following format: 2016-12-31 + * 24:45:14:453 yyyy-MM-dd HH:mm:ss:SSS + */ + public DateTime(long dateTimeAsLong) { + String str = String.valueOf(dateTimeAsLong); + + if(str.length()!= 17){ + throw new TimeException("Wrong Date Time format: " + dateTimeAsLong); + } + String year = str.substring(0,4); + String month = str.substring(4,6); + String day = str.substring(6,8); + String hour = str.substring(8,10); + String minute = str.substring(10,12); + String second = str.substring(12,14); + String millisecond = str.substring(14,17); + + int yearInt = Integer.valueOf(year); + int monthInt = Integer.valueOf(month); + int dayInt = Integer.valueOf(day); + int hourInt = Integer.valueOf(hour); + int minuteInt = Integer.valueOf(minute); + int secondInt = Integer.valueOf(second); + int millisecondInt = Integer.valueOf(millisecond); + + date = new LocalDate(yearInt, monthInt, dayInt); + + time = new LocalTime(hourInt, minuteInt, secondInt, millisecondInt); + } + + /** + * @return year + */ + public int getYear() { + return this.date.getYear(); + } + + /** + * @return month + */ + public int getMonth() { + return this.date.getMonth(); + } + + /** + * @return day + */ + public int getDay() { + return this.date.getDay(); + } + + /** + * @return hour + */ + public int getHour() { + return this.time.getHour(); + } + + /** + * @return minute + */ + public int getMinute() { + return this.time.getMinute(); + } + + /** + * @return second + */ + public int getSecond() { + return this.time.getSecond(); + } + + /** + * @return millisecond + */ + public int getMillisecond() { + return this.time.getMillisecond(); + } + /** + * @return date + */ + public LocalDate getDate() { + return this.date; + } + + /** + * @return time + */ + public LocalTime getTime() { + return this.time; + } + + @Override + public String toString() { + StringBuilder stringBuffer = new StringBuilder(); + stringBuffer.append(this.date.toString()); + stringBuffer.append(" "); + stringBuffer.append(this.time.toString()); + + return stringBuffer.toString(); + } + + public long toLong() { + StringBuilder sb = new StringBuilder(); + sb.append(getYear()); + + if (getMonth() < 10) { + sb.append("0"); + } + sb.append(getMonth()); + + if (getDay() < 10) { + sb.append("0"); + } + sb.append(getDay()); + + if (getHour() < 10) { + sb.append("0"); + } + sb.append(getHour()); + + if (getMinute() < 10) { + sb.append("0"); + } + sb.append(getMinute()); + + if (getSecond() < 10) { + sb.append("0"); + } + sb.append(getSecond()); + + if (getMillisecond() < 100) { + sb.append("0"); + } + if (getMillisecond() < 10) { + sb.append("0"); + } + sb.append(getMillisecond()); + + return Long.valueOf(sb.toString()); + } + + public int compareTo(DateTime otherDateTime) { + return Long.valueOf(toLong()).compareTo(Long.valueOf(otherDateTime.toLong())); + } +} diff --git a/src/main/java/org/nanoboot/powerframework/datetime/LocalDate.java b/power-time/src/main/java/org/nanoboot/powerframework/time/moment/LocalDate.java similarity index 52% rename from src/main/java/org/nanoboot/powerframework/datetime/LocalDate.java rename to power-time/src/main/java/org/nanoboot/powerframework/time/moment/LocalDate.java index 02fdd47..e304580 100644 --- a/src/main/java/org/nanoboot/powerframework/datetime/LocalDate.java +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/moment/LocalDate.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,16 +18,63 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.datetime; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +package org.nanoboot.powerframework.time.moment; -import org.nanoboot.powerframework.PowerRuntimeException; +import org.nanoboot.powerframework.core.PowerException; +import org.nanoboot.powerframework.time.utils.DateUnitsValidator; +import org.nanoboot.powerframework.time.utils.TimeException; +import org.nanoboot.powerframework.utils.StringUtils; /** * Represents Date without time zone information. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokáč e-mail: robertvokac@nanoboot.org */ -public final class LocalDate { +public final class LocalDate { + + private static final String DASH = "-"; + public static final int LOCAL_DATE_AS_STRING_LENGTH = 10; + + /** + * + * @param s with format yyyy-MM-dd + */ + public LocalDate(String s) { + if (s == null) { + throw new TimeException("Local date as string is null."); + } + if (s.length() != LOCAL_DATE_AS_STRING_LENGTH) { + throw new TimeException("Local date length is " + s.length() + ", but length 10 is expected."); + } + int year = Integer.parseInt(s.substring(0, 4)); + int month = Integer.parseInt(s.substring(5, 7)); + int day = Integer.parseInt(s.substring(8, 10)); + + DateUnitsValidator.validate(year, month, day); + this.year = year; + this.month = month; + this.day = day; + } + + /** + * Checks if year is leap. A year is leap if this year is divided by 4 and + * there remainder 0. In other words this year is divisible by 4. + * + * @param year value + * + * @return true if the year is leap, otherwise false. + */ + public static boolean isYearLeap(int year) { + return (year % 4) == 0; + } + + private final int year; private final int month; @@ -39,55 +86,17 @@ public final class LocalDate { * @param year Year of this date. * @param month Month of this date. * @param day Day of this date. - * @exception PowerRuntimeException if parameters are invalid or have wrong + * + * @throws PowerException if parameters are invalid or have wrong * combination. */ public LocalDate(int year, int month, int day) { - LocalDate.checkInputValuesForDateAndIfThereIsAnInvalidOneThrowException(year, month, day); + DateUnitsValidator.validate(year, month, day); this.year = year; this.month = month; this.day = day; } - /** - * Checks input data for date. - * - * @param year - * @param month - * @param day - * @exception PowerRuntimeException if input data for date are invalid or - * have wrong combination.
- * This will throw PowerRuntimeException: - * {@code new LocalDateTime(2015,2,29)}
- * This will throw PowerRuntimeException: - * {@code new LocalDateTime(2013,6,31)}
- * This will not throw PowerRuntimeException: - * {@code new LocalDateTime(2013,6,30)}
- */ - private static void checkInputValuesForDateAndIfThereIsAnInvalidOneThrowException(int year, int month, int day) { - if (!DateUnitsValidator.isMonthValid(month)) { - throw new PowerRuntimeException("Month is not valid."); - } - if (!DateUnitsValidator.isDayValid(day)) { - throw new PowerRuntimeException("Day is not valid."); - } - if (!DateUnitsValidator.hasDateValidCombination(year, month, day)) { - throw new PowerRuntimeException("Date has not valid combination."); - - } - } - - /** - * Checks if year is leap. A year is leap if this year is divided by 4 and - * there remainder 0. In other words this year is divisible by 4. - * - * @param year - * @return true if the year is leap, otherwise false. - */ - public static boolean isYearLeap(int year) { - return (year % 4) == 0; - } - /** * * @return year of this date. @@ -114,19 +123,8 @@ public final class LocalDate { @Override public String toString() { - StringBuilder stringBuilder; - stringBuilder = new StringBuilder(); - stringBuilder.append(this.getYear()); - stringBuilder.append("-"); - if (month < 10) { - stringBuilder.append("0"); - } - stringBuilder.append(this.getMonth()); - stringBuilder.append("-"); - if (day < 10) { - stringBuilder.append("0"); - } - stringBuilder.append(this.getDay()); - return stringBuilder.toString(); + return StringUtils.appendObjects(getYear(), DASH, month < 10 ? "0" : "", getMonth(), DASH, day < 10 ? "0" : "", getDay()); } + + } diff --git a/power-time/src/main/java/org/nanoboot/powerframework/time/moment/LocalDateTime.java b/power-time/src/main/java/org/nanoboot/powerframework/time/moment/LocalDateTime.java new file mode 100644 index 0000000..7955138 --- /dev/null +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/moment/LocalDateTime.java @@ -0,0 +1,167 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.time.moment; + +import java.time.format.DateTimeFormatter; + +/** + * This class stores date time without time zone information. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public final class LocalDateTime extends DateTime { + + /** + * + * @param universalDateTime UniversalDateTime instance + * + * @return LocalDateTime instance + */ + public static LocalDateTime removeUniversalTimeZone(UniversalDateTime universalDateTime) { + return new LocalDateTime(universalDateTime); + } + + /** + * + * @param zonedDateTime ZonedDateTime instance + * + * @return LocalDateTime instance + */ + public static LocalDateTime removeTimeZone(ZonedDateTime zonedDateTime) { + return new LocalDateTime(zonedDateTime); + } + + /** + * + * + * @param ldt java.time.LocalDateTime instance + * + * @return a java.time.LocalDateTime instance from this object + */ + public static LocalDateTime toPowerLocalDateTime(java.time.LocalDateTime ldt) { + return new LocalDateTime(ldt.getYear(), ldt.getDayOfMonth(), ldt.getDayOfMonth(), ldt.getHour(), ldt.getMinute(), ldt.getSecond(), ldt.getSecond()); + } + + /** + * Constructor + * + * Creates new LocalDateTime from String. + * + * @param dateTimeInString string representing the new LocalDateTime + */ + public LocalDateTime(final String dateTimeInString) { + super(dateTimeInString); + } + + /** + * Constructor + * + * Creates new LocalDateTime with these parameters. + * + * @param date date + * @param time time + */ + public LocalDateTime(final LocalDate date, final LocalTime time) { + super(date.getYear(), date.getMonth(), date.getDay(), + time.getHour(), time.getMinute(), time.getSecond(), + time.getMillisecond()); + } + /** + * Constructor + * + * Creates new LocalDateTime with these parameters. + * + * @param year value + * @param month value + * @param day value + * @param hour24Format value + * @param minute value + * @param second value + * @param millisecond value + */ + public LocalDateTime(int year, + int month, + int day, + int hour24Format, + int minute, + int second, + int millisecond) { + super(year, month, day, hour24Format, minute, second, millisecond); + } + + /** + * Constructor + * + * Creates new LocalDateTime from UniversalDateTime. + * + * @param universalDateTime UniversalDateTime instance + */ + private LocalDateTime(UniversalDateTime universalDateTime) { + super(universalDateTime); + } + + /** + * Constructor + * + * Creates new LocalDateTime from ZonedDateTime. The time zone information + * is lost. + * + * @param zonedDateTime ZonedDateTime instance + */ + private LocalDateTime(ZonedDateTime zonedDateTime) { + super(zonedDateTime); + } + + /** + * Adds the universal time zone information to this local date time and + * return new instance. + * + * @return a UniversalDateTime instance from this object. + */ + public UniversalDateTime addUniversalTimeZoneInformation() { + return UniversalDateTime.addUniversalTimeZoneInformation(this); + } + + /** + * Adds the time zone information to this local date time and return new + * instance. + * + * @param timeZone time zone of new created ZonedDateTime + * + * @return a ZonedDateTime instance from this object + */ + public ZonedDateTime addTimeZone(TimeZone timeZone) { + return ZonedDateTime.joinLocalDateTimeAndTimeZone(this, timeZone); + } + + /** + * + * + * @return a java.time.LocalDateTime instance from this object + */ + public java.time.LocalDateTime toJavaLocalDateTime() { + DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS"); + String stringRepresentationOfThisObject = this.toString(); + return java.time.LocalDateTime.parse(stringRepresentationOfThisObject, dateTimeFormatter); + } + +} diff --git a/power-time/src/main/java/org/nanoboot/powerframework/time/moment/LocalTime.java b/power-time/src/main/java/org/nanoboot/powerframework/time/moment/LocalTime.java new file mode 100644 index 0000000..d2255ba --- /dev/null +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/moment/LocalTime.java @@ -0,0 +1,138 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.time.moment; + +import org.nanoboot.powerframework.core.PowerException; +import org.nanoboot.powerframework.time.utils.TimeException; +import org.nanoboot.powerframework.time.utils.TimeUnitsValidator; +import lombok.Getter; + +/** + * Represents Time without date and time zone information. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public final class LocalTime { + + private static final String COLON = ":"; + public static final int LOCAL_TIME_AS_STRING_LENGTH = 12; + + @Getter + private final int hour; + @Getter + private final int minute; + @Getter + private final int second; + @Getter + private final int millisecond; + + /** + * Constructor. + * Millisecond is automatically set to 0. + * + * @param hour hour value + * @param minute minute value + * @param second second value + * + * @throws PowerException if parameters are invalid. + */ + public LocalTime(int hour, + int minute, + int second) { + this(hour, minute, second, 0); + } + /** + * Constructor + * + * @param hour hour value + * @param minute minute value + * @param second second value + * @param millisecond millisecond value + * + * @throws PowerException if parameters are invalid. + */ + public LocalTime(int hour, + int minute, + int second, + int millisecond) { + TimeUnitsValidator.validate(hour, minute, second, millisecond); + this.hour = hour; + this.minute = minute; + this.second = second; + this.millisecond = millisecond; + } + + /** + * + * @param s with format HH:mm:ss:SSS + */ + public LocalTime(String s) { + if (s == null) { + throw new TimeException("Local time as string is null."); + } + if (s.length() != LOCAL_TIME_AS_STRING_LENGTH) { + throw new TimeException("Local time length is " + s.length() + ", but length 12 is expected."); + } + int hour = Integer.parseInt(s.substring(0, 2)); + int minute = Integer.parseInt(s.substring(3, 5)); + int second = Integer.parseInt(s.substring(6, 8)); + int millisecond = Integer.parseInt(s.substring(9, 12)); + TimeUnitsValidator.validate(hour, minute, second, millisecond); + this.hour = hour; + this.minute = minute; + this.second = second; + this.millisecond = millisecond; + } + + /* + * Converts this time to format HH:MM:SS::MIS + */ + @Override + public String toString() { + StringBuilder stringBuilder = new StringBuilder(); + + if(hour < 10) { + stringBuilder.append("0"); + } + stringBuilder.append(this.getHour()); + stringBuilder.append(COLON); + if(minute < 10) { + stringBuilder.append("0"); + } + stringBuilder.append(this.getMinute()); + stringBuilder.append(COLON); + if(second < 10) { + stringBuilder.append("0"); + } + stringBuilder.append(this.getSecond()); + stringBuilder.append(COLON); + if(millisecond < 10) { + stringBuilder.append("00"); + } else if(millisecond < 100) { + stringBuilder.append("0"); + } + stringBuilder.append(this.getMillisecond()); + return stringBuilder.toString(); + } + + +} diff --git a/src/main/java/org/nanoboot/powerframework/datetime/TimeZone.java b/power-time/src/main/java/org/nanoboot/powerframework/time/moment/TimeZone.java similarity index 80% rename from src/main/java/org/nanoboot/powerframework/datetime/TimeZone.java rename to power-time/src/main/java/org/nanoboot/powerframework/time/moment/TimeZone.java index cbf4cf2..194cfb2 100644 --- a/src/main/java/org/nanoboot/powerframework/datetime/TimeZone.java +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/moment/TimeZone.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,39 +18,23 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.datetime; +package org.nanoboot.powerframework.time.moment; -import java.time.ZoneId; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import org.nanoboot.powerframework.PowerRuntimeException; +import java.time.*; +import java.util.*; +import org.nanoboot.powerframework.time.utils.TimeException; /** * Represents time zone. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * + * @author Robert Vokac + * @since 0.0.0 */ public class TimeZone { private static final ArrayList listOfTimeZones = new ArrayList<>(ZoneId.getAvailableZoneIds()); - private final String timeZoneID; - - /** - * Constructor - * - * Only time zone with valid timeZoneID can be created. - * - * @param timeZoneID - */ - public TimeZone(String timeZoneID) { - if (!TimeZone.isTimeZoneIDValid(timeZoneID)) { - throw new PowerRuntimeException("There is no time zone id with the name " + timeZoneID + "."); - } - this.timeZoneID = timeZoneID; - } - static { Collections.sort(listOfTimeZones); } @@ -60,17 +44,33 @@ public class TimeZone { * @return list of all available time zone IDs */ public static List getListOfTimeZoneIDs() { - return listOfTimeZones; + return Collections.unmodifiableList(listOfTimeZones); } /** * * @param timeZoneID + * * @return true if the timeZoneID is valid (available), otherwise false. */ public static boolean isTimeZoneIDValid(String timeZoneID) { return listOfTimeZones.contains(timeZoneID); } + private final String timeZoneID; + + /** + * Constructor + * + * Only time zone with valid timeZoneID can be created. + * + * @param timeZoneID + */ + public TimeZone(String timeZoneID) { + if(!TimeZone.isTimeZoneIDValid(timeZoneID)) { + throw new TimeException("There is no time zone id with the name " + timeZoneID + "."); + } + this.timeZoneID = timeZoneID; + } /** * diff --git a/src/main/java/org/nanoboot/powerframework/datetime/UniversalDateTime.java b/power-time/src/main/java/org/nanoboot/powerframework/time/moment/UniversalDateTime.java similarity index 50% rename from src/main/java/org/nanoboot/powerframework/datetime/UniversalDateTime.java rename to power-time/src/main/java/org/nanoboot/powerframework/time/moment/UniversalDateTime.java index a9985a9..f026a20 100644 --- a/src/main/java/org/nanoboot/powerframework/datetime/UniversalDateTime.java +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/moment/UniversalDateTime.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,17 +18,57 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.datetime; +package org.nanoboot.powerframework.time.moment; -import org.nanoboot.powerframework.pseudorandom.PseudoRandomGenerator; +import org.nanoboot.powerframework.random.generators.RandomGenerator; +import org.nanoboot.powerframework.time.TimeSource; +import org.nanoboot.powerframework.time.utils.DateUnitsValidator; +import org.nanoboot.powerframework.time.duration.Duration; +import org.nanoboot.powerframework.time.duration.Period; /** * This class stores universal date time. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public final class UniversalDateTime extends DateTime { + static UniversalDateTime addUniversalTimeZoneInformation( + LocalDateTime localDateTime) { + return new UniversalDateTime(localDateTime); + } + + /** + * + * @return current universal date time + */ + public static UniversalDateTime now() { + return TimeSource.getCurrentUniversalDateTimeInstance(); + } + + /** + * + * @return random universal date time + */ + public static UniversalDateTime random() { + UniversalDateTime universalDateTime; + int maxPossibleYear = UniversalDateTime.now().getYear(); + RandomGenerator randomGenerator = RandomGenerator.getDefaultImplStatic(); + int randomYear = randomGenerator.nextInt(1900, maxPossibleYear); + int randomMonth = randomGenerator.nextInt(1, 12); + int randomDay = randomGenerator.nextInt(1, 31); + int randomHour = randomGenerator.nextInt(0, 23); + int randomMinute = randomGenerator.nextInt(0, 59); + int randomSecond = randomGenerator.nextInt(0, 59); + int randomMillisecond = randomGenerator.nextInt(0, 999); + if(!DateUnitsValidator.hasDateValidCombination(randomYear, randomMonth, randomDay)) { + randomDay -= randomGenerator.nextInt(3, 20); + } + universalDateTime = new UniversalDateTime(randomYear, randomMonth, randomDay, randomHour, randomMinute, randomSecond, randomMillisecond); + return universalDateTime; + } + /** * Constructor * @@ -53,7 +93,13 @@ public final class UniversalDateTime extends DateTime { * @param second * @param millisecond */ - public UniversalDateTime(int year, int month, int day, int hour24Format, int minute, int second, int millisecond) { + public UniversalDateTime(int year, + int month, + int day, + int hour24Format, + int minute, + int second, + int millisecond) { super(year, month, day, hour24Format, minute, second, millisecond); } @@ -64,7 +110,7 @@ public final class UniversalDateTime extends DateTime { * * @param zonedDateTime */ - public UniversalDateTime(ZonedDateTime zonedDateTime) { + private UniversalDateTime(ZonedDateTime zonedDateTime) { super(zonedDateTime.toUniversalDateTime()); } @@ -78,54 +124,46 @@ public final class UniversalDateTime extends DateTime { public UniversalDateTime(LocalDateTime localDateTime) { super(localDateTime); } - /** + * Constructor * - * @return current universal date time + * Creates new UniversalDateTime from long. + * + * @param udtAsLong */ - public static UniversalDateTime getCurrentUniversalDateTime() { - return TimeSource.getCurrentUniversalDateTimeInstance(); + public UniversalDateTime(long udtAsLong) { + super(udtAsLong); + } + + UniversalDateTime updateDateAndTimeToUniversalTimeZone( + ZonedDateTime zonedDateTime) { + return new UniversalDateTime(zonedDateTime); } /** * - * @return random universal date time + * @param duration + * + * @return */ - public static UniversalDateTime getRandomUniversalDateTime() { - UniversalDateTime universalDateTime; - - int maxPossibleYear = UniversalDateTime.getCurrentUniversalDateTime().getYear(); - - int randomYear = PseudoRandomGenerator.getInstance().getInt(1900, maxPossibleYear); - int randomMonth = PseudoRandomGenerator.getInstance().getInt(1, 12); - int randomDay = PseudoRandomGenerator.getInstance().getInt(1, 31); - - int randomHour = PseudoRandomGenerator.getInstance().getInt(0, 23); - int randomMinute = PseudoRandomGenerator.getInstance().getInt(0, 59); - int randomSecond = PseudoRandomGenerator.getInstance().getInt(0, 59); - int randomMillisecond = PseudoRandomGenerator.getInstance().getInt(0, 999); - - if (!DateUnitsValidator.hasDateValidCombination(randomYear, randomMonth, randomDay)) { - randomDay = randomDay - PseudoRandomGenerator.getInstance().getInt(3, 20); - } - - universalDateTime = new UniversalDateTime(randomYear, randomMonth, randomDay, randomHour, randomMinute, randomSecond, randomMillisecond); - - return universalDateTime; + public UniversalDateTime plusDuration(Duration duration) { + return new Period(this, duration).getEndUniversalDateTime(); } /** - * @return a ZonedDateTime instance from this object + * + * @return */ - public ZonedDateTime toZonedDateTime() { - return new ZonedDateTime(this); + public ZonedDateTime convertToZonedDateTimeWithUniversalTimeZone() { + return ZonedDateTime.updateDateAndTimeToUniversalDateTime(this); } /** - * @return a LocalDateTime instance from this object without universal date - * time information. + * + * @return */ - public LocalDateTime toLocalDateTime() { - return new LocalDateTime(this); + public LocalDateTime removeUniversalTimeZone() { + return LocalDateTime.removeUniversalTimeZone(this); } + } diff --git a/src/main/java/org/nanoboot/powerframework/datetime/ZonedDateTime.java b/power-time/src/main/java/org/nanoboot/powerframework/time/moment/ZonedDateTime.java similarity index 71% rename from src/main/java/org/nanoboot/powerframework/datetime/ZonedDateTime.java rename to power-time/src/main/java/org/nanoboot/powerframework/time/moment/ZonedDateTime.java index e83366a..2c183d6 100644 --- a/src/main/java/org/nanoboot/powerframework/datetime/ZonedDateTime.java +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/moment/ZonedDateTime.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,20 +18,70 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.datetime; +package org.nanoboot.powerframework.time.moment; import java.time.ZoneId; -import java.time.format.DateTimeFormatter; +import java.time.format.*; +import org.nanoboot.powerframework.time.duration.Duration; +import org.nanoboot.powerframework.time.duration.Period; /** * Represents date and time with time zone information. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public final class ZonedDateTime extends DateTime { private static final String DATETIMEFORMAT = "yyyy-MM-dd HH:mm:ss:SSS"; private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATETIMEFORMAT); + + /** + * + * @param timeZone + * + * @return + */ + public static ZonedDateTime getCurrentZonedDateTimeForTimeZone( + TimeZone timeZone) { + UniversalDateTime udt = UniversalDateTime.now(); + return udt.convertToZonedDateTimeWithUniversalTimeZone().toZonedDateTime(timeZone); + } + + static ZonedDateTime updateDateAndTimeToUniversalDateTime( + UniversalDateTime universalDateTime) { + return new ZonedDateTime(universalDateTime); + } + + static ZonedDateTime joinLocalDateTimeAndTimeZone( + LocalDateTime localDateTime, + TimeZone toTimeZone) { + return new ZonedDateTime(localDateTime, toTimeZone); + } + + /** + * + * @param dateTimeInString + * @param oldTimeZone + * @param newTimeZone + * + * @return String representation from the given String, but old time zone is + * changed to new time zone. + */ + static String convertDateTimeFromOneTimeZoneToAnother( + String dateTimeInString, + TimeZone oldTimeZone, + TimeZone newTimeZone) { + + java.time.LocalDateTime localDateTime = java.time.LocalDateTime.parse(dateTimeInString, dateTimeFormatter); + + ZoneId oldZoneID = ZoneId.of(oldTimeZone.getTimeZoneID()); + java.time.ZonedDateTime oldZonedDateTime = localDateTime.atZone(oldZoneID); + + ZoneId newZoneId = ZoneId.of(newTimeZone.getTimeZoneID()); + java.time.ZonedDateTime newZonedDateTime = oldZonedDateTime.withZoneSameInstant(newZoneId); + return dateTimeFormatter.format(newZonedDateTime); + } /** * Instance of class UniversalDateTime for this ZonedDateTime. */ @@ -45,10 +95,10 @@ public final class ZonedDateTime extends DateTime { * * @param universalDateTime */ - public ZonedDateTime(UniversalDateTime universalDateTime) { + private ZonedDateTime(UniversalDateTime universalDateTime) { super(universalDateTime); - TimeZone timeZoneForUniversalTime = new org.nanoboot.powerframework.datetime.TimeZone("UTC"); + TimeZone timeZoneForUniversalTime = new TimeZone("UTC"); this.timeZone = timeZoneForUniversalTime; this.universalDateTime = universalDateTime; @@ -62,12 +112,13 @@ public final class ZonedDateTime extends DateTime { * @param localDateTime * @param toTimeZone */ - public ZonedDateTime(LocalDateTime localDateTime, org.nanoboot.powerframework.datetime.TimeZone toTimeZone) { + private ZonedDateTime(LocalDateTime localDateTime, + TimeZone toTimeZone) { super(localDateTime.getYear(), localDateTime.getMonth(), localDateTime.getDay(), localDateTime.getHour(), localDateTime.getMinute(), localDateTime.getSecond(), localDateTime.getMillisecond()); String stringRepresentationOfLocalDateTime = localDateTime.toString(); - TimeZone timeZoneForUniversalTime = new org.nanoboot.powerframework.datetime.TimeZone("UTC"); - String stringRepresentationOfZonedDateTimeWithUniversalTimeZone = org.nanoboot.powerframework.datetime.ZonedDateTime.convertDateTimeFromOneTimeZoneToAnother( + TimeZone timeZoneForUniversalTime = new TimeZone("UTC"); + String stringRepresentationOfZonedDateTimeWithUniversalTimeZone = ZonedDateTime.convertDateTimeFromOneTimeZoneToAnother( stringRepresentationOfLocalDateTime, toTimeZone, timeZoneForUniversalTime @@ -86,34 +137,14 @@ public final class ZonedDateTime extends DateTime { * @param zonedDateTime * @param newTimeZone */ - public ZonedDateTime(ZonedDateTime zonedDateTime, org.nanoboot.powerframework.datetime.TimeZone newTimeZone) { + public ZonedDateTime(ZonedDateTime zonedDateTime, + TimeZone newTimeZone) { super(ZonedDateTime.convertDateTimeFromOneTimeZoneToAnother(zonedDateTime.toString(), zonedDateTime.timeZone, newTimeZone)); this.universalDateTime = zonedDateTime.toUniversalDateTime(); this.timeZone = newTimeZone; } - /** - * - * @param dateTimeInString - * @param oldTimeZone - * @param newTimeZone - * - * @return String representation from the given String, but old time zone is - * changed to new time zone. - */ - static String convertDateTimeFromOneTimeZoneToAnother(String dateTimeInString, org.nanoboot.powerframework.datetime.TimeZone oldTimeZone, org.nanoboot.powerframework.datetime.TimeZone newTimeZone) { - - java.time.LocalDateTime localDateTime = java.time.LocalDateTime.parse(dateTimeInString, dateTimeFormatter); - - ZoneId oldZoneID = ZoneId.of(oldTimeZone.getTimeZoneID()); - java.time.ZonedDateTime oldZonedDateTime = localDateTime.atZone(oldZoneID); - - ZoneId newZoneId = ZoneId.of(newTimeZone.getTimeZoneID()); - java.time.ZonedDateTime newZonedDateTime = oldZonedDateTime.withZoneSameInstant(newZoneId); - return dateTimeFormatter.format(newZonedDateTime); - } - /** * * @return time zone of this ZonedDateTime @@ -122,6 +153,16 @@ public final class ZonedDateTime extends DateTime { return timeZone; } + /** + * + * @param duration + * + * @return + */ + public ZonedDateTime plusDuration(Duration duration) { + return new Period(this, duration).getEndZonedDateTime(); + } + /** * * @return a UniversalDateTime instance from this object @@ -135,16 +176,17 @@ public final class ZonedDateTime extends DateTime { * @return a LocalDateTime instance from this object */ public LocalDateTime toLocalDateTime() { - return new LocalDateTime(this); + return LocalDateTime.removeTimeZone(this); } /** * * @param newTimeZone + * * @return a ZonedDateTime instance from this object with the given new time * zone. */ - public ZonedDateTime toZonedDateTime(org.nanoboot.powerframework.datetime.TimeZone newTimeZone) { + public ZonedDateTime toZonedDateTime(TimeZone newTimeZone) { return new ZonedDateTime(this, newTimeZone); } diff --git a/power-time/src/main/java/org/nanoboot/powerframework/time/utils/AbstractValidator.java b/power-time/src/main/java/org/nanoboot/powerframework/time/utils/AbstractValidator.java new file mode 100644 index 0000000..b7771be --- /dev/null +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/utils/AbstractValidator.java @@ -0,0 +1,37 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.time.utils; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public abstract class AbstractValidator { + + static boolean isInBound(TimeUnit timeUnit, + int value) { + return (value >= timeUnit.getLowerBound()) && (value <= timeUnit.getHigherBound()); + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/datetime/DateUnitsValidator.java b/power-time/src/main/java/org/nanoboot/powerframework/time/utils/DateUnitsValidator.java similarity index 50% rename from src/main/java/org/nanoboot/powerframework/datetime/DateUnitsValidator.java rename to power-time/src/main/java/org/nanoboot/powerframework/time/utils/DateUnitsValidator.java index 2f941d6..6efbc8e 100644 --- a/src/main/java/org/nanoboot/powerframework/datetime/DateUnitsValidator.java +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/utils/DateUnitsValidator.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,17 +18,19 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.datetime; +package org.nanoboot.powerframework.time.utils; import java.util.ArrayList; -import org.nanoboot.powerframework.PowerRuntimeException; +import org.nanoboot.powerframework.core.PowerException; +import org.nanoboot.powerframework.time.moment.LocalDate; /** * Validates date units. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ -class DateUnitsValidator { +public class DateUnitsValidator extends AbstractValidator { private static final int MONTHLOWERBOUND = 1; private static final int MONTHHIGHERBOUND = 12; @@ -36,96 +38,136 @@ class DateUnitsValidator { private static final int DAYHIGHERBOUND = 31; private static final int MAXIMUMDAYFORFEBRUARYANDLEAPYEAR = 29; private static final int MAXIMUMDAYFORFEBRUARYANDNOTLEAPYEAR = 28; + private static final ArrayList LIST_OF_MONTH_HAVING_MAXIMUM_DAY_31 = new ArrayList<>(); - /** - * Constructor + static { + LIST_OF_MONTH_HAVING_MAXIMUM_DAY_31.add(1); + LIST_OF_MONTH_HAVING_MAXIMUM_DAY_31.add(3); + LIST_OF_MONTH_HAVING_MAXIMUM_DAY_31.add(5); + LIST_OF_MONTH_HAVING_MAXIMUM_DAY_31.add(7); + LIST_OF_MONTH_HAVING_MAXIMUM_DAY_31.add(8); + LIST_OF_MONTH_HAVING_MAXIMUM_DAY_31.add(10); + LIST_OF_MONTH_HAVING_MAXIMUM_DAY_31.add(12); + } + + + /* + * Checks input data for date. * - * Not meant to be instantiated. + * @param year + * @param month + * @param day + * @exception PowerRuntimeException if input data for date are invalid or + * have wrong combination.
+ * This will throw PowerRuntimeException: + * {@code new LocalDateTime(2015,2,29)}
+ * This will throw PowerRuntimeException: + * {@code new LocalDateTime(2013,6,31)}
+ * This will not throw PowerRuntimeException: + * {@code new LocalDateTime(2013,6,30)}
*/ - private DateUnitsValidator() { + /** + * + * @param year year value + * @param month month value + * @param day day value + */ + public static void validate(int year, + int month, + int day) { + if(!DateUnitsValidator.isMonthValid(month)) { + throw new TimeException("Month " + month + " is not valid."); + } + if(!DateUnitsValidator.isDayValid(day)) { + throw new TimeException("Day " + day + " is not valid."); + } + if(!DateUnitsValidator.hasDateValidCombination(year, month, day)) { + throw new TimeException("Date has not valid combination."); + + } } /** * Checks if month has valid format. * - * @param month + * @param month 1 to 12 + * * @return Result of this control. */ static boolean isMonthValid(int month) { - return (month >= MONTHLOWERBOUND) && (month <= MONTHHIGHERBOUND); + return DateUnitsValidator.isInBound(TimeUnit.MONTH, month); } /** * Checks if day is not more than the highest possible one- 31. * - * @param day + * @param day 1 to 31 + * * @return Result of this control. */ static boolean isDayValid(int day) { - return (day >= DAYLOWERBOUND) && (day <= DAYHIGHERBOUND); + return DateUnitsValidator.isInBound(TimeUnit.DAY, day); } /** * Checks if date has valid combination. * - * @param year - * @param month - * @param day + * @param year year value + * @param month month value + * @param day day value * * @return true if the date combination is valid, otherwise false. */ - static boolean hasDateValidCombination(int year, int month, int day) { + public static boolean hasDateValidCombination(int year, int month, int day) { return day <= getMaximumDay(year, month); } /** * - * @param year - * @param month + * @param year year value + * @param month month value + * * @return maximum day for the given month in the given year. - * @exception PowerRuntimeException if month is out of range and is invalid. + * + * @throws PowerException if month is out of range and is invalid. */ - private static int getMaximumDay(int year, int month) {//NOSONAR - if (!isMonthValid(month)) { - throw new PowerRuntimeException("Month is not valid."); + private static int getMaximumDay(int year, + int month) {//NOSONAR + if(!isMonthValid(month)) { + throw new TimeException("Month is not valid."); } - if (hasMonth31Days(month)) { + if(hasMonth31Days(month)) { return 31; } - if (hasMonth30Days(month)) { + if(hasMonth30Days(month)) { return 30; } - if (hasMonth29Days(year, month)) { + if(hasMonth29Days(year, month)) { return MAXIMUMDAYFORFEBRUARYANDLEAPYEAR; } - if (hasMonth28Days(year, month)) { + if(hasMonth28Days(year, month)) { return MAXIMUMDAYFORFEBRUARYANDNOTLEAPYEAR; } - throw new PowerRuntimeException(year + " " + month + " " + "I am not able to find out the maximum day for the given year and month."); + throw new TimeException(year + " " + month + " " + "I am not able to find out the maximum day for the given year and month."); } /** * - * @param month + * @param month month value + * * @return true if the given month in the given year has 31 days, otherwise * false. */ private static boolean hasMonth31Days(int month) { - ArrayList monthWithMaximumDay31 = new ArrayList<>(); - monthWithMaximumDay31.add(1); - monthWithMaximumDay31.add(3); - monthWithMaximumDay31.add(5); - monthWithMaximumDay31.add(7); - monthWithMaximumDay31.add(8); - monthWithMaximumDay31.add(10); - monthWithMaximumDay31.add(12); - return monthWithMaximumDay31.contains(month); + + return LIST_OF_MONTH_HAVING_MAXIMUM_DAY_31.contains(month); } /** * - * @param month + * @param month month value + * * @return true if the given month in the given year has 30 days, otherwise * false. */ @@ -135,8 +177,9 @@ class DateUnitsValidator { /** * - * @param year - * @param month + * @param year year value + * @param month month value + * * @return true if the given month in the given year has 29 days, otherwise * false. */ @@ -146,8 +189,9 @@ class DateUnitsValidator { /** * - * @param year - * @param month + * @param year year value + * @param month month value + * * @return true if the given month in the given year has 28 days, otherwise * false. */ @@ -155,4 +199,11 @@ class DateUnitsValidator { return (month == 2) && (!LocalDate.isYearLeap(year)); } + /** + * Constructor + * + * Not meant to be instantiated. + */ + private DateUnitsValidator() { + } } diff --git a/power-time/src/main/java/org/nanoboot/powerframework/time/utils/LocalSettings.java b/power-time/src/main/java/org/nanoboot/powerframework/time/utils/LocalSettings.java new file mode 100644 index 0000000..5b07e4d --- /dev/null +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/utils/LocalSettings.java @@ -0,0 +1,55 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.time.utils; + +import org.nanoboot.powerframework.time.moment.TimeZone; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class LocalSettings { + + private static TimeZone timeZone = new TimeZone("UTC"); + + /** + * + * @param timeZoneIn TimeZone instance + */ + public static void setLocalTimeZone(TimeZone timeZoneIn) { + timeZone = timeZoneIn; + } + + /** + * + * @return TimeZone instance + */ + public static TimeZone getLocalTimeZone() { + return timeZone; + } + + private LocalSettings() { + } + +} diff --git a/power-time/src/main/java/org/nanoboot/powerframework/time/utils/RandomDateTimeUnitsGenerator.java b/power-time/src/main/java/org/nanoboot/powerframework/time/utils/RandomDateTimeUnitsGenerator.java new file mode 100644 index 0000000..d473426 --- /dev/null +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/utils/RandomDateTimeUnitsGenerator.java @@ -0,0 +1,31 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.time.utils; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +class RandomDateTimeUnitsGenerator { + +} diff --git a/power-time/src/main/java/org/nanoboot/powerframework/time/utils/RemainingTimeCalculator.java b/power-time/src/main/java/org/nanoboot/powerframework/time/utils/RemainingTimeCalculator.java new file mode 100644 index 0000000..740f19a --- /dev/null +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/utils/RemainingTimeCalculator.java @@ -0,0 +1,68 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.time.utils; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +class RemainingTimeCalculator { + private long startNanoTime = 0; + private long total; + private long done = 0; + + public RemainingTimeCalculator(final int total) { + this.total = total; + this.start(); + } + private void start() { + this.startNanoTime = System.nanoTime(); + } + + private boolean started() { + return this.startNanoTime != 0; + } + public long elapsedSecondSinceStart() { + return (System.nanoTime() - this.startNanoTime) / 1000000000; + } + + public void nextDone() { + this.done++; + if (this.done > this.total) { + System.err.println("done is greater than total: " + "done=" + this.done + ", total=" + this.total); + } + } + + public long remainingSecondsUntilEnd() { + long remains = this.total - this.done; + long remainsSeconds = (this.elapsedSecondSinceStart() / this.done) * remains; + return remainsSeconds; + } + + public long getDoneCount() { + return this.done; + } + + public String getMessage() { + return "Time elapsed: " + this.elapsedSecondSinceStart() + " seconds. Time left: " + this.remainingSecondsUntilEnd() + " seconds. Done: " + this.getDoneCount() + " tasks."; + } +} diff --git a/src/main/java/org/nanoboot/powerframework/PowerRuntimeException.java b/power-time/src/main/java/org/nanoboot/powerframework/time/utils/TimeException.java similarity index 75% rename from src/main/java/org/nanoboot/powerframework/PowerRuntimeException.java rename to power-time/src/main/java/org/nanoboot/powerframework/time/utils/TimeException.java index d18127f..b18c8cc 100644 --- a/src/main/java/org/nanoboot/powerframework/PowerRuntimeException.java +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/utils/TimeException.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,21 +18,23 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework; +package org.nanoboot.powerframework.time.utils; + +import org.nanoboot.powerframework.core.PowerException; /** - * Exception for Power library + * * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ -public class PowerRuntimeException extends RuntimeException { +public class TimeException extends PowerException { /** - * Constructor with message. * * @param message */ - public PowerRuntimeException(String message) { + public TimeException(String message) { super(message); } diff --git a/power-time/src/main/java/org/nanoboot/powerframework/time/utils/TimeUnit.java b/power-time/src/main/java/org/nanoboot/powerframework/time/utils/TimeUnit.java new file mode 100644 index 0000000..9954fba --- /dev/null +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/utils/TimeUnit.java @@ -0,0 +1,203 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.time.utils; + +import org.nanoboot.powerframework.random.generators.RandomGenerator; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public enum TimeUnit { + + /** + * + */ + YEAR("year", 1, Integer.MIN_VALUE, Integer.MAX_VALUE), + + /** + * + */ + MONTH("month", 2, 1, 12), + + /** + * + */ + DAY("day", 3, 1, 31), + + /** + * + */ + HOUR("hour", 4, 0, 23), + + /** + * + */ + MINUTE("minute", 5, 0, 59), + + /** + * + */ + SECOND("second", 6, 0, 59), + + /** + * + */ + MILLISECOND("millisecond", 7, 0, 999); + private final String description; + private final int asNumber; + private final int lowerBound; + private final int higherBound; + + /** + * + * @param timeUnitFrom + * @param timeUnitTo + * + * @return + */ + public static TimeUnit getRandom(TimeUnit timeUnitFrom, + TimeUnit timeUnitTo) { + RandomGenerator randomGenerator = RandomGenerator.getDefaultImplStatic(); + return TimeUnit.getFromNumber(randomGenerator.nextInt(timeUnitFrom.asNumber, timeUnitTo.asNumber)); + } + + TimeUnit(String description, + int asNumber, + int lowerBound, + int higherBound) { + this.description = description; + this.asNumber = asNumber; + this.lowerBound = lowerBound; + this.higherBound = higherBound; + } + + /** + * + * @return + */ + public String getDescription() { + return this.description; + } + + /** + * + * @return + */ + public TimeUnit getSmallerUnit() { + switch (this) { + case YEAR: + return MONTH; + case MONTH: + return DAY; + case DAY: + return HOUR; + case HOUR: + return MINUTE; + case MINUTE: + return SECOND; + case SECOND: + return MILLISECOND; + default: + throw new TimeException("Can't get smaller time unit."); + } + } + + /** + * + * @return + */ + public TimeUnit getBiggerUnit() { + switch (this) { + + case MONTH: + return YEAR; + case DAY: + return MONTH; + case HOUR: + return DAY; + case MINUTE: + return HOUR; + case SECOND: + return MINUTE; + case MILLISECOND: + return SECOND; + default: + throw new TimeException("Can't get bigger time unit."); + } + } + + /** + * + * @param asNumber + * + * @return + */ + public static TimeUnit getFromNumber(int asNumber) { + switch (asNumber) { + case 1: + return YEAR; + case 2: + return MONTH; + case 3: + return DAY; + case 4: + return HOUR; + case 5: + return MINUTE; + case 6: + return SECOND; + case 7: + return MILLISECOND; + default: + throw new TimeException("Can't get TimeUnit from number."); + } + } + + /** + * + * @return + */ + public int getLowerBound() { + return lowerBound; + } + + /** + * + * @return + */ + public int getHigherBound() { + return higherBound; + } + + /** + * + * @return + */ + public int getRandomValue() { + int from = this == YEAR ? 0 : this.lowerBound; + int to = this == YEAR ? 3000 : this.higherBound; + return RandomGenerator.getDefaultImplStatic().nextInt(from, to); + } + +} diff --git a/power-time/src/main/java/org/nanoboot/powerframework/time/utils/TimeUnitConvertor.java b/power-time/src/main/java/org/nanoboot/powerframework/time/utils/TimeUnitConvertor.java new file mode 100644 index 0000000..26f4520 --- /dev/null +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/utils/TimeUnitConvertor.java @@ -0,0 +1,96 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.time.utils; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class TimeUnitConvertor { + + private static final long DAYHASHOURS = 24; + private static final long HOURHASMINUTES = 60; + private static final long MINUTEHASSECONDS = 60; + private static final long SECONDHASMILLISECONDS = 1000; + + /** + * + * @param timeUnitFrom DAY,HOUR,MINUTE,SECOND,MILLISECOND + * @param timeUnitTo DAY,HOUR,MINUTE,SECOND,MILLISECOND umst be smaller than + * timeUnitFrom + * @param value + * + * @return + */ + public static long convert(long value, + TimeUnit timeUnitFrom, + TimeUnit timeUnitTo) { + + if(timeUnitFrom == timeUnitTo) { + return value; + } + + long returnValue = value; + + TimeUnit tempTimeUnit = timeUnitFrom; + + while (true) { + tempTimeUnit = tempTimeUnit.getSmallerUnit(); + if(tempTimeUnit != TimeUnit.DAY) { + returnValue *= TimeUnitConvertor.timeUnitHasSmallerTimeUnits(tempTimeUnit.getBiggerUnit()); + } + if(timeUnitTo == tempTimeUnit) { + return returnValue; + } + + if(timeUnitTo == TimeUnit.MILLISECOND && tempTimeUnit == timeUnitTo) { + break; + } + + } + + throw new TimeException("Can't convert value " + value + " " + " from unit " + timeUnitFrom + " to unit " + timeUnitTo); + } + + private static long timeUnitHasSmallerTimeUnits(TimeUnit timeUnit) { + switch (timeUnit) { + case DAY: + return DAYHASHOURS; + case HOUR: + return HOURHASMINUTES; + case MINUTE: + return MINUTEHASSECONDS; + case SECOND: + return SECONDHASMILLISECONDS; + } + throw new TimeException("Can't get smaller time units of time unit " + timeUnit.getDescription()); + } + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private TimeUnitConvertor() { + } +} diff --git a/src/main/java/org/nanoboot/powerframework/datetime/TimeUnitsValidator.java b/power-time/src/main/java/org/nanoboot/powerframework/time/utils/TimeUnitsValidator.java similarity index 51% rename from src/main/java/org/nanoboot/powerframework/datetime/TimeUnitsValidator.java rename to power-time/src/main/java/org/nanoboot/powerframework/time/utils/TimeUnitsValidator.java index 44f03b7..3b3628b 100644 --- a/src/main/java/org/nanoboot/powerframework/datetime/TimeUnitsValidator.java +++ b/power-time/src/main/java/org/nanoboot/powerframework/time/utils/TimeUnitsValidator.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,23 +18,85 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.datetime; - -import org.nanoboot.powerframework.PowerRuntimeException; +package org.nanoboot.powerframework.time.utils; /** * Validates time units. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * + * @author Robert Vokac + * @since 0.0.0 */ -class TimeUnitsValidator { +public class TimeUnitsValidator extends AbstractValidator { - private static final int HOURLOWERBOUND = 0; - private static final int HOURHIGHERBOUND = 23; - private static final int MINUTEORSECONDLOWERBOUND = 0; - private static final int MINUTEORSECONDHIGHERBOUND = 59; - private static final int MILLISECONDLOWERBOUND = 0; - private static final int MILLISECONDHIGHERBOUND = 999; + /** + * + * @param hour + * @param minute + * @param second + * @param millisecond + */ + public static void validate(int hour, + int minute, + int second, + int millisecond) { + if(!TimeUnitsValidator.isHourValid(hour)) { + throw new TimeException("Hour is not valid."); + } + if(!TimeUnitsValidator.isMinuteValid(minute)) { + throw new TimeException("Minute is not valid."); + } + if(!TimeUnitsValidator.isSecondValid(second)) { + throw new TimeException("Second is not valid."); + } + if(!TimeUnitsValidator.isMillisecondValid(millisecond)) { + throw new TimeException("Millisecond is not valid."); + } + } + + /** + * Checks if hour has valid format. + * + * @param hour + * + * @return Result of this control. + */ + static boolean isHourValid(int hour) { + return isInBound(TimeUnit.HOUR, hour); + } + + /** + * Checks if minute has valid format. + * + * @param minute + * + * @return Result of this control. + */ + static boolean isMinuteValid(int minute) { + return isInBound(TimeUnit.MINUTE, minute); + } + + /** + * Checks if second has valid format. + * + * @param second + * + * @return Result of this control. + */ + static boolean isSecondValid(int second) { + return isInBound(TimeUnit.SECOND, second); + } + + /** + * Checks if millisecond has valid format. + * + * @param millisecond + * + * @return Result of this control. + */ + static boolean isMillisecondValid(int millisecond) { + return isInBound(TimeUnit.MILLISECOND, millisecond); + } /** * Constructor @@ -43,76 +105,4 @@ class TimeUnitsValidator { */ private TimeUnitsValidator() { } - - /** - * Checks if hour has valid format. - * - * @param hour - * @return Result of this control. - */ - static boolean isHourValid(int hour) { - return (hour >= HOURLOWERBOUND) && (hour <= HOURHIGHERBOUND); - } - - /** - * Checks if minuteOrSecond has valid format. - * - * @param minuteOrSecond - * @return Result of this control. - */ - private static boolean isMinuteOrSecondValid(int minuteOrSecond) { - return (minuteOrSecond >= MINUTEORSECONDLOWERBOUND) && (minuteOrSecond <= MINUTEORSECONDHIGHERBOUND); - } - - /** - * Checks if minute has valid format. - * - * @param minute - * @return Result of this control. - */ - static boolean isMinuteValid(int minute) { - return isMinuteOrSecondValid(minute); - } - - /** - * Checks if second has valid format. - * - * @param second - * @return Result of this control. - */ - static boolean isSecondValid(int second) { - return isMinuteOrSecondValid(second); - } - - /** - * Checks if millisecond has valid format. - * - * @param millisecond - * @return Result of this control. - */ - static boolean isMillisecondValid(int millisecond) { - return (millisecond >= MILLISECONDLOWERBOUND) && (millisecond <= MILLISECONDHIGHERBOUND); - } - - /** - * Checks if all the given time values are valid. - * - * @param hour - * @param minute - * @param second - * @param millisecond - * * @return Result of this control. - */ - static boolean areAllTimeUnitsValid(int hour, int minute, int second, int millisecond) { - return isHourValid(hour) - && (isMinuteValid(minute)) - && (isSecondValid(second)) - && (isMillisecondValid(millisecond)); - } - - static void checkInputValuesForTimeAndIfThereIsAnInvalidOneThrowException(int hour, int minute, int second, int millisecond) { - if (!areAllTimeUnitsValid(hour, minute, second, millisecond)) { - throw new PowerRuntimeException("One or more values of time units have invalid format."); - } - } } diff --git a/power-time/src/main/resources/.gitkeep b/power-time/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-time/src/test/java/org/nanoboot/powerframework/time/duration/DurationTest.java b/power-time/src/test/java/org/nanoboot/powerframework/time/duration/DurationTest.java new file mode 100644 index 0000000..cdf87ce --- /dev/null +++ b/power-time/src/test/java/org/nanoboot/powerframework/time/duration/DurationTest.java @@ -0,0 +1,877 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.time.duration; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class DurationTest { +// +// /** +// +// */ +// public DurationTest() { +// } +// +// /** +// Test of constructor, of class Duration. +// */ +// @Test +// public void TestDuration_5Args_ThereShouldBeThrownNoPowerRuntimeException() { +// //arrange +// boolean isExceptionThrown = false; +// //act +// try { +// Duration duration = new Duration(23, 5, 3, 43, 97); +// } catch (PowerException e) { +// isExceptionThrown = true; +// } +// //assert +// if(isExceptionThrown) { +// fail("There should be thrown no PowerRuntimeException"); +// } +// } +// +// /** +// Test of constructor, of class Duration. +// */ +// @Test +// public void TestDuration_5Args_ThereShouldBeThrownPowerRuntimeException() { +// //arrange +// boolean isExceptionThrown = false; +// //act +// try { +// Duration duration = new Duration(23, 5, 3, 143, 97); +// } catch (PowerException e) { +// isExceptionThrown = true; +// } +// //assert +// if(!isExceptionThrown) { +// fail("There should be thrown PowerRuntimeException"); +// } +// } +// +// /** +// Test of constructor, of class Duration. +// */ +// @Test +// public void TestDuration_5Args_ThereShouldBeReturnedIsPositive() { +// //arrange +// boolean expectedValue = true; +// boolean returnedValue; +// Duration duration = new Duration(23, 5, 3, 43, 97); +// //act +// returnedValue = duration.isPositive(); +// //assert +// assertEquals(expectedValue, returnedValue); +// } +// +// /** +// Test of constructor, of class Duration. +// */ +// @Test +// public void TestDuration_6Args_ThereShouldBeReturnedIsPositive() { +// //arrange +// boolean expectedValue = true; +// boolean returnedValue; +// Duration duration = new Duration(true, 23, 5, 3, 43, 97); +// //act +// returnedValue = duration.isPositive(); +// //assert +// assertEquals(expectedValue, returnedValue); +// } +// +// /** +// Test of constructor, of class Duration. +// */ +// @Test +// public void TestDuration_6Args_ThereShouldBeReturnedIsNotPositive() { +// //arrange +// boolean expectedValue = false; +// boolean returnedValue; +// Duration duration = new Duration(false, 23, 5, 3, 43, 97); +// //act +// returnedValue = duration.isPositive(); +// //assert +// assertEquals(expectedValue, returnedValue); +// } +// +// /** +// Test of constructor, of class Duration. +// */ +// @Test +// public void TestDuration_StringArg() { +// //arrange +// String argString = "+00023:05:03:43:097"; +// String expectedString = "+23:5:3:43:97"; +// String returnedString; +// +// Duration duration = new Duration(argString); +// //act +// returnedString = duration.toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of constructor, of class Duration. +// */ +// @Test +// public void TestDuration_StringArg_ThereShouldBeThrownPowerRuntimeException() { +// //arrange +// boolean isExceptionThrown = false; +// //act +// try { +// String argString = "+23:5:60:43:97"; +// Duration duration = new Duration(argString); +// } catch (PowerException e) { +// isExceptionThrown = true; +// } +// //assert +// if(!isExceptionThrown) { +// fail("There should be thrown PowerRuntimeException"); +// } +// } +// +// /** +// Test of between method, of class Duration. +// */ +// @Test +// public void testBetween1_UniversalDateTime_UniversalDateTime() { +// //arrange +// UniversalDateTime startUniversalDateTime = new UniversalDateTime(1949, 8, 6, 4, 23, 7, 654); +// UniversalDateTime endUniversalDateTime = new UniversalDateTime(2007, 4, 21, 9, 17, 58, 954); +// String expectedString = "+21077:4:54:51:300"; +// String returnedString; +// //act +// returnedString = Duration.between(startUniversalDateTime, endUniversalDateTime).toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of between method, of class Duration. +// */ +// @Test +// public void testBetween2_UniversalDateTime_UniversalDateTime() { +// //arrange +// UniversalDateTime startUniversalDateTime = new UniversalDateTime(2007, 4, 21, 9, 17, 58, 954); +// UniversalDateTime endUniversalDateTime = new UniversalDateTime(1949, 8, 6, 4, 23, 7, 654); +// String expectedString = "-21077:4:54:51:300"; +// String returnedString; +// //act +// returnedString = Duration.between(startUniversalDateTime, endUniversalDateTime).toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of between method, of class Duration. +// */ +// @Test +// public void testBetween1_ZonedDateTime_ZonedDateTime() { +// //arrange +// LocalDateTime localDateTime = new LocalDateTime(2016, 10, 29, 11, 19, 34, 276); +// ZonedDateTime startZonedDateTime = new ZonedDateTime(localDateTime, new TimeZone("Europe/Prague")); +// ZonedDateTime endZonedDateTime = new ZonedDateTime(localDateTime, new TimeZone("Australia/Sydney")); +// String expectedString = "-0:9:0:0:0"; +// String returnedString; +// //act +// returnedString = Duration.between(startZonedDateTime, endZonedDateTime).toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of between method, of class Duration. +// */ +// @Test +// public void testBetween2_ZonedDateTime_ZonedDateTime() { +// //arrange +// LocalDateTime localDateTime = new LocalDateTime(2016, 10, 29, 11, 19, 34, 276); +// ZonedDateTime startZonedDateTime = new ZonedDateTime(localDateTime, new TimeZone("Australia/Sydney")); +// ZonedDateTime endZonedDateTime = new ZonedDateTime(localDateTime, new TimeZone("Europe/Prague")); +// String expectedString = "+0:9:0:0:0"; +// String returnedString; +// //act +// returnedString = Duration.between(startZonedDateTime, endZonedDateTime).toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of ofDays method, of class Duration. +// */ +// @Test +// public void testOfDays() { +// //arrange +// int days = 13; +// +// Duration duration = Duration.ofDays(days); +// String expectedString = "+13:0:0:0:0"; +// String returnedString; +// //act +// returnedString = duration.toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of ofHours method, of class Duration. +// */ +// @Test +// public void testOfHours() { +// //arrange +// int hours = 17; +// +// Duration duration = Duration.ofHours(hours); +// String expectedString = "+0:17:0:0:0"; +// String returnedString; +// //act +// returnedString = duration.toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of ofMinutes method, of class Duration. +// */ +// @Test +// public void testOfMinutes() { +// //arrange +// int minutes = 42; +// +// Duration duration = Duration.ofMinutes(minutes); +// String expectedString = "+0:0:42:0:0"; +// String returnedString; +// //act +// returnedString = duration.toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of ofSeconds method, of class Duration. +// */ +// @Test +// public void testOfSeconds() { +// //arrange +// int seconds = 9; +// +// Duration duration = Duration.ofSeconds(seconds); +// String expectedString = "+0:0:0:9:0"; +// String returnedString; +// //act +// returnedString = duration.toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of ofMilliseconds method, of class Duration. +// */ +// @Test +// public void testOfMilliseconds() { +// //arrange +// int milliseconds = 4; +// +// Duration duration = Duration.ofMilliseconds(milliseconds); +// String expectedString = "+0:0:0:0:4"; +// String returnedString; +// //act +// returnedString = duration.toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of fromUniversalDateTimePlusDurationCreateNewUniversalDateTime +// method, of class Duration. +// */ +// @Test +// public void testFromUniversalDateTimePlusDurationCreateNewUniversalDateTime() { +// //arrange +// UniversalDateTime universalDateTime = new UniversalDateTime(2007, 4, 21, 9, 17, 58, 954); +// Duration duration = Duration.ofHours(7); +// String expectedString = "2007-04-21 16:17:58:954"; +// String returnedString; +// //act +// returnedString = Duration.fromUniversalDateTimePlusDurationCreateNewUniversalDateTime(universalDateTime, duration).toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of fromUniversalDateTimeMinusDurationCreateNewUniversalDateTime +// method, of class Duration. +// */ +// @Test +// public void testFromUniversalDateTimeMinusDurationCreateNewUniversalDateTime() { +// //arrange +// UniversalDateTime universalDateTime = new UniversalDateTime(2007, 4, 21, 9, 17, 58, 954); +// Duration duration = Duration.ofHours(7); +// String expectedString = "2007-04-21 02:17:58:954"; +// String returnedString; +// //act +// returnedString = Duration.fromUniversalDateTimeMinusDurationCreateNewUniversalDateTime(universalDateTime, duration).toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of fromZonedDateTimePlusDurationCreateNewZonedDateTime method, of +// class Duration. +// */ +// @Test +// public void testFromZonedDateTimePlusDurationCreateNewZonedDateTime() { +// //arrange +// LocalDateTime localDateTime = new LocalDateTime(2007, 4, 21, 9, 17, 58, 954); +// TimeZone timeZone = new TimeZone("Australia/Sydney"); +// ZonedDateTime zonedDateTime = new ZonedDateTime(localDateTime, timeZone); +// Duration duration = Duration.ofHours(7); +// String expectedString = "2007-04-21 16:17:58:954"; +// String returnedString; +// //act +// returnedString = Duration.fromZonedDateTimePlusDurationCreateNewZonedDateTime(zonedDateTime, duration).toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of fromZonedDateTimeMinusDurationCreateNewZonedDateTime method, of +// class Duration. +// */ +// @Test +// public void testFromZonedDateTimeMinusDurationCreateNewZonedDateTime() { +// //arrange +// LocalDateTime localDateTime = new LocalDateTime(2007, 4, 21, 9, 17, 58, 954); +// TimeZone timeZone = new TimeZone("Australia/Sydney"); +// ZonedDateTime zonedDateTime = new ZonedDateTime(localDateTime, timeZone); +// Duration duration = Duration.ofHours(7); +// String expectedString = "2007-04-21 02:17:58:954"; +// String returnedString; +// //act +// returnedString = Duration.fromZonedDateTimeMinusDurationCreateNewZonedDateTime(zonedDateTime, duration).toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of getDays method, of class Duration. +// */ +// @Test +// public void testGetDays() { +// //arrange +// Duration duration = new Duration(23, 5, 3, 43, 97); +// long expectedDays = 23; +// long returnedDays; +// //act +// returnedDays = duration.getDays(); +// //assert +// assertEquals(expectedDays, returnedDays); +// } +// +// /** +// Test of getHours method, of class Duration. +// */ +// @Test +// public void testGetHours() { +// //arrange +// Duration duration = new Duration(23, 5, 3, 43, 97); +// int expectedHours = 5; +// int returnedHours; +// //act +// returnedHours = duration.getHours(); +// //assert +// assertEquals(expectedHours, returnedHours); +// } +// +// /** +// Test of getMinutes method, of class Duration. +// */ +// @Test +// public void testGetMinutes() { +// //arrange +// Duration duration = new Duration(23, 5, 3, 43, 97); +// int expectedMinutes = 3; +// int returnedMinutes; +// //act +// returnedMinutes = duration.getMinutes(); +// //assert +// assertEquals(expectedMinutes, returnedMinutes); +// } +// +// /** +// Test of getSeconds method, of class Duration. +// */ +// @Test +// public void testGetSeconds() { +// //arrange +// Duration duration = new Duration(23, 5, 3, 43, 97); +// int expectedSeconds = 43; +// int returnedSeconds; +// //act +// returnedSeconds = duration.getSeconds(); +// //assert +// assertEquals(expectedSeconds, returnedSeconds); +// } +// +// /** +// Test of getMilliseconds method, of class Duration. +// */ +// @Test +// public void testGetMilliseconds() { +// //arrange +// Duration duration = new Duration(23, 5, 3, 43, 97); +// int expectedMilliseconds = 97; +// int returnedMilliseconds; +// //act +// returnedMilliseconds = duration.getMilliseconds(); +// //assert +// assertEquals(expectedMilliseconds, returnedMilliseconds); +// } +// +// /** +// Test of isPositive method, of class Duration. +// */ +// @Test +// public void testIsPositive() { +// //arrange +// Duration duration = new Duration(false, 23, 5, 3, 43, 97); +// boolean expectedValue = false; +// boolean returnedValue; +// //act +// returnedValue = duration.isPositive(); +// //assert +// assertEquals(expectedValue, returnedValue); +// } +// +// /** +// Test of negated method, of class Duration. +// */ +// @Test +// public void testNegated() { +// //arrange +// Duration duration = new Duration(23, 5, 3, 43, 97); +// Duration negatedDuration; +// +// boolean expectedValue = false; +// boolean returnedValue; +// //act +// negatedDuration = duration.negated(); +// returnedValue = negatedDuration.isPositive(); +// //assert +// assertEquals(expectedValue, returnedValue); +// } +// +// /** +// Test of abs method, of class Duration. +// */ +// @Test +// public void testAbs() { +// //arrange +// Duration duration = new Duration(false, 23, 5, 3, 43, 97); +// Duration absDuration; +// +// boolean expectedValue = true; +// boolean returnedValue; +// //act +// absDuration = duration.abs(); +// returnedValue = absDuration.isPositive(); +// //assert +// assertEquals(expectedValue, returnedValue); +// } +// +// /** +// Test of plusDuration method, of class Duration. +// */ +// @Test +// public void testPlusDuration() { +// //arrange +// Duration duration = new Duration(12, 0, 0, 0, 0); +// Duration durationToAdd = new Duration(0, 5, 4, 2, 7); +// Duration returnedDuration; +// String expectedString = "+12:5:4:2:7"; +// String returnedString; +// +// //act +// returnedDuration = duration.plusDuration(durationToAdd); +// returnedString = returnedDuration.toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of plusDays method, of class Duration. +// */ +// @Test +// public void testPlusDays() { +// //arrange +// Duration duration = new Duration(12, 0, 0, 0, 0); +// long daysToAdd = 1; +// Duration returnedDuration; +// String expectedString = "+13:0:0:0:0"; +// String returnedString; +// +// //act +// returnedDuration = duration.plusDays(daysToAdd); +// returnedString = returnedDuration.toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of plusHours method, of class Duration. +// */ +// @Test +// public void testPlusHours() { +// //arrange +// Duration duration = new Duration(12, 0, 0, 0, 0); +// int hoursToAdd = 1; +// Duration returnedDuration; +// String expectedString = "+12:1:0:0:0"; +// String returnedString; +// +// //act +// returnedDuration = duration.plusHours(hoursToAdd); +// returnedString = returnedDuration.toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of plusMinutes method, of class Duration. +// */ +// @Test +// public void testPlusMinutes() { +// //arrange +// Duration duration = new Duration(12, 0, 0, 0, 0); +// int minutesToAdd = 1; +// Duration returnedDuration; +// String expectedString = "+12:0:1:0:0"; +// String returnedString; +// +// //act +// returnedDuration = duration.plusMinutes(minutesToAdd); +// returnedString = returnedDuration.toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of plusSeconds method, of class Duration. +// */ +// @Test +// public void testPlusSeconds() { +// //arrange +// Duration duration = new Duration(12, 0, 0, 0, 0); +// int secondsToAdd = 1; +// Duration returnedDuration; +// String expectedString = "+12:0:0:1:0"; +// String returnedString; +// +// //act +// returnedDuration = duration.plusSeconds(secondsToAdd); +// returnedString = returnedDuration.toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of plusMilliseconds method, of class Duration. +// */ +// @Test +// public void testPlusMilliseconds() { +// //arrange +// Duration duration = new Duration(12, 0, 0, 0, 0); +// int millisecondsToAdd = 1; +// Duration returnedDuration; +// String expectedString = "+12:0:0:0:1"; +// String returnedString; +// +// //act +// returnedDuration = duration.plusMilliseconds(millisecondsToAdd); +// returnedString = returnedDuration.toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of minusDuration method, of class Duration. +// */ +// @Test +// public void testMinusDuration() { +// //arrange +// Duration duration = new Duration(12, 5, 4, 2, 7); +// Duration durationToSubtract = new Duration(0, 5, 4, 2, 7); +// Duration returnedDuration; +// String expectedString = "+12:0:0:0:0"; +// String returnedString; +// +// //act +// returnedDuration = duration.minusDuration(durationToSubtract); +// returnedString = returnedDuration.toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of minusDays method, of class Duration. +// */ +// @Test +// public void testMinusDays() { +// //arrange +// Duration duration = new Duration(12, 5, 4, 2, 7); +// long daysToSubtract = 1; +// Duration returnedDuration; +// String expectedString = "+11:5:4:2:7"; +// String returnedString; +// +// //act +// returnedDuration = duration.minusDays(daysToSubtract); +// returnedString = returnedDuration.toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of minusHours method, of class Duration. +// */ +// @Test +// public void testMinusHours() { +// //arrange +// Duration duration = new Duration(12, 5, 4, 2, 7); +// int hoursToSubtract = 1; +// Duration returnedDuration; +// String expectedString = "+12:4:4:2:7"; +// String returnedString; +// +// //act +// returnedDuration = duration.minusHours(hoursToSubtract); +// returnedString = returnedDuration.toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of minusMinutes method, of class Duration. +// */ +// @Test +// public void testMinusMinutes() { +// //arrange +// Duration duration = new Duration(12, 5, 4, 2, 7); +// int minutesToSubtract = 1; +// Duration returnedDuration; +// String expectedString = "+12:5:3:2:7"; +// String returnedString; +// +// //act +// returnedDuration = duration.minusMinutes(minutesToSubtract); +// returnedString = returnedDuration.toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of minusSeconds method, of class Duration. +// */ +// @Test +// public void testMinusSeconds() { +// //arrange +// Duration duration = new Duration(12, 5, 4, 2, 7); +// int secondsToSubtract = 1; +// Duration returnedDuration; +// String expectedString = "+12:5:4:1:7"; +// String returnedString; +// +// //act +// returnedDuration = duration.minusSeconds(secondsToSubtract); +// returnedString = returnedDuration.toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of minusMilliseconds method, of class Duration. +// */ +// @Test +// public void testMinusMilliseconds() { +// //arrange +// Duration duration = new Duration(12, 5, 4, 2, 7); +// int millisecondsToSubtract = 1; +// Duration returnedDuration; +// String expectedString = "+12:5:4:2:6"; +// String returnedString; +// +// //act +// returnedDuration = duration.minusMilliseconds(millisecondsToSubtract); +// returnedString = returnedDuration.toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of toTotalDays method, of class Duration. +// */ +// @Test +// public void testToTotalDays() { +// //arrange +// Duration duration = new Duration(14, 9, 17, 53, 834); +// long expectedValue = 14; +// long returnedValue; +// //act +// returnedValue = (long) Math.floor(duration.toTotalDays()); +// //assert +// assertEquals(expectedValue, returnedValue); +// } +// +// /** +// Test of toTotalHours method, of class Duration. +// */ +// @Test +// public void testToTotalHours() { +// //arrange +// Duration duration = new Duration(14, 9, 17, 53, 834); +// long expectedValue = 345; +// long returnedValue; +// //act +// returnedValue = (long) Math.floor(duration.toTotalHours()); +// //assert +// assertEquals(expectedValue, returnedValue); +// } +// +// /** +// Test of toTotalMinutes method, of class Duration. +// */ +// @Test +// public void testToTotalMinutes() { +// //arrange +// Duration duration = new Duration(14, 9, 17, 53, 834); +// long expectedValue = 20717; +// long returnedValue; +// //act +// returnedValue = (long) Math.floor(duration.toTotalMinutes()); +// //assert +// assertEquals(expectedValue, returnedValue); +// } +// +// /** +// Test of toTotalSeconds method, of class Duration. +// */ +// @Test +// public void testToTotalSeconds() { +// //arrange +// Duration duration = new Duration(14, 9, 17, 53, 834); +// long expectedValue = 1243073; +// long returnedValue; +// //act +// returnedValue = (long) Math.floor(duration.toTotalSeconds()); +// //assert +// assertEquals(expectedValue, returnedValue); +// } +// +// /** +// Test of toTotalMilliseconds method, of class Duration. +// */ +// @Test +// public void testToTotalMilliseconds() { +// //arrange +// Duration duration = new Duration(14, 9, 17, 53, 834); +// long expectedValue = 1243073834; +// long returnedValue; +// //act +// returnedValue = (long) Math.floor(duration.toTotalMilliseconds()); +// //assert +// assertEquals(expectedValue, returnedValue); +// } +// +// /** +// Test of toJavaDuration method, of class Duration. +// */ +// @Test +// public void testToJavaDuration() { +// //arrange +// Duration duration = new Duration(14, 9, 17, 53, 834); +// long expectedTotalSeconds = (long) Math.floor(duration.toTotalSeconds()); +// long returnedSeconds; +// java.time.Duration javaDuration; +// //act +// javaDuration = duration.toJavaDuration(); +// returnedSeconds = javaDuration.getSeconds(); +// //assert +// assertEquals(expectedTotalSeconds, returnedSeconds); +// } +// +// /** +// Test of toString method, of class Duration. +// */ +// @Test +// public void testToString1_ConstructorWithLongArgUsed() { +// //arrange +// String expectedString = "+23:5:3:43:97"; +// String returnedString; +// long countOfTotalMilliseconds = 2005423097; +// +// Duration duration = new Duration(countOfTotalMilliseconds); +// //act +// returnedString = duration.toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of toString method, of class Duration. +// */ +// @Test +// public void testToString2_ConstructorWithLongArgUsed() { +// //arrange +// String expectedString = "-23:5:3:43:97"; +// String returnedString; +// long countOfTotalMilliseconds = -2005423097; +// +// Duration duration = new Duration(countOfTotalMilliseconds); +// //act +// returnedString = duration.toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +// +// /** +// Test of toString method, of class Duration. +// */ +// @Test +// public void testToString3_ConstructorWithLongArgUsed() { +// //arrange +// String expectedString = "+0:0:0:0:0"; +// String returnedString; +// long countOfTotalMilliseconds = 0; +// +// Duration duration = new Duration(countOfTotalMilliseconds); +// //act +// returnedString = duration.toString(); +// //assert +// assertEquals(expectedString, returnedString); +// } +} diff --git a/power-time/src/test/java/org/nanoboot/powerframework/time/duration/StopWatchTest.java b/power-time/src/test/java/org/nanoboot/powerframework/time/duration/StopWatchTest.java new file mode 100644 index 0000000..2d2588f --- /dev/null +++ b/power-time/src/test/java/org/nanoboot/powerframework/time/duration/StopWatchTest.java @@ -0,0 +1,279 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.time.duration; + +import static org.junit.Assert.assertEquals; + +import org.nanoboot.powerframework.time.utils.TimeUnit; +import org.junit.*; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class StopWatchTest { + + public StopWatchTest() { + } + + @BeforeClass + public static void setUpClass() { + } + + @AfterClass + public static void tearDownClass() { + } + + @Before + public void setUp() { + } + + @After + public void tearDown() { + } + + /** + * Test of getCurrentStopWatchState method, of class StopWatch. + */ + @Test + public void testGetStopWatchState_shouldBeClear() { + //arrange + StopWatch stopWatch = new StopWatch(); + StopWatchState expectedValue = StopWatchState.CLEAR; + StopWatchState returnedValue; + //act + returnedValue = stopWatch.getStopWatchState(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getCurrentStopWatchState method, of class StopWatch. + */ + @Test + public void testGetStopWatchState_shouldBeRunning() { + //arrange + StopWatch stopWatch = new StopWatch(); + StopWatchState expectedValue = StopWatchState.RUNNING; + StopWatchState returnedValue; + //act + stopWatch.start(); + returnedValue = stopWatch.getStopWatchState(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of clear method, of class StopWatch. + */ + @Test + public void testClear() { + //arrange + StopWatch stopWatch = new StopWatch(); + StopWatchState expectedValue = StopWatchState.CLEAR; + StopWatchState returnedValue; + //act + stopWatch.start(); + stopWatch.stop(); + stopWatch.start(); + stopWatch.stop(); + stopWatch.start(); + stopWatch.stop(); + stopWatch.clear(); + returnedValue = stopWatch.getStopWatchState(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of clear method, of class StopWatch. + */ + @Test + public void testClear2() { + //arrange + StopWatch stopWatch = new StopWatch(); + int expectedValue = 0; + int returnedValue; + //act + stopWatch.start(); + stopWatch.stop(); + stopWatch.start(); + stopWatch.stop(); + stopWatch.start(); + stopWatch.stop(); + stopWatch.clear(); + returnedValue = (int) stopWatch.getCurrentDuration().toTotal(TimeUnit.MILLISECOND); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of start method, of class StopWatch. + */ + @Test + public void testStart() { + //arrange + StopWatch stopWatch = new StopWatch(); + StopWatchState expectedValue = StopWatchState.RUNNING; + StopWatchState returnedValue; + //act + stopWatch.start(); + stopWatch.stop(); + stopWatch.start(); + stopWatch.stop(); + stopWatch.start(); + stopWatch.stop(); + stopWatch.start(); + returnedValue = stopWatch.getStopWatchState(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of start method, of class StopWatch. + */ + @Test + public void testStart2() { + //arrange + StopWatch stopWatch = new StopWatch(); + StopWatchState expectedValue = StopWatchState.RUNNING; + StopWatchState returnedValue; + //act + stopWatch.start(); + stopWatch.stop(); + stopWatch.start(); + stopWatch.stop(); + stopWatch.clear(); + stopWatch.start(); + stopWatch.stop(); + stopWatch.start(); + returnedValue = stopWatch.getStopWatchState(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of stop method, of class StopWatch. + */ + @Test + public void testStop() { //arrange + StopWatch stopWatch = new StopWatch(); + StopWatchState expectedValue = StopWatchState.STOPPED; + StopWatchState returnedValue; + //act + stopWatch.start(); + stopWatch.stop(); + stopWatch.start(); + stopWatch.stop(); + stopWatch.clear(); + stopWatch.start(); + stopWatch.stop(); + stopWatch.start(); + stopWatch.stop(); + returnedValue = stopWatch.getStopWatchState(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of getCurrentDuration method, of class StopWatch. + */ + @Test + public void testGetCurrentDuration() { + StopWatch stopWatch = new StopWatch(); + boolean expectedValue = true; + boolean returnedValue; + //act + stopWatch.start(); + stopWatch.stop(); + stopWatch.start(); + stopWatch.stop(); + stopWatch.clear(); + stopWatch.start(); + stopWatch.stop(); + returnedValue = stopWatch.getCurrentDuration().toTotal(TimeUnit.MILLISECOND) == 0; + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isClear method, of class StopWatch. + */ + @Test + public void testIsClear() { + //arrange + StopWatch stopWatch = new StopWatch(); + StopWatchState expectedValue = StopWatchState.CLEAR; + StopWatchState returnedValue; + //act + returnedValue = stopWatch.getStopWatchState(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isRunning method, of class StopWatch. + */ + @Test + public void testIsRunning() { + //arrange + StopWatch stopWatch = new StopWatch(); + StopWatchState expectedValue = StopWatchState.RUNNING; + StopWatchState returnedValue; + //act + stopWatch.start(); + stopWatch.stop(); + stopWatch.start(); + stopWatch.stop(); + stopWatch.start(); + stopWatch.stop(); + stopWatch.start(); + returnedValue = stopWatch.getStopWatchState(); + //assert + assertEquals(expectedValue, returnedValue); + } + + /** + * Test of isStopped method, of class StopWatch. + */ + @Test + public void testIsStopped() { + StopWatch stopWatch = new StopWatch(); + StopWatchState expectedValue = StopWatchState.STOPPED; + StopWatchState returnedValue; + //act + stopWatch.start(); + stopWatch.stop(); + stopWatch.start(); + stopWatch.stop(); + stopWatch.clear(); + stopWatch.start(); + stopWatch.stop(); + stopWatch.start(); + stopWatch.stop(); + returnedValue = stopWatch.getStopWatchState(); + //assert + assertEquals(expectedValue, returnedValue); + } + +} diff --git a/src/test/java/org/nanoboot/powerframework/datetime/DateTimeTest.java b/power-time/src/test/java/org/nanoboot/powerframework/time/moment/DateTimeTest.java similarity index 80% rename from src/test/java/org/nanoboot/powerframework/datetime/DateTimeTest.java rename to power-time/src/test/java/org/nanoboot/powerframework/time/moment/DateTimeTest.java index 6d0c018..7ed9798 100644 --- a/src/test/java/org/nanoboot/powerframework/datetime/DateTimeTest.java +++ b/power-time/src/test/java/org/nanoboot/powerframework/time/moment/DateTimeTest.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,25 +18,36 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.datetime; +package org.nanoboot.powerframework.time.moment; -import org.nanoboot.powerframework.PowerRuntimeException; -import org.junit.Test; -import static org.junit.Assert.*; +import org.nanoboot.powerframework.core.PowerException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import org.junit.*; /** + * * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ + public class DateTimeTest { private class DateTimeImpl extends DateTime { - public DateTimeImpl(LocalDate localDate, LocalTime localTime) { + public DateTimeImpl(LocalDate localDate, + LocalTime localTime) { super(localDate, localTime); } - public DateTimeImpl(int year, int month, int day, int hour24Format, int minute, int second, int millisecond) { + public DateTimeImpl(int year, + int month, + int day, + int hour24Format, + int minute, + int second, + int millisecond) { super(year, month, day, hour24Format, minute, second, millisecond); } @@ -47,6 +58,9 @@ public class DateTimeTest { public DateTimeImpl(String dateTimeInString) { super(dateTimeInString); } + public DateTimeImpl(long dateTimeAsLong) { + super(dateTimeAsLong); + } } @@ -67,11 +81,11 @@ public class DateTimeTest { //act try { DateTimeImpl dateTimeImpl = new DateTimeImpl(new LocalDate(1994, 5, 6), new LocalTime(21, 45, 6, 32)); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (isExceptionThrown) { + if(isExceptionThrown) { fail("There should be thrown no PowerRuntimeException"); } } @@ -87,11 +101,11 @@ public class DateTimeTest { //act try { DateTimeImpl dateTimeImpl = new DateTimeImpl(new LocalDate(1994, 15, 6), new LocalTime(21, 45, 6, 32)); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { + if(!isExceptionThrown) { fail("There should be thrown PowerRuntimeException"); } } @@ -107,11 +121,11 @@ public class DateTimeTest { //act try { DateTimeImpl dateTimeImpl = new DateTimeImpl(1994, 5, 6, 21, 45, 6, 32); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (isExceptionThrown) { + if(isExceptionThrown) { fail("There should be thrown no PowerRuntimeException"); } } @@ -127,11 +141,11 @@ public class DateTimeTest { //act try { DateTimeImpl dateTimeImpl = new DateTimeImpl(1994, 15, 6, 21, 45, 6, 32); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { + if(!isExceptionThrown) { fail("There should be thrown PowerRuntimeException"); } } @@ -146,11 +160,11 @@ public class DateTimeTest { //act try { DateTimeImpl dateTimeImpl = new DateTimeImpl(new DateTimeImpl(1994, 5, 6, 21, 45, 6, 32)); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (isExceptionThrown) { + if(isExceptionThrown) { fail("There should be thrown no PowerRuntimeException"); } } @@ -165,11 +179,11 @@ public class DateTimeTest { //act try { DateTimeImpl dateTimeImpl = new DateTimeImpl(new DateTimeImpl(1994, 15, 6, 21, 45, 6, 32)); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { + if(!isExceptionThrown) { fail("There should be thrown PowerRuntimeException"); } } @@ -184,11 +198,11 @@ public class DateTimeTest { //act try { DateTimeImpl dateTimeImpl = new DateTimeImpl("1994-05-06 21:45:06:032"); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (isExceptionThrown) { + if(isExceptionThrown) { fail("There should be thrown no PowerRuntimeException"); } } @@ -203,14 +217,28 @@ public class DateTimeTest { //act try { DateTimeImpl dateTimeImpl = new DateTimeImpl("1994-15-06 21:45:06:032"); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { + if(!isExceptionThrown) { fail("There should be thrown PowerRuntimeException"); } } + /** + * Test of constructor of class DateTime. (String dateTimeInString) + */ + @Test + public void testDateTime_longConstructor() { + String expectedResult = "19940506214506032"; + String result; + DateTimeImpl dateTimeImpl; + //act + dateTimeImpl = new DateTimeImpl(19940506214506032l); + result = String.valueOf(dateTimeImpl.toLong()); + //assert + assertEquals(expectedResult, result); + } /** * Test of getYear method, of class LocalDate. @@ -339,4 +367,19 @@ public class DateTimeTest { assertEquals(expectedResult, result); } + + /** + * Test of toString method, of class LocalDate. + */ + @Test + public void testToLong() { //arrange + String expectedResult = "19940506214506032"; + String result; + DateTimeImpl dateTimeImpl; + //act + dateTimeImpl = new DateTimeImpl(1994, 5, 6, 21, 45, 6, 32); + result = String.valueOf(dateTimeImpl.toLong()); + //assert + assertEquals(expectedResult, result); + } } diff --git a/src/test/java/org/nanoboot/powerframework/datetime/LocalDateTest.java b/power-time/src/test/java/org/nanoboot/powerframework/time/moment/LocalDateTest.java similarity index 83% rename from src/test/java/org/nanoboot/powerframework/datetime/LocalDateTest.java rename to power-time/src/test/java/org/nanoboot/powerframework/time/moment/LocalDateTest.java index 4aa9f7d..e395a20 100644 --- a/src/test/java/org/nanoboot/powerframework/datetime/LocalDateTest.java +++ b/power-time/src/test/java/org/nanoboot/powerframework/time/moment/LocalDateTest.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,15 +18,19 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.datetime; +package org.nanoboot.powerframework.time.moment; -import org.nanoboot.powerframework.PowerRuntimeException; -import org.junit.Test; +import org.nanoboot.powerframework.core.PowerException; import static org.junit.Assert.*; +import org.nanoboot.powerframework.time.utils.TimeException; +import org.junit.*; + /** + * * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public class LocalDateTest { @@ -46,15 +50,41 @@ public class LocalDateTest { //act try { LocalDate localDate = new LocalDate(1994, 5, 6); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (isExceptionThrown) { + if(isExceptionThrown) { fail("There should be thrown no PowerRuntimeException"); } } + /** + * Test of constructor of class LocalDate . + */ + @Test(expected = TimeException.class) + public void testLocalDate_stringIsLonger_ThereShouldBeThrownTimeException() { + //arrange + //act + LocalDate localDate = new LocalDate("1994-05-012"); + + //assert + } + /** + * Test of constructor of class LocalDate . + */ + @Test() + public void testLocalDate_aDateIsExpected() { + //arrange + //act + String dateAsString = "1994-05-12"; + LocalDate localDate = new LocalDate(dateAsString); + assertEquals(localDate.getYear(),1994); + assertEquals(localDate.getMonth(),5); + assertEquals(localDate.getDay(),12); + //assert + } + /** * Test of constructor of class LocalDate . */ @@ -65,11 +95,11 @@ public class LocalDateTest { //act try { LocalDate localDate = new LocalDate(1994, 0, 6); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { + if(!isExceptionThrown) { fail("There should be thrown PowerRuntimeException"); } } @@ -84,11 +114,11 @@ public class LocalDateTest { //act try { LocalDate localDate = new LocalDate(1994, 50, 6); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { + if(!isExceptionThrown) { fail("There should be thrown PowerRuntimeException"); } } @@ -103,11 +133,11 @@ public class LocalDateTest { //act try { LocalDate localDate = new LocalDate(1994, 5, 0); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { + if(!isExceptionThrown) { fail("There should be thrown PowerRuntimeException"); } } @@ -122,11 +152,11 @@ public class LocalDateTest { //act try { LocalDate localDate = new LocalDate(1994, 5, 32); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { + if(!isExceptionThrown) { fail("There should be thrown PowerRuntimeException"); } } @@ -141,11 +171,11 @@ public class LocalDateTest { //act try { LocalDate localDate = new LocalDate(1994, 9, 31); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { + if(!isExceptionThrown) { fail("There should be thrown PowerRuntimeException"); } } @@ -160,11 +190,11 @@ public class LocalDateTest { //act try { LocalDate localDate = new LocalDate(1992, 2, 31); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { + if(!isExceptionThrown) { fail("There should be thrown PowerRuntimeException"); } } @@ -179,11 +209,11 @@ public class LocalDateTest { //act try { LocalDate localDate = new LocalDate(1993, 2, 30); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { + if(!isExceptionThrown) { fail("There should be thrown PowerRuntimeException"); } } @@ -198,11 +228,11 @@ public class LocalDateTest { //act try { LocalDate localDate = new LocalDate(1993, 2, 29); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { + if(!isExceptionThrown) { fail("There should be thrown PowerRuntimeException"); } } @@ -217,11 +247,11 @@ public class LocalDateTest { //act try { LocalDate localDate = new LocalDate(1993, 2, 28); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (isExceptionThrown) { + if(isExceptionThrown) { fail("There should be thrown no PowerRuntimeException"); } } @@ -236,11 +266,11 @@ public class LocalDateTest { //act try { LocalDate localDate = new LocalDate(1993, 2, 27); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (isExceptionThrown) { + if(isExceptionThrown) { fail("There should be thrown no PowerRuntimeException"); } @@ -256,11 +286,11 @@ public class LocalDateTest { //act try { LocalDate localDate = new LocalDate(1992, 2, 31); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { + if(!isExceptionThrown) { fail("There should be thrown PowerRuntimeException"); } } @@ -275,11 +305,11 @@ public class LocalDateTest { //act try { LocalDate localDate = new LocalDate(1992, 2, 30); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { + if(!isExceptionThrown) { fail("There should be thrown PowerRuntimeException"); } } @@ -294,11 +324,11 @@ public class LocalDateTest { //act try { LocalDate localDate = new LocalDate(1992, 2, 29); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (isExceptionThrown) { + if(isExceptionThrown) { fail("There should be thrown no PowerRuntimeException"); } } @@ -313,11 +343,11 @@ public class LocalDateTest { //act try { LocalDate localDate = new LocalDate(1992, 2, 28); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (isExceptionThrown) { + if(isExceptionThrown) { fail("There should be thrown no PowerRuntimeException"); } } @@ -332,11 +362,11 @@ public class LocalDateTest { //act try { LocalDate localDate = new LocalDate(1992, 2, 27); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (isExceptionThrown) { + if(isExceptionThrown) { fail("There should be thrown no PowerRuntimeException"); } } diff --git a/power-time/src/test/java/org/nanoboot/powerframework/time/moment/LocalDateTimeTest.java b/power-time/src/test/java/org/nanoboot/powerframework/time/moment/LocalDateTimeTest.java new file mode 100644 index 0000000..514315e --- /dev/null +++ b/power-time/src/test/java/org/nanoboot/powerframework/time/moment/LocalDateTimeTest.java @@ -0,0 +1,167 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.time.moment; + +/** + * + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class LocalDateTimeTest { +// +// /** +// +// */ +// public LocalDateTimeTest() { +// } +// +// /** +// Test of constructor of class LocalDateTime. (String dateTimeInString) +// */ +// @Test +// public void testLocalDateTime_1argString_day6MustBeReturned() { +// //arrange +// LocalDateTime localDateTime; +// int expectedDay = 6; +// int returnedDay; +// //act +// localDateTime = new LocalDateTime("1994-05-06 21:45:06:032"); +// returnedDay = localDateTime.getDay(); +// //assert +// assertEquals(expectedDay, returnedDay); +// } +// +// /** +// Test of constructor of class LocalDateTime. (int year, int month, int +// day, int hour24Format, int minute, int second, int millisecond) +// */ +// @Test +// public void testLocalDateTime_7args_day6MustBeReturned() { +// //arrange +// LocalDateTime localDateTime; +// int expectedDay = 6; +// int returnedDay; +// //act +// localDateTime = new LocalDateTime(1994, 5, 6, 21, 45, 6, 32); +// returnedDay = localDateTime.getDay(); +// //assert +// assertEquals(expectedDay, returnedDay); +// } +// +// /** +// Test of constructor of class LocalDateTime. (UniversalDateTime +// universalDateTime) +// */ +// @Test +// public void testLocalDateTime_1argUniversalDateTime_day6MustBeReturned() { +// //arrange +// LocalDateTime localDateTime; +// UniversalDateTime universalDateTime; +// int expectedDay = 6; +// int returnedDay; +// //act +// universalDateTime = new UniversalDateTime(1994, 5, 6, 21, 45, 6, 32); +// localDateTime = new LocalDateTime(universalDateTime); +// returnedDay = localDateTime.getDay(); +// //assert +// assertEquals(expectedDay, returnedDay); +// } +// +// /** +// Test of constructor of class LocalDateTime. (ZonedDateTime zonedDateTime) +// */ +// @Test +// public void testLocalDateTime_1argZonedDateTime_day6MustBeReturned() { +// //arrange +// LocalDateTime localDateTime; +// TimeZone timeZone; +// ZonedDateTime zonedDateTime; +// int expectedDay = 6; +// int returnedDay; +// //act +// timeZone = new TimeZone("Australia/Sydney"); +// zonedDateTime = new ZonedDateTime(new LocalDateTime(1994, 5, 6, 21, 45, 6, 32), timeZone); +// localDateTime = new LocalDateTime(zonedDateTime); +// returnedDay = localDateTime.getDay(); +// //assert +// assertEquals(expectedDay, returnedDay); +// } +// +// /** +// Test of toUniversalDateTime method, of class LocalDateTime. +// */ +// @Test +// public void testToUniversalDateTime() { +// //arrange +// LocalDateTime localDateTime; +// UniversalDateTime universalDateTime; +// int expectedDay = 6; +// int returnedDay; +// //act +// localDateTime = new LocalDateTime(1994, 5, 6, 21, 45, 6, 32); +// universalDateTime = localDateTime.addUniversalTimeZone(); +// returnedDay = universalDateTime.getDay(); +// //assert +// assertEquals(expectedDay, returnedDay); +// } +// +// /** +// Test of toZonedDateTime method, of class LocalDateTime. +// */ +// @Test +// public void testToZonedDateTime() { +// //arrange +// LocalDateTime localDateTime; +// TimeZone timeZone; +// ZonedDateTime zonedDateTime; +// int expectedDay = 6; +// int returnedDay; +// //act +// timeZone = new TimeZone("Australia/Sydney"); +// localDateTime = new LocalDateTime(1994, 5, 6, 21, 45, 6, 32); +// zonedDateTime = localDateTime.addTimeZone(timeZone); +// returnedDay = zonedDateTime.getDay(); +// //assert +// assertEquals(expectedDay, returnedDay); +// } +// +// /** +// Test of toJavaLocalDateTime method, of class LocalDateTime. +// */ +// @Test +// public void testToJavaLocalDateTime() { +// //arrange +// LocalDateTime localDateTime; +// java.time.LocalDateTime javaLocalDateTime; +// int expectedDay = 6; +// int returnedDay; +// //act +// localDateTime = new LocalDateTime(1994, 5, 6, 21, 45, 6, 32); +// javaLocalDateTime = localDateTime.toJavaLocalDateTime(); +// returnedDay = javaLocalDateTime.getDayOfMonth(); +// //assert +// assertEquals(expectedDay, returnedDay); +// } + +} diff --git a/src/test/java/org/nanoboot/powerframework/datetime/LocalTimeTest.java b/power-time/src/test/java/org/nanoboot/powerframework/time/moment/LocalTimeTest.java similarity index 80% rename from src/test/java/org/nanoboot/powerframework/datetime/LocalTimeTest.java rename to power-time/src/test/java/org/nanoboot/powerframework/time/moment/LocalTimeTest.java index a201269..ef6be97 100644 --- a/src/test/java/org/nanoboot/powerframework/datetime/LocalTimeTest.java +++ b/power-time/src/test/java/org/nanoboot/powerframework/time/moment/LocalTimeTest.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,16 +18,22 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.datetime; +package org.nanoboot.powerframework.time.moment; -import org.nanoboot.powerframework.PowerRuntimeException; -import org.junit.Test; -import static org.junit.Assert.*; +import org.nanoboot.powerframework.core.PowerException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.nanoboot.powerframework.time.utils.TimeException; +import org.junit.*; /** + * * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ + public class LocalTimeTest { /** @@ -46,15 +52,40 @@ public class LocalTimeTest { //act try { LocalTime localTime = new LocalTime(21, 45, 6, 32); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (isExceptionThrown) { + if(isExceptionThrown) { fail("There should be thrown no PowerRuntimeException"); } } + /** + * Test of constructor of class LocalTime . + */ + @Test(expected = TimeException.class) + public void testLocalTime_stringIsLonger_ThereShouldBeThrownTimeException() { + //arrange + //act + LocalTime localTime = new LocalTime("21:45:06:0037"); + //assert + } + /** + * Test of constructor of class LocalTime . + */ + @Test() + public void testLocalTime_aTimeIsExpected() { + //arrange + //act + String timeAsString = "21:45:06:037"; + LocalTime localTime = new LocalTime(timeAsString); + assertEquals(localTime.getHour(),21); + assertEquals(localTime.getMinute(),45); + assertEquals(localTime.getSecond(),06); + assertEquals(localTime.getMillisecond(),37); + //assert + } /** * Test of constructor of class LocalTime. */ @@ -65,11 +96,11 @@ public class LocalTimeTest { //act try { LocalTime localTime = new LocalTime(-1, 45, 6, 32); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { + if(!isExceptionThrown) { fail("There should be thrown PowerRuntimeException"); } } @@ -84,11 +115,11 @@ public class LocalTimeTest { //act try { LocalTime localTime = new LocalTime(24, 45, 6, 32); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { + if(!isExceptionThrown) { fail("There should be thrown PowerRuntimeException"); } } @@ -104,11 +135,11 @@ public class LocalTimeTest { //act try { LocalTime localTime = new LocalTime(21, -1, 6, 32); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { + if(!isExceptionThrown) { fail("There should be thrown PowerRuntimeException"); } } @@ -123,11 +154,11 @@ public class LocalTimeTest { //act try { LocalTime localTime = new LocalTime(21, 60, 6, 32); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { + if(!isExceptionThrown) { fail("There should be thrown PowerRuntimeException"); } } @@ -142,11 +173,11 @@ public class LocalTimeTest { //act try { LocalTime localTime = new LocalTime(21, 45, -1, 32); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { + if(!isExceptionThrown) { fail("There should be thrown PowerRuntimeException"); } } @@ -161,11 +192,11 @@ public class LocalTimeTest { //act try { LocalTime localTime = new LocalTime(21, 45, 60, 32); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { + if(!isExceptionThrown) { fail("There should be thrown PowerRuntimeException"); } } @@ -180,11 +211,11 @@ public class LocalTimeTest { //act try { LocalTime localTime = new LocalTime(21, 45, 6, -1); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { + if(!isExceptionThrown) { fail("There should be thrown PowerRuntimeException"); } } @@ -199,11 +230,11 @@ public class LocalTimeTest { //act try { LocalTime localTime = new LocalTime(21, 45, 6, 1000); - } catch (PowerRuntimeException e) { + } catch (PowerException e) { isExceptionThrown = true; } //assert - if (!isExceptionThrown) { + if(!isExceptionThrown) { fail("There should be thrown PowerRuntimeException"); } } diff --git a/src/test/java/org/nanoboot/powerframework/datetime/TimeZoneTest.java b/power-time/src/test/java/org/nanoboot/powerframework/time/moment/TimeZoneTest.java similarity index 77% rename from src/test/java/org/nanoboot/powerframework/datetime/TimeZoneTest.java rename to power-time/src/test/java/org/nanoboot/powerframework/time/moment/TimeZoneTest.java index 95d3743..8fb5e68 100644 --- a/src/test/java/org/nanoboot/powerframework/datetime/TimeZoneTest.java +++ b/power-time/src/test/java/org/nanoboot/powerframework/time/moment/TimeZoneTest.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,15 +18,18 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.datetime; +package org.nanoboot.powerframework.time.moment; -import java.util.List; -import org.junit.Test; -import static org.junit.Assert.*; +import java.util.*; + +import static org.junit.Assert.assertEquals; +import org.junit.*; /** + * * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public class TimeZoneTest { @@ -46,7 +49,7 @@ public class TimeZoneTest { boolean expectedValue = true; boolean result; //act - listOfTimeZoneIDs = TimeZone.getListOfTimeZoneIDs(); + listOfTimeZoneIDs = org.nanoboot.powerframework.time.moment.TimeZone.getListOfTimeZoneIDs(); result = listOfTimeZoneIDs.contains("Australia/Sydney"); //assert assertEquals(expectedValue, result); @@ -62,7 +65,7 @@ public class TimeZoneTest { boolean expectedValue = false; boolean result; //act - listOfTimeZoneIDs = TimeZone.getListOfTimeZoneIDs(); + listOfTimeZoneIDs = org.nanoboot.powerframework.time.moment.TimeZone.getListOfTimeZoneIDs(); result = listOfTimeZoneIDs.contains("Amflkfd/Adfkjldfk"); //assert assertEquals(expectedValue, result); @@ -77,7 +80,7 @@ public class TimeZoneTest { boolean expectedValue = true; boolean result; //act - result = TimeZone.isTimeZoneIDValid("Australia/Sydney"); + result = org.nanoboot.powerframework.time.moment.TimeZone.isTimeZoneIDValid("Australia/Sydney"); //assert assertEquals(expectedValue, result); } @@ -91,7 +94,7 @@ public class TimeZoneTest { boolean expectedValue = false; boolean result; //act - result = TimeZone.isTimeZoneIDValid("Jehjujfdue/Eklfglsdi"); + result = org.nanoboot.powerframework.time.moment.TimeZone.isTimeZoneIDValid("Jehjujfdue/Eklfglsdi"); //assert assertEquals(expectedValue, result); } @@ -104,7 +107,7 @@ public class TimeZoneTest { //arrange String expectedValue = "Australia/Sydney"; String result; - TimeZone timeZone = new TimeZone("Australia/Sydney"); + org.nanoboot.powerframework.time.moment.TimeZone timeZone = new org.nanoboot.powerframework.time.moment.TimeZone("Australia/Sydney"); //act result = timeZone.toString(); //assert @@ -119,7 +122,7 @@ public class TimeZoneTest { //arrange String expectedValue = "Australia/Sydney"; String result; - TimeZone timeZone = new TimeZone("Australia/Sydney"); + org.nanoboot.powerframework.time.moment.TimeZone timeZone = new TimeZone("Australia/Sydney"); //act result = timeZone.getTimeZoneID(); //assert diff --git a/power-time/src/test/java/org/nanoboot/powerframework/time/moment/UniversalDateTimeTest.java b/power-time/src/test/java/org/nanoboot/powerframework/time/moment/UniversalDateTimeTest.java new file mode 100644 index 0000000..4e20411 --- /dev/null +++ b/power-time/src/test/java/org/nanoboot/powerframework/time/moment/UniversalDateTimeTest.java @@ -0,0 +1,146 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.time.moment; + +/** + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class UniversalDateTimeTest { +// +// /** +// +// */ +// public UniversalDateTimeTest() { +// } +// +// /** +// Test of constructor of class UniversalDateTime. (String dateTimeInString) +// */ +// @Test +// public void testUniversalDateTime_1argString_day6MustBeReturned() { +// //arrange +// UniversalDateTime universalDateTime; +// int expectedDay = 6; +// int returnedDay; +// //act +// universalDateTime = new UniversalDateTime("1994-05-06 21:45:06:032"); +// returnedDay = universalDateTime.getDay(); +// //assert +// assertEquals(expectedDay, returnedDay); +// } +// +// /** +// Test of constructor of class UniversalDateTime. (int year, int month, int +// day, int hour24Format, int minute, int second, int millisecond) +// */ +// @Test +// public void testUniversalDateTime_7args_day6MustBeReturned() { +// //arrange +// UniversalDateTime universalDateTime; +// int expectedDay = 6; +// int returnedDay; +// //act +// universalDateTime = new UniversalDateTime(1994, 5, 6, 21, 45, 6, 32); +// returnedDay = universalDateTime.getDay(); +// //assert +// assertEquals(expectedDay, returnedDay); +// } +// +// /** +// Test of constructor of class UniversalDateTime. (ZonedDateTime +// zonedDateTime) +// */ +// @Test +// public void testUniversalDateTime_1argZonedDateTime_day6MustBeReturned() { +// //arrange +// UniversalDateTime universalDateTime; +// TimeZone timeZone; +// ZonedDateTime zonedDateTime; +// int expectedDay = 5; +// int returnedDay; +// //act +// timeZone = new TimeZone("Australia/Sydney"); +// zonedDateTime = new ZonedDateTime(new LocalDateTime(1994, 5, 6, 21, 45, 6, 32), timeZone); +// universalDateTime = new UniversalDateTime(zonedDateTime); +// returnedDay = universalDateTime.getMonth(); +// //assert +// assertEquals(expectedDay, returnedDay); +// } +// +// /** +// Test of constructor of class UniversalDateTime. (LocalDateTime +// localDateTime) +// */ +// @Test +// public void testUniversalDateTime_1argLocalDateTime_day6MustBeReturned() { +// //arrange +// UniversalDateTime universalDateTime; +// LocalDateTime localDateTime; +// int expectedDay = 6; +// int returnedDay; +// //act +// localDateTime = new LocalDateTime(1994, 5, 6, 21, 45, 6, 32); +// universalDateTime = new UniversalDateTime(localDateTime); +// +// returnedDay = localDateTime.getDay(); +// //assert +// assertEquals(expectedDay, returnedDay); +// } +// +// /** +// Test of toZonedDateTime method, of class LocalDateTime. +// */ +// @Test +// public void testToZonedDateTime() { +// //arrange +// UniversalDateTime universalDateTime; +// ZonedDateTime zonedDateTime; +// int expectedMonth = 5; +// int returnedMonth; +// //act +// universalDateTime = new UniversalDateTime(1994, 5, 6, 21, 45, 6, 32); +// zonedDateTime = universalDateTime.toZonedDateTime(); +// returnedMonth = zonedDateTime.getMonth(); +// //assert +// assertEquals(expectedMonth, returnedMonth); +// } +// +// /** +// Test of testToLocalDateTime method, of class LocalDateTime. +// */ +// @Test +// public void testToLocalDateTime() { +// //arrange +// UniversalDateTime universalDateTime; +// LocalDateTime localDateTime; +// +// int expectedMonth = 5; +// int returnedMonth; +// //act +// universalDateTime = new UniversalDateTime(1994, 5, 6, 21, 45, 6, 32); +// localDateTime = universalDateTime.toLocalDateTime(); +// returnedMonth = universalDateTime.getMonth(); +// //assert +// assertEquals(expectedMonth, returnedMonth); +// } +} diff --git a/power-time/src/test/java/org/nanoboot/powerframework/time/moment/ZonedDateTimeTest.java b/power-time/src/test/java/org/nanoboot/powerframework/time/moment/ZonedDateTimeTest.java new file mode 100644 index 0000000..5e93e21 --- /dev/null +++ b/power-time/src/test/java/org/nanoboot/powerframework/time/moment/ZonedDateTimeTest.java @@ -0,0 +1,155 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.time.moment; + +/** + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class ZonedDateTimeTest { +// +// /** +// +// */ +// public ZonedDateTimeTest() { +// } +// +// /** +// Test of convertDateTimeFromOneTimeZoneToAnother method, of class +// ZonedDateTime. +// */ +// @Test +// public void testConvertDateTimeFromOneTimeZoneToAnother() { +// //arrange +// TimeZone oldTimeZone = new TimeZone("Australia/West"); +// ZonedDateTime oldZonedDateTime = new ZonedDateTime(new LocalDateTime(1995, 11, 5, 10, 5, 4, 64), oldTimeZone); +// String stringRepresentationOfOldZonedDateTime = oldZonedDateTime.toString(); +// +// String expectedStringValue = "1995-11-05 13:05:04:064"; +// String returnedStringValue; +// TimeZone newTimeZone = new TimeZone("Australia/Sydney"); +// //act +// returnedStringValue = ZonedDateTime.convertDateTimeFromOneTimeZoneToAnother(stringRepresentationOfOldZonedDateTime, oldTimeZone, newTimeZone); +// //assert +// assertEquals(expectedStringValue, returnedStringValue); +// } +// +// /** +// Test of getTimeZone method, of class ZonedDateTime. +// */ +// @Test +// public void testGetTimeZone() { +// //arrange +// String timeZoneID = "Australia/West"; +// TimeZone timeZone = new TimeZone(timeZoneID); +// ZonedDateTime zonedDateTime = new ZonedDateTime(new LocalDateTime(1995, 8, 5, 10, 5, 4, 64), timeZone); +// TimeZone returnedTimeZone; +// String returnedZoneID; +// //act +// returnedTimeZone = zonedDateTime.getTimeZone(); +// returnedZoneID = returnedTimeZone.getTimeZoneID(); +// //assert +// assertEquals(timeZoneID, returnedZoneID); +// +// } +// +// /** +// Test of toUniversalDateTime method, of class ZonedDateTime. +// */ +// @Test +// public void testToUniversalDateTime() { +// //arrange +// TimeZone oldTimeZone = new TimeZone("Australia/West"); +// ZonedDateTime zonedDateTime = new ZonedDateTime(new LocalDateTime(1995, 8, 5, 10, 5, 4, 64), oldTimeZone); +// String stringRepresentationOfZonedDateTime = zonedDateTime.toString(); +// +// String expectedStringValue = "1995-08-05 02:05:04:064"; +// String returnedStringValue; +// //act +// UniversalDateTime universalDateTime = zonedDateTime.toUniversalDateTime(); +// returnedStringValue = universalDateTime.toString(); +// //assert +// assertEquals(expectedStringValue, returnedStringValue); +// } +// +// /** +// Test of toLocalDateTime method, of class ZonedDateTime. +// */ +// @Test +// public void testToLocalDateTime() { +// //arrange +// TimeZone oldTimeZone = new TimeZone("Australia/West"); +// ZonedDateTime zonedDateTime = new ZonedDateTime(new LocalDateTime(1995, 8, 5, 10, 5, 4, 64), oldTimeZone); +// String stringRepresentationOfZonedDateTime = zonedDateTime.toString(); +// +// String expectedStringValue = "1995-08-05 10:05:04:064"; +// String returnedStringValue; +// //act +// LocalDateTime localDateTime = zonedDateTime.toLocalDateTime(); +// returnedStringValue = localDateTime.toString(); +// //assert +// assertEquals(expectedStringValue, returnedStringValue); +// } +// +// /** +// Test of toZonedDateTime method, of class ZonedDateTime. +// */ +// @Test +// public void testToZonedDateTime() { +// //arrange +// TimeZone oldTimeZone = new TimeZone("Australia/West"); +// ZonedDateTime oldZonedDateTime = new ZonedDateTime(new LocalDateTime(1995, 11, 5, 10, 5, 4, 64), oldTimeZone); +// String stringRepresentationOfOldZonedDateTime = oldZonedDateTime.toString(); +// +// TimeZone newTimeZone = new TimeZone("Australia/Sydney"); +// ZonedDateTime newZonedDateTime = new ZonedDateTime(new LocalDateTime(1995, 11, 5, 13, 5, 4, 64), oldTimeZone); +// +// String expectedStringValue = "1995-11-05 13:05:04:064"; +// String returnedStringValue; +// //act +// String stringRepresentationOfNewZonedDateTime = newZonedDateTime.toString(); +// returnedStringValue = stringRepresentationOfNewZonedDateTime; +// //assert +// assertEquals(expectedStringValue, returnedStringValue); +// } +// +// /** +// Test of toJavaZonedDateTime method, of class ZonedDateTime. +// */ +// @Test +// public void testToJavaZonedDateTime() { +// //arrange +// TimeZone timeZone = new TimeZone("Australia/West"); +// ZonedDateTime zonedDateTime; +// zonedDateTime = new ZonedDateTime(new LocalDateTime(1994, 5, 6, 21, 45, 6, 32), timeZone); +// java.time.ZonedDateTime javaZonedDateTime; +// int expectedDay = 6; +// int returnedDay; +// //act +// +// javaZonedDateTime = zonedDateTime.toJavaZonedDateTime(); +// returnedDay = javaZonedDateTime.getDayOfMonth(); +// //assert +// assertEquals(expectedDay, returnedDay); +// } + +} diff --git a/src/test/java/org/nanoboot/powerframework/datetime/DateUnitsValidatorTest.java b/power-time/src/test/java/org/nanoboot/powerframework/time/utils/DateUnitsValidatorTest.java similarity index 95% rename from src/test/java/org/nanoboot/powerframework/datetime/DateUnitsValidatorTest.java rename to power-time/src/test/java/org/nanoboot/powerframework/time/utils/DateUnitsValidatorTest.java index 69ab5a5..16a88dd 100644 --- a/src/test/java/org/nanoboot/powerframework/datetime/DateUnitsValidatorTest.java +++ b/power-time/src/test/java/org/nanoboot/powerframework/time/utils/DateUnitsValidatorTest.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,15 +18,19 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.datetime; +package org.nanoboot.powerframework.time.utils; -import org.junit.Test; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import org.junit.*; /** + * * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ + public class DateUnitsValidatorTest { /** diff --git a/power-time/src/test/java/org/nanoboot/powerframework/time/utils/TimeUnitsValidatorTest.java b/power-time/src/test/java/org/nanoboot/powerframework/time/utils/TimeUnitsValidatorTest.java new file mode 100644 index 0000000..c0af852 --- /dev/null +++ b/power-time/src/test/java/org/nanoboot/powerframework/time/utils/TimeUnitsValidatorTest.java @@ -0,0 +1,286 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.time.utils; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class TimeUnitsValidatorTest { +// +// /** +// +// */ +// public TimeUnitsValidatorTest() { +// } +// +// /** +// Test of isHourValid method, of class TimeUnitsValidator. +// */ +// @Test +// public void testIsHourValid_HourIs13_ThereShouldBeReturnedTrue() { +// //arrange +// int hour = 13; +// boolean returnedValue; +// //act +// returnedValue = TimeUnitsValidator.isHourValid(hour); +// //assert +// assertTrue(returnedValue); +// } +// +// /** +// Test of isHourValid method, of class TimeUnitsValidator. +// */ +// @Test +// public void testIsHourValid_HourIsMinus1_ThereShouldBeReturneFalse() { +// //arrange +// int hour = -1; +// boolean returnedValue; +// //act +// returnedValue = TimeUnitsValidator.isHourValid(hour); +// //assert +// assertFalse(returnedValue); +// } +// +// /** +// Test of isHourValid method, of class TimeUnitsValidator. +// */ +// @Test +// public void testIsHourValid_HourIs24_ThereShouldBeReturneFalse() { +// //arrange +// int hour = 24; +// boolean returnedValue; +// //act +// returnedValue = TimeUnitsValidator.isHourValid(hour); +// //assert +// assertFalse(returnedValue); +// } +// +// /** +// Test of isMinuteValid method, of class TimeUnitsValidator. +// */ +// @Test +// public void testIsMinuteValid_MinuteIs34__ThereShouldBeReturnedTrue() { +// //arrange +// int minute = 34; +// boolean returnedValue; +// //act +// returnedValue = TimeUnitsValidator.isMinuteValid(minute); +// //assert +// assertTrue(returnedValue); +// } +// +// /** +// Test of isMinuteValid method, of class TimeUnitsValidator. +// */ +// @Test +// public void testIsMinuteValid_MinuteIsMinus1_ThereShouldBeReturneFalse() { +// //arrange +// int minute = -1; +// boolean returnedValue; +// //act +// returnedValue = TimeUnitsValidator.isMinuteValid(minute); +// //assert +// assertFalse(returnedValue); +// } +// +// /** +// Test of isMinuteValid method, of class TimeUnitsValidator. +// */ +// @Test +// public void testIsMinuteValid_MinuteIs60_ThereShouldBeReturneFalse() { +// //arrange +// int minute = 60; +// boolean returnedValue; +// //act +// returnedValue = TimeUnitsValidator.isMinuteValid(minute); +// //assert +// assertFalse(returnedValue); +// } +// +// /** +// Test of isSecondValid method, of class TimeUnitsValidator. +// */ +// @Test +// public void testIsSecondValid_SecondIs46__ThereShouldBeReturnedTrue() { +// //arrange +// int second = 46; +// boolean returnedValue; +// //act +// returnedValue = TimeUnitsValidator.isSecondValid(second); +// //assert +// assertTrue(returnedValue); +// } +// +// /** +// Test of isSecondValid method, of class TimeUnitsValidator. +// */ +// @Test +// public void testIsSecondValid_SecondIsMinus1__ThereShouldBeReturneFalse() { +// //arrange +// int second = -1; +// boolean returnedValue; +// //act +// returnedValue = TimeUnitsValidator.isSecondValid(second); +// //assert +// assertFalse(returnedValue); +// } +// +// /** +// Test of isSecondValid method, of class TimeUnitsValidator. +// */ +// @Test +// public void testIsSecondValid_SecondIs60__ThereShouldBeReturneFalse() { +// //arrange +// int second = 60; +// boolean returnedValue; +// //act +// returnedValue = TimeUnitsValidator.isSecondValid(second); +// //assert +// assertFalse(returnedValue); +// } +// +// /** +// Test of isMillisecondValid method, of class TimeUnitsValidator. +// */ +// @Test +// public void testIsMillisecondValid_MillisecondIs843__ThereShouldBeReturnedTrue() { +// //arrange +// int millisecond = 843; +// boolean returnedValue; +// //act +// returnedValue = TimeUnitsValidator.isMillisecondValid(millisecond); +// //assert +// assertTrue(returnedValue); +// } +// +// /** +// Test of isMillisecondValid method, of class TimeUnitsValidator. +// */ +// @Test +// public void testIsMillisecondValid_MillisecondIsMinus1_ThereShouldBeReturneFalse() { +// //arrange +// int millisecond = -1; +// boolean returnedValue; +// //act +// returnedValue = TimeUnitsValidator.isMillisecondValid(millisecond); +// //assert +// assertFalse(returnedValue); +// } +// +// /** +// Test of isMillisecondValid method, of class TimeUnitsValidator. +// */ +// @Test +// public void testIsMillisecondValid_MillisecondIs1000_ThereShouldBeReturneFalse() { +// //arrange +// int millisecond = 1000; +// boolean returnedValue; +// //act +// returnedValue = TimeUnitsValidator.isMillisecondValid(millisecond); +// //assert +// assertFalse(returnedValue); +// } +// +// /** +// Test of areAllTimeUnitsValid method, of class TimeUnitsValidator. +// */ +// @Test +// public void testAreAllTimeUnitsValid_ThereShouldBeReturneTrue() { +// //arrange +// int hour = 2; +// int minute = 34; +// int second = 23; +// int millisecond = 428; +// boolean returnedValue; +// //act +// returnedValue = TimeUnitsValidator.areAllTimeUnitsValid(hour, minute, second, millisecond); +// //assert +// assertTrue(returnedValue); +// } +// +// /** +// Test of areAllTimeUnitsValid method, of class TimeUnitsValidator. +// */ +// @Test +// public void testAreAllTimeUnitsValid_ThereShouldBeReturneFalse() { +// //arrange +// int hour = 112; +// int minute = 134; +// int second = 123; +// int millisecond = 1428; +// boolean returnedValue; +// //act +// returnedValue = TimeUnitsValidator.areAllTimeUnitsValid(hour, minute, second, millisecond); +// //assert +// assertFalse(returnedValue); +// } +// +// /** +// Test of checkInputValuesForTimeAndIfThereIsAnInvalidOneThrowException +// method, of class TimeUnitsValidator. +// */ +// @Test +// public void testCheckInputValuesForTimeAndIfThereIsAnInvalidOneThrowException_ThereShouldBeThrownNoPowerRuntimeException() { +// //arrange +// int hour = 12; +// int minute = 34; +// int second = 23; +// int millisecond = 428; +// boolean isExceptionThrown = false; +// //act +// try { +// TimeUnitsValidator.validate(hour, minute, second, millisecond); +// } catch (PowerException e) { +// isExceptionThrown = true; +// } +// //assert +// if(isExceptionThrown) { +// fail("There should be thrown no PowerRuntimeException"); +// } +// } +// +// /** +// Test of checkInputValuesForTimeAndIfThereIsAnInvalidOneThrowException +// method, of class TimeUnitsValidator. +// */ +// @Test +// public void testCheckInputValuesForTimeAndIfThereIsAnInvalidOneThrowException_ThereShouldBeThrownPowerRuntimeException() { +// //arrange +// int hour = 112; +// int minute = 134; +// int second = 123; +// int millisecond = 1428; +// boolean isExceptionThrown = false; +// //act +// try { +// TimeUnitsValidator.validate(hour, minute, second, millisecond); +// } catch (PowerException e) { +// isExceptionThrown = true; +// } +// //assert +// if(!isExceptionThrown) { +// fail("There should be thrown PowerRuntimeException"); +// } +// } +} diff --git a/power-utils/pom.xml b/power-utils/pom.xml new file mode 100644 index 0000000..76d7cdc --- /dev/null +++ b/power-utils/pom.xml @@ -0,0 +1,69 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-utils + jar + + Power Utils + Utils for the Power library + + + true + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + org.nanoboot.powerframework + power-reflection + ${power.version} + + + org.projectlombok + lombok + + + org.jgrapht + jgrapht-core + 1.5.1 + + + org.nanoboot.powerframework + power-text + ${power.version} + compile + + + + diff --git a/power-utils/src/main/java/module-info.java b/power-utils/src/main/java/module-info.java new file mode 100644 index 0000000..a7a392c --- /dev/null +++ b/power-utils/src/main/java/module-info.java @@ -0,0 +1,36 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +module powerframework.utils { + requires powerframework.core; + requires lombok; + requires powerframework.text; + requires powerframework.reflection; + requires org.jgrapht.core; + exports org.nanoboot.powerframework.utils; + exports org.nanoboot.powerframework.utils.annotations; + exports org.nanoboot.powerframework.utils.dependencies; +} diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/CommandReader.java b/power-utils/src/main/java/org/nanoboot/powerframework/utils/CommandReader.java new file mode 100644 index 0000000..7b31eb9 --- /dev/null +++ b/power-utils/src/main/java/org/nanoboot/powerframework/utils/CommandReader.java @@ -0,0 +1,252 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils; + +import org.nanoboot.powerframework.text.AsciiCharacter; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class CommandReader { + + /** + * Space regexp. + */ + private static final String SPACE_REGEXP = "\\s+"; + /** + * Double colon delimiter. + */ + private static final String SPACE_COLON_COLON_SPACE_DELIMITER = " :: "; + /** + * Default current index. + */ + private static final int DEFAULT_CURRENT_INDEX = -1; + /** + * Array. + */ + private final String[] commands; + /** + * Array index. + */ + private int currentIndex = DEFAULT_CURRENT_INDEX; + + /** + * Current command. + */ + private String currentCommand = null; + + /** + * Constructor. + * + * @param stringToSplit string to be split + */ + public CommandReader(final String stringToSplit) { + if (stringToSplit == null) { + throw new UtilsException("stringToSplit must not be null."); + } + commands = stringToSplit.split(SPACE_REGEXP); + } + + /** + * Returns size of the split commands. + * @return size of the split commands + */ + public int size() { + return commands.length; + } + + /** + * Returns size of the split commands. + * @return size of the split commands + */ + public int isEmpty() { + return commands.length; + } + /** + * Returns current command. + * + * @return current command + */ + public String current() { + return currentCommand; + } + + /** + * Increments the pointer to the current word. + */ + private void incrementCurrentIndex() { + if (!hasNext()) { + throw new UtilsException("CommandReader has no next command."); + } + currentIndex++; + } + /** + * Checks, if there is a next command. + * @return true, if there is a next command, otherwise false + */ + public boolean hasNext() { + int nextIndex = currentIndex + 1; + return isIndexValid(nextIndex); + } + + /** + * Checks, if the index is valid. + * @param index index to be checked + * @return true, if the index is at least zero and + * less than the size, otherwise false + */ + private boolean isIndexValid(final int index) { + return index >= 0 && index < size(); + } + + /** + * Returns next command. + * + * @return next command + */ + public String next() { + incrementCurrentIndex(); + this.currentCommand = commands[currentIndex]; + return current(); + } + + /** + * Almost same as next(). + * The only difference is, that the current number is not updated. + * @return next command, if exists, otherwise an exception is thrown. + */ + public String nextPreview() { + int nextNumber = currentNumber() + 1; + return getCommandByNumber(nextNumber); + } + + /** + * Converts index to number. (one is added) + * @param index index (starting from 0) + * @return number + */ + private int convertIndexToNumber(final int index) { + return index + 1; + } + /** + * Converts number to index. (one is removed) + * @param number number (starting from 1) + * @return number + */ + private int convertNumberToIndex(final int number) { + return number - 1; + } + /** + * Returns command by number. + * @param number number + * @return command + */ + public String getCommandByNumber(final int number) { + if (!isNumberValid(number)) { + throw new UtilsException("Number " + number + " is not valid."); + } + int index = convertNumberToIndex(number); + return this.commands[index]; + } + /** + * Resets this command reader. + */ + public void reset() { + this.currentIndex = DEFAULT_CURRENT_INDEX; + this.currentCommand = null; + } + /** + * Checks, if a number is valid. + * @param number number + * @return true, if the number is valid, otherwise false + */ + public boolean isNumberValid(final int number) { + int index = convertNumberToIndex(number); + return isIndexValid(index); + } + /** + * Returns next as int. + * @return next as int + */ + public int nextAsInt() { + return Integer.parseInt(next()); + } + + /** + * Returns current number. + * @return current number + */ + public int currentNumber() { + return convertIndexToNumber(currentIndex); + } + + /** + * Creates String array representing this CommandReader. + * @return String array + */ + public String[] toArray() { + String[] returnArray = new String[this.commands.length]; + int index = 0; + for (String e: this.commands) { + returnArray[index] = e; + index++; + } + return returnArray; + } + /** + * Creates debugging string. + * @return string representation + * of the command reader for debugging purposes + */ + public String toStringForDebuggingPurposes() { + StringBuilder stringBuilder = new StringBuilder(); + + for (int i = 0; i < commands.length; i++) { + String element = commands[i]; + if (i == this.currentIndex) { + stringBuilder.append('['); + } + stringBuilder.append(element); + if (i == this.currentIndex) { + stringBuilder.append(']'); + } + if (i != (commands.length - 1)) { + stringBuilder.append(AsciiCharacter.SPACE.toChar()); + } + } + return stringBuilder.toString(); + } + + @Override + public final String toString() { + StringBuilder stringBuilder = new StringBuilder(); + for (String element : this.commands) { + stringBuilder + .append(element) + .append(SPACE_COLON_COLON_SPACE_DELIMITER); + } + return stringBuilder.toString(); + } +} diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/NamingConvention.java b/power-utils/src/main/java/org/nanoboot/powerframework/utils/NamingConvention.java new file mode 100644 index 0000000..93405c7 --- /dev/null +++ b/power-utils/src/main/java/org/nanoboot/powerframework/utils/NamingConvention.java @@ -0,0 +1,73 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils; + +import lombok.Data; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public enum NamingConvention { + + /** + * Database. + * Example: MY_OBJECT + */ + DATABASE, + + /** + * Java. + * Example: myObject + * Duplicate of JAVA_FIELD + * Example: MyObject + */ + @Deprecated + JAVA, + + /** + * Java. + * Example: myObject + */ + JAVA_FIELD, + + /** + * Java. + * Example: MyObject + */ + JAVA_CLASS, + + + /** + * Human. + * Example: my object + */ + HUMAN, + + /** + * Unknown. + * Used only for test purposes. + */ + UNKNOWN; +} diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/NamingConventionConvertor.java b/power-utils/src/main/java/org/nanoboot/powerframework/utils/NamingConventionConvertor.java new file mode 100644 index 0000000..df4ab2e --- /dev/null +++ b/power-utils/src/main/java/org/nanoboot/powerframework/utils/NamingConventionConvertor.java @@ -0,0 +1,287 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils; + +import org.nanoboot.powerframework.text.AsciiCharacter; + +import java.util.ArrayList; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public final class NamingConventionConvertor { + + /** + * Delimiter for databases. + */ + private static final String DATABASE_DELIMITER = + AsciiCharacter.UNDERSCORE.asString(); + /** + * Delimiter for humans. + */ + private static final String HUMAN_DELIMITER = + AsciiCharacter.SPACE.asString(); + + /** + * @param name name to convert + * @param inputNamingConvention input naming convention + * @param outputNamingConvention output naming convention + * @return converted name + */ + public static String convert( + final String name, + final NamingConvention inputNamingConvention, + final NamingConvention outputNamingConvention) { + System.out.println("Going to convert name=" + name + " in=" + inputNamingConvention + " out=" + outputNamingConvention); + check(name, inputNamingConvention); + String[] array = convertToArray(name, inputNamingConvention); + StringBuilder stringBuilder = new StringBuilder(); + + if (outputNamingConvention == null) { + throw new UtilsException("Output naming convention is null."); + } + switch (outputNamingConvention) { + case JAVA: + return convertToJavaField(array, stringBuilder); + case JAVA_FIELD: + return convertToJavaField(array, stringBuilder); + case JAVA_CLASS: + return convertToJavaClass(array, stringBuilder); + case DATABASE: + return convertToDatabase(array, stringBuilder); + case HUMAN: + return convertToHuman(array, stringBuilder); + default: + throw new UtilsException( + "Unknown NamingConvention" + inputNamingConvention); + } + + } + + + /** + * Checks name validity. + * + * @param name name to be checked + * @param inputNamingConvention input naming convention + */ + private static void check(final String name, + final NamingConvention inputNamingConvention) { + NamingConvention detectedNamingConvention = detectNamingConvention(name); + boolean valid = detectedNamingConvention == inputNamingConvention; + + if (!valid) { + if (inputNamingConvention == NamingConvention.JAVA && detectedNamingConvention == NamingConvention.JAVA_FIELD) { + valid = true; + } + } + if (!valid) { + String msg = "Wrong name and input naming convention combination: name=" + + name + ", in=" + inputNamingConvention + ", but detected is=" + detectedNamingConvention; + throw new UtilsException(msg); + } + } + + /** + * Detects naming convention. + * + * @param name name to detect + * @return detected naming convention + */ + public static NamingConvention detectNamingConvention( + final String name) { + boolean databasePredicate = name.contains(DATABASE_DELIMITER) || stringHasAllUpperCase(name); + boolean humanPredicate = name.contains(HUMAN_DELIMITER); + if (databasePredicate && !humanPredicate) { + return NamingConvention.DATABASE; + } + if (!databasePredicate && humanPredicate) { + return NamingConvention.HUMAN; + } + if (databasePredicate /*&& humanPredicate*/) { + String msg = "The name contain database and also human delimiters."; + throw new UtilsException(msg); + } + return Character.isUpperCase(name.charAt(0)) ? NamingConvention.JAVA_CLASS : NamingConvention.JAVA_FIELD; + } + + private static boolean stringHasAllUpperCase(final String s) { + for (char ch : s.toCharArray()) { + if (Character.isLetter(ch)) { + if (Character.isLowerCase(ch)) { + return false; + } + } + } + return true; + } + + /** + * Converts the Strings to Human representation. + * + * @param array array + * @param stringBuilder stringBuilder + * @return human words + */ + private static String convertToHuman(final String[] array, + final StringBuilder stringBuilder) { + for (String element : array) { + stringBuilder.append(element.toLowerCase()).append(HUMAN_DELIMITER); + } + String tempString = stringBuilder.toString(); + return tempString.substring(0, tempString.length() - 1); + } + + /** + * Converts the Strings to database representation. + * + * @param array array + * @param stringBuilder stringBuilder + * @return database words + */ + private static String convertToDatabase(final String[] array, + final StringBuilder stringBuilder) { + for (String element : array) { + stringBuilder + .append(element.toUpperCase()).append(DATABASE_DELIMITER); + } + String tempString = stringBuilder.toString(); + return tempString.substring(0, tempString.length() - 1); + } + + /** + * Converts the Strings to Java representation. + * + * @param array array + * @param stringBuilder stringBuilder + * @return Java words + */ + private static String convertToJavaField(final String[] array, + final StringBuilder stringBuilder) { + String string = convertToJavaClass(array, stringBuilder); + return Character.toLowerCase( + string.charAt(0)) + string.substring(1); + + } + + private static String convertToJavaClass(String[] array, StringBuilder stringBuilder) { + for (String element : array) { + if (element.length() != 0) { + stringBuilder.append(Character.toUpperCase(element.charAt(0))); + stringBuilder.append(element.substring(1, element.length())); + } + } + String tempString = stringBuilder.toString(); + return tempString; + } + + /** + * Converts input string to array, all characters are changed to lower case. + * + * @param name name to convert + * @param inputNamingConvention input naming convention + * @return String array + */ + private static String[] convertToArray( + final String name, + final NamingConvention inputNamingConvention) { + + switch (inputNamingConvention) { + case DATABASE: + return name.toLowerCase().split(DATABASE_DELIMITER); + case JAVA: + return getArrayFromJavaConvention(name); + case JAVA_FIELD: + return getArrayFromJavaConvention(name); + case JAVA_CLASS: + return getArrayFromJavaConvention(name); + case HUMAN: + return name.toLowerCase().split(HUMAN_DELIMITER); + default: + String msg = "Unknown NamingConvention" + inputNamingConvention; + throw new UtilsException(msg); + } + } + + /** + * Creates array from Java convention. + * + * @param name name + * @return String array + */ + private static String[] getArrayFromJavaConvention(final String name) { + String finalName = name; + if (Character.isUpperCase(finalName.charAt(0))) { + finalName = finalName.substring(0, 1).toLowerCase() + finalName.substring(1); + } + + ArrayList upperCharPositions = getIndexesOfUpperChars(finalName); + String[] result = new String[upperCharPositions.size() + 1]; + int startIndex; + int endIndex = 0; + int resultIndex = 0; + for (int element : upperCharPositions) { + if (element == 0) { + continue; + } + startIndex = endIndex; + endIndex = element; + result[resultIndex] = finalName + .substring(startIndex, endIndex).toLowerCase(); + resultIndex++; + } + startIndex = endIndex; + endIndex = finalName.length(); + result[resultIndex] = finalName.substring(startIndex, endIndex); + + return result; + } + + /** + * Returns indexes of all upper characters of the String. + * + * @param name name + * @return String array with indexes + */ + private static ArrayList getIndexesOfUpperChars( + final String name) { + ArrayList list = new ArrayList<>(); + for (int i = 0; i < name.length(); i++) { + char ch = name.charAt(i); + if (Character.isUpperCase(ch)) { + list.add(i); + } + } + return list; + } + + /** + * Constructor. + *

+ * Not meant to be instantiated. + */ + private NamingConventionConvertor() { + //Not meant to be instantiated. + } +} diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/StringTemplate.java b/power-utils/src/main/java/org/nanoboot/powerframework/utils/StringTemplate.java new file mode 100644 index 0000000..a5b0eab --- /dev/null +++ b/power-utils/src/main/java/org/nanoboot/powerframework/utils/StringTemplate.java @@ -0,0 +1,65 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils; + +/** + * + * @author robertvokac + */ + +import java.util.HashMap; +import java.util.Map; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class StringTemplate { + public static final String VAR_START = "{{{{"; + public static final String VAR_END = "}}}}"; + private final String template; + + public StringTemplate(String template) { + this.template = template; + } + public String apply(Map map) { + String result = template; + for(String key:map.keySet()) { + String var = VAR_START + key + VAR_END; + String value = map.get(key); + result = result.replace(var, value); + } + if(result.contains(VAR_START)) { + throw new UtilsException("Template \"" + result + "\"still contains \"" + VAR_START + "\"."); + } + + if(result.contains(VAR_END)) { + throw new UtilsException("Template \"" + result + "\"still contains \"" + VAR_END + "\"."); + } + return result; + } + public Map createEmptyMap() { + return new HashMap<>(); + } +} + + diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/StringUtils.java b/power-utils/src/main/java/org/nanoboot/powerframework/utils/StringUtils.java new file mode 100644 index 0000000..33b0f30 --- /dev/null +++ b/power-utils/src/main/java/org/nanoboot/powerframework/utils/StringUtils.java @@ -0,0 +1,84 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public final class StringUtils { + + /** + * "" Constant. + */ + public static final String EMPTY_STRING = ""; + + /** + * Appends objects. + * @param objects objects to append + * + * @return appended objects + */ + public static String appendObjects(final Object... objects) { + StringBuilder stringBuilder = new StringBuilder(); + for (Object element : objects) { + stringBuilder.append(element); + } + return stringBuilder.toString(); + } + + /** + * Checks, if a string is empty. + * @param string string to check + * @return true, if the string is empty, otherwise false. + */ + public static boolean isEmpty(final String string) { + return string.equals(EMPTY_STRING); + } + + /** + * Converts string to int. + * @param string string to convert + * @return int + */ + public static int toInt(final String string) { + return Integer.valueOf(string); + } + + /** + * Creates lines from a String. + * @param string string to split + * @return splitted string + */ + public static String[] toLines(final String string) { + return string.split("\\r?\\n"); + } + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private StringUtils() { + } +} diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/UtilsException.java b/power-utils/src/main/java/org/nanoboot/powerframework/utils/UtilsException.java new file mode 100644 index 0000000..272ea39 --- /dev/null +++ b/power-utils/src/main/java/org/nanoboot/powerframework/utils/UtilsException.java @@ -0,0 +1,42 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils; + + +import org.nanoboot.powerframework.core.PowerException; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class UtilsException extends PowerException { + + /** + * Constructor. + * @param message detail of the exception + */ + public UtilsException(final String message) { + super(message); + } + +} diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/annotations/Done.java b/power-utils/src/main/java/org/nanoboot/powerframework/utils/annotations/Done.java new file mode 100644 index 0000000..801f849 --- /dev/null +++ b/power-utils/src/main/java/org/nanoboot/powerframework/utils/annotations/Done.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils.annotations; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public @interface Done { + +} diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/annotations/InProgress.java b/power-utils/src/main/java/org/nanoboot/powerframework/utils/annotations/InProgress.java new file mode 100644 index 0000000..698dc2f --- /dev/null +++ b/power-utils/src/main/java/org/nanoboot/powerframework/utils/annotations/InProgress.java @@ -0,0 +1,36 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils.annotations; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public @interface InProgress { + /** + * Description. + * @return text + */ + String description() default ""; +} diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/annotations/ToDo.java b/power-utils/src/main/java/org/nanoboot/powerframework/utils/annotations/ToDo.java new file mode 100644 index 0000000..a05f769 --- /dev/null +++ b/power-utils/src/main/java/org/nanoboot/powerframework/utils/annotations/ToDo.java @@ -0,0 +1,35 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils.annotations; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public @interface ToDo { + /** + * Description. + * @return text + */ + String description() default ""; +} diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/annotations/ToRemove.java b/power-utils/src/main/java/org/nanoboot/powerframework/utils/annotations/ToRemove.java new file mode 100644 index 0000000..bdef6db --- /dev/null +++ b/power-utils/src/main/java/org/nanoboot/powerframework/utils/annotations/ToRemove.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils.annotations; + +/** + * Describes a work (code). + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public @interface ToRemove { + +} diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/annotations/package-info.java b/power-utils/src/main/java/org/nanoboot/powerframework/utils/annotations/package-info.java new file mode 100644 index 0000000..0dc3f69 --- /dev/null +++ b/power-utils/src/main/java/org/nanoboot/powerframework/utils/annotations/package-info.java @@ -0,0 +1,27 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * Some annotations. + * + * @author Robert Vokac + * @since 0.0.0 + */ +package org.nanoboot.powerframework.utils.annotations; diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/builder/AbstractBuilder.java b/power-utils/src/main/java/org/nanoboot/powerframework/utils/builder/AbstractBuilder.java new file mode 100644 index 0000000..842243a --- /dev/null +++ b/power-utils/src/main/java/org/nanoboot/powerframework/utils/builder/AbstractBuilder.java @@ -0,0 +1,43 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils.builder; + +import org.nanoboot.powerframework.reflection.ReflectionUtils; + +/** + * Builder abstract implementation. + * @param + * + * @author Robert Vokac + * @since 0.0.0 + */ +public abstract class AbstractBuilder implements Builder { + /** + * The object, which is modified and finally returned by build() method. + */ + protected final T result = (T) ReflectionUtils + .newInstance(ReflectionUtils.getConstructor(getClassUsedByThisBuilder())); + abstract Class getClassUsedByThisBuilder(); + @Override + public final T build() { + return result; + } +} diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/builder/Builder.java b/power-utils/src/main/java/org/nanoboot/powerframework/utils/builder/Builder.java new file mode 100644 index 0000000..22dd366 --- /dev/null +++ b/power-utils/src/main/java/org/nanoboot/powerframework/utils/builder/Builder.java @@ -0,0 +1,36 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils.builder; + +/** + * Builder generic interface for builders. + * @param Class for this generic interface + * + * @author Robert Vokac + * @since 0.0.0 + */ +public interface Builder { + /** + * Builds the final object. + * @return object instance + */ + T build(); +} diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/builder/package-info.java b/power-utils/src/main/java/org/nanoboot/powerframework/utils/builder/package-info.java new file mode 100644 index 0000000..0f88f78 --- /dev/null +++ b/power-utils/src/main/java/org/nanoboot/powerframework/utils/builder/package-info.java @@ -0,0 +1,27 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * Builder utilities. + * + * @author Robert Vokac + * @since 0.0.0 + */ +package org.nanoboot.powerframework.utils.builder; diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/collections/ListSplitter.java b/power-utils/src/main/java/org/nanoboot/powerframework/utils/collections/ListSplitter.java new file mode 100644 index 0000000..0f3b566 --- /dev/null +++ b/power-utils/src/main/java/org/nanoboot/powerframework/utils/collections/ListSplitter.java @@ -0,0 +1,67 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils.collections; + +import java.util.ArrayList; +import java.util.List; +import org.nanoboot.powerframework.utils.UtilsException; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class ListSplitter { + private ListSplitter() { + //Not meant to be instantiated. + } + public static List> splitListToSublists(List inputList, int sizePerSublist) { + if(sizePerSublist < 2) { + throw new UtilsException("sizePerSublist is " + sizePerSublist + ", but it must be 2 or more."); + } + List> outputList = new ArrayList<>(); + if(inputList.isEmpty()) { + return outputList; + } + List tmpList = null; + for(int i = 0; i < inputList.size(); i++) { + if(tmpList == null) { + tmpList = new ArrayList<>(); + } + T element = inputList.get(i); + tmpList.add(element); + if(tmpList.size() == sizePerSublist) { + outputList.add(tmpList); + tmpList = null; + } + } + if(tmpList != null) { + outputList.add(tmpList); + tmpList = null; + } + return outputList; +} + + + +} diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/compression/.gitkeep b/power-utils/src/main/java/org/nanoboot/powerframework/utils/compression/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/dependencies/DependencyNode.java b/power-utils/src/main/java/org/nanoboot/powerframework/utils/dependencies/DependencyNode.java new file mode 100644 index 0000000..01f53dc --- /dev/null +++ b/power-utils/src/main/java/org/nanoboot/powerframework/utils/dependencies/DependencyNode.java @@ -0,0 +1,53 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils.dependencies; + +import java.util.ArrayList; +import java.util.List; +import lombok.Data; +import lombok.ToString; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@Data +@ToString +public class DependencyNode { + + private final String name; + private List dependencies = new ArrayList<>(); + + public DependencyNode(String nameIn, List dependenciesIn) { + this.name = nameIn; + for (String s : dependenciesIn) { + this.dependencies.add(s); + } + } + + DependencyNode(String nameIn) { + this.name = nameIn; + } + +} diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/dependencies/DependencyResolver.java b/power-utils/src/main/java/org/nanoboot/powerframework/utils/dependencies/DependencyResolver.java new file mode 100644 index 0000000..6c48c79 --- /dev/null +++ b/power-utils/src/main/java/org/nanoboot/powerframework/utils/dependencies/DependencyResolver.java @@ -0,0 +1,34 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils.dependencies; + +import java.util.List; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public interface DependencyResolver { + List resolve(List dependencyNodesIn); +} diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/dependencies/DependencyResolverJGraphTImpl.java b/power-utils/src/main/java/org/nanoboot/powerframework/utils/dependencies/DependencyResolverJGraphTImpl.java new file mode 100644 index 0000000..8fc475d --- /dev/null +++ b/power-utils/src/main/java/org/nanoboot/powerframework/utils/dependencies/DependencyResolverJGraphTImpl.java @@ -0,0 +1,61 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils.dependencies; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import org.jgrapht.Graph; +import org.jgrapht.graph.DefaultEdge; +import org.jgrapht.graph.DirectedAcyclicGraph; +import org.jgrapht.traverse.TopologicalOrderIterator; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class DependencyResolverJGraphTImpl implements DependencyResolver{ + public List resolve(List dependencyNodesIn) { + // DirectAcyclicGraph to prevent circular dependency + Graph directedGraph = new DirectedAcyclicGraph<>(DefaultEdge.class); + List dependencyNodes = dependencyNodesIn; + Map taskNameToTaskMap = dependencyNodes.stream() + .collect(Collectors.toMap(task -> task.getName(), task -> task)); + for (DependencyNode task : dependencyNodes) { + directedGraph.addVertex(task); + for (String predecessor : task.getDependencies()) { + DependencyNode predecessorTask = taskNameToTaskMap.get(predecessor); + directedGraph.addVertex(predecessorTask); + directedGraph.addEdge(predecessorTask, task); + } + } + TopologicalOrderIterator moreDependencyFirstIterator = new TopologicalOrderIterator<>( + directedGraph); + List result = new ArrayList<>(); + moreDependencyFirstIterator.forEachRemaining(dependencyNode -> result.add(dependencyNode.getName())); + return result; + } + +} diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/minitext/.gitkeep b/power-utils/src/main/java/org/nanoboot/powerframework/utils/minitext/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/package-info.java b/power-utils/src/main/java/org/nanoboot/powerframework/utils/package-info.java new file mode 100644 index 0000000..d2069de --- /dev/null +++ b/power-utils/src/main/java/org/nanoboot/powerframework/utils/package-info.java @@ -0,0 +1,27 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * Utils. + * + * @author Robert Vokac + * @since 0.0.0 + */ +package org.nanoboot.powerframework.utils; diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/proxy/MethodInvoker.java b/power-utils/src/main/java/org/nanoboot/powerframework/utils/proxy/MethodInvoker.java new file mode 100644 index 0000000..02fa161 --- /dev/null +++ b/power-utils/src/main/java/org/nanoboot/powerframework/utils/proxy/MethodInvoker.java @@ -0,0 +1,33 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils.proxy; + +import java.lang.reflect.Method; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public interface MethodInvoker { + Object invoke(Object original, Object proxy, Method method, Object[] args) throws Exception; +} diff --git a/power-utils/src/main/java/org/nanoboot/powerframework/utils/proxy/ProxyUtils.java b/power-utils/src/main/java/org/nanoboot/powerframework/utils/proxy/ProxyUtils.java new file mode 100644 index 0000000..4c26c93 --- /dev/null +++ b/power-utils/src/main/java/org/nanoboot/powerframework/utils/proxy/ProxyUtils.java @@ -0,0 +1,136 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils.proxy; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.List; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class ProxyUtils { + + private static class InvocationHandlerImpl implements InvocationHandler { + + private final T original; + private final MethodInvoker methodInvoker; + + public InvocationHandlerImpl(T original, MethodInvoker methodInvoker) { + this.original = original; + this.methodInvoker = methodInvoker; + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Exception { + return this.methodInvoker.invoke(original, proxy, method, args); + } + } + + + + public static void main(String[] args) { + // class ListHandler implements InvocationHandler { + // + // private final List originalList; + // + // public ListHandler(List originalList) { + // this.originalList = originalList; + // } + // + // @Override + // public Object invoke(Object proxy, Method method, Object[] args) throws Exception { + // StringBuilder argsAsOneString = new StringBuilder(); + // if (args != null) { + // for (Object arg : args) { + // argsAsOneString.append(arg).append(", "); + // } + // } + // String argsAsOneStringStr = argsAsOneString.toString(); + // if (!argsAsOneStringStr.isEmpty()) { + // argsAsOneStringStr = argsAsOneStringStr.substring(0, argsAsOneStringStr.length() - 2); + // } + // System.out.println("Calling List method: " + method.getName() + "(" + argsAsOneStringStr + ")"); + // Object o = method.invoke(originalList, args); // zavolá původní metodu + // if (method.getName().equals("size")) { + // return ((Integer) o) * 2; + // } + // if (method.getName().equals("add")) { + // //again- for second time + // return method.invoke(originalList, args); // zavolá původní metodu + // } + // return o; + // } + // } + + List list = new ArrayList<>(); + + // List proxyList = (List) Proxy.newProxyInstance(List.class.getClassLoader(), + // new Class[] {List.class}, new ListHandler(list)); + + MethodInvoker methodInvoker = new MethodInvoker() { + @Override + public Object invoke(Object original, Object proxy, Method method, Object[] args) throws Exception { + StringBuilder argsAsOneString = new StringBuilder(); + if (args != null) { + for (Object arg : args) { + argsAsOneString.append(arg).append(", "); + } + } + String argsAsOneStringStr = argsAsOneString.toString(); + if (!argsAsOneStringStr.isEmpty()) { + argsAsOneStringStr = argsAsOneStringStr.substring(0, argsAsOneStringStr.length() - 2); + } + System.out.println("Calling List method: " + method.getName() + "(" + argsAsOneStringStr + ")"); + Object o = method.invoke(original, args); // zavolá původní metodu + if (method.getName().equals("size")) { + return ((Integer) o) * 2; + } + if (method.getName().equals("add")) { + //again- for second time + return method.invoke(original, args); // zavolá původní metodu + } + return o; + } + }; + List proxyList2 = createProxy(list, List.class, methodInvoker); + proxyList2.add("ahoj"); + proxyList2.add("dobry den"); + proxyList2.add("na shledanou"); + proxyList2.add("zdar"); + System.out.println("proxyList.size()=" + proxyList2.size()); + proxyList2.get(0); + for (String s : proxyList2) { + System.out.println("s = " + s); + } + } + + public static T createProxy(T original, Class interfaceClazz, MethodInvoker methodInvoker) { + return (T) Proxy.newProxyInstance(interfaceClazz.getClassLoader(), + new Class[] {interfaceClazz}, new InvocationHandlerImpl(original, methodInvoker)); + } +} + + diff --git a/power-utils/src/main/resources/.gitkeep b/power-utils/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-utils/src/test/java/.gitkeep b/power-utils/src/test/java/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-utils/src/test/java/org/nanoboot/powerframework/utils/CommandReaderTest.java b/power-utils/src/test/java/org/nanoboot/powerframework/utils/CommandReaderTest.java new file mode 100644 index 0000000..05276a9 --- /dev/null +++ b/power-utils/src/test/java/org/nanoboot/powerframework/utils/CommandReaderTest.java @@ -0,0 +1,263 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils; + +import org.junit.Test; + +import static org.junit.Assert.*; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class CommandReaderTest { + + @Test(expected = UtilsException.class) + public void constructor_exception() { + //prepare + CommandReader commandReader = new CommandReader(null); + //execute + //assert + } + + @Test + public void size() { + //prepare + CommandReader commandReader = new CommandReader("A B C D E"); + //execute + //assert + assertEquals(5, commandReader.size()); + } + + @Test + public void current() { + //prepare + CommandReader commandReader = new CommandReader("A B C D E"); + //execute + //assert + assertNull(commandReader.current()); + commandReader.next(); + assertEquals("A", commandReader.current()); + commandReader.next(); + assertEquals("B", commandReader.current()); + commandReader.nextPreview(); + assertEquals("B", commandReader.current()); + } + + @Test + public void hasNext() { + //prepare + CommandReader commandReader = new CommandReader("A B C D E"); + //execute + //assert + assertTrue(commandReader.hasNext()); + commandReader.next(); + assertTrue(commandReader.hasNext()); + commandReader.next(); + assertTrue(commandReader.hasNext()); + commandReader.next(); + assertTrue(commandReader.hasNext()); + commandReader.next(); + assertTrue(commandReader.hasNext()); + commandReader.next(); + assertFalse(commandReader.hasNext()); + } + + @Test + public void next() { + //prepare + CommandReader commandReader = new CommandReader("A B C D E"); + //execute + //assert + assertEquals("A", commandReader.next()); + assertEquals("B", commandReader.next()); + assertEquals("C", commandReader.next()); + assertEquals("D", commandReader.nextPreview()); + assertEquals("D", commandReader.next()); + assertEquals("E", commandReader.next()); + assertFalse(commandReader.hasNext()); + } + @Test(expected = UtilsException.class) + public void next_exception() { + //prepare + CommandReader commandReader = new CommandReader("A B C D E"); + //execute + //assert + commandReader.next(); + commandReader.next(); + commandReader.next(); + commandReader.next(); + commandReader.next(); + commandReader.next(); + } + + @Test + public void nextPreview() { + //prepare + CommandReader commandReader = new CommandReader("A B C D E"); + //execute + //assert + assertEquals("A", commandReader.next()); + assertEquals("B", commandReader.nextPreview()); + assertEquals("B", commandReader.nextPreview()); + assertEquals("B", commandReader.nextPreview()); + assertEquals("B", commandReader.nextPreview()); + assertEquals("B", commandReader.next()); + assertEquals("C", commandReader.next()); + assertEquals("D", commandReader.next()); + assertEquals("E", commandReader.nextPreview()); + assertEquals("E", commandReader.nextPreview()); + assertEquals("E", commandReader.nextPreview()); + assertEquals("E", commandReader.next()); + } + + @Test + public void getCommandByNumber() { + //prepare + CommandReader commandReader = new CommandReader("A B C D E"); + //execute + //assert + assertEquals("A", commandReader.getCommandByNumber(1)); + assertEquals("B", commandReader.getCommandByNumber(2)); + assertEquals("C", commandReader.getCommandByNumber(3)); + assertEquals("D", commandReader.getCommandByNumber(4)); + assertEquals("E", commandReader.getCommandByNumber(5)); + } + + @Test(expected = UtilsException.class) + public void getCommandByNumber_exception1() { + //prepare + CommandReader commandReader = new CommandReader("A B C D E"); + //execute + //assert + commandReader.getCommandByNumber(0); + } + + @Test(expected = UtilsException.class) + public void getCommandByNumber_exception2() { + //prepare + CommandReader commandReader = new CommandReader("A B C D E"); + //execute + //assert + commandReader.getCommandByNumber(6); + } + + @Test + public void reset() { + //prepare + CommandReader commandReader = new CommandReader("A B C D E"); + //execute + commandReader.next(); + commandReader.next(); + commandReader.next(); + commandReader.reset(); + //assert + assertEquals("A", commandReader.next()); + assertEquals("B", commandReader.next()); + assertEquals("C", commandReader.next()); + commandReader.reset(); + assertEquals("A", commandReader.next()); + assertEquals("B", commandReader.next()); + } + + @Test + public void isNumberValid() { + //prepare + CommandReader commandReader = new CommandReader("A B C D E"); + //execute + //assert + for(int number = -5; number < 20; number++) { + boolean numberIsValid = commandReader.isNumberValid(number); + if (number >= 1 && number <= 5) { + assertTrue(numberIsValid); + } else { + assertFalse(numberIsValid); + } + } + } + + @Test + public void nextAsInt() { + //prepare + CommandReader commandReader = new CommandReader("A B 4 D E"); + //execute + commandReader.next(); + commandReader.next(); + //assert + assertEquals(4, commandReader.nextAsInt()); + } + + @Test + public void currentNumber() { + //prepare + CommandReader commandReader = new CommandReader("A B C D E"); + //execute + //assert + assertEquals(0, commandReader.currentNumber()); + commandReader.next(); + assertEquals(1, commandReader.currentNumber()); + commandReader.next(); + assertEquals(2, commandReader.currentNumber()); + commandReader.next(); + assertEquals(3, commandReader.currentNumber()); + commandReader.next(); + assertEquals(4, commandReader.currentNumber()); + commandReader.next(); + assertEquals(5, commandReader.currentNumber()); + } + + @Test + public void toArray() { + //prepare + CommandReader commandReader = new CommandReader("A B C D E"); + //execute + //assert + assertArrayEquals((new String[] {"A", "B", "C", "D", "E"}), commandReader.toArray()); + } + + @Test + public void toStringForDebuggingPurposes() { + //prepare + CommandReader commandReader = new CommandReader("A B C D E"); + //execute + commandReader.next(); + commandReader.next(); + commandReader.next(); + commandReader.next(); + //assert + assertEquals("A B C [D] E", commandReader.toStringForDebuggingPurposes()); + } + + @Test + public void testToString() { + //prepare + CommandReader commandReader = new CommandReader("A B C D E"); + //execute + commandReader.next(); + commandReader.next(); + commandReader.next(); + commandReader.next(); + //assert + assertEquals("A :: B :: C :: D :: E :: ", commandReader.toString()); + } +} diff --git a/power-utils/src/test/java/org/nanoboot/powerframework/utils/NamingConventionConvertorTest.java b/power-utils/src/test/java/org/nanoboot/powerframework/utils/NamingConventionConvertorTest.java new file mode 100644 index 0000000..74382c1 --- /dev/null +++ b/power-utils/src/test/java/org/nanoboot/powerframework/utils/NamingConventionConvertorTest.java @@ -0,0 +1,224 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils; + +import org.junit.Test; + +import static org.junit.Assert.*; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class NamingConventionConvertorTest { + + private static final String DATABASE_STRING = "MY_BEST_FRIEND"; + private static final String HUMAN_STRING = "my best friend"; + private static final String JAVA_STRING = "myBestFriend"; + private static final String UNKNOWN_STRING = "my-best-friend"; + @Test + public void convert_database_human() { + //prepare + String input = DATABASE_STRING; + String expected = HUMAN_STRING; + String returned; + NamingConvention inputNamingConvention = NamingConvention.DATABASE; + NamingConvention outputNamingConvention = NamingConvention.HUMAN; + //execute + returned = NamingConventionConvertor.convert(input, inputNamingConvention, outputNamingConvention); + //assert + assertEquals(expected, returned); + } + @Test + public void convert_database_java() { + //prepare + String input = DATABASE_STRING; + String expected = JAVA_STRING; + String returned; + NamingConvention inputNamingConvention = NamingConvention.DATABASE; + NamingConvention outputNamingConvention = NamingConvention.JAVA_FIELD; + //execute + returned = NamingConventionConvertor.convert(input, inputNamingConvention, outputNamingConvention); + //assert + assertEquals(expected, returned); + } + @Test + public void convert_human_database() { + //prepare + String input = HUMAN_STRING; + String expected = DATABASE_STRING; + String returned; + NamingConvention inputNamingConvention = NamingConvention.HUMAN; + NamingConvention outputNamingConvention = NamingConvention.DATABASE; + //execute + returned = NamingConventionConvertor.convert(input, inputNamingConvention, outputNamingConvention); + //assert + assertEquals(expected, returned); + } + @Test + public void convert_human_java() { + //prepare + String input = HUMAN_STRING; + String expected = JAVA_STRING; + String returned; + NamingConvention inputNamingConvention = NamingConvention.HUMAN; + NamingConvention outputNamingConvention = NamingConvention.JAVA_FIELD; + //execute + returned = NamingConventionConvertor.convert(input, inputNamingConvention, outputNamingConvention); + //assert + assertEquals(expected, returned); + } + @Test + public void convert_java_database() { + //prepare + String input = JAVA_STRING; + String expected = DATABASE_STRING; + String returned; + NamingConvention inputNamingConvention = NamingConvention.JAVA_FIELD; + NamingConvention outputNamingConvention = NamingConvention.DATABASE; + //execute + returned = NamingConventionConvertor.convert(input, inputNamingConvention, outputNamingConvention); + //assert + assertEquals(expected, returned); + } + @Test + public void convert_java_human() { + //prepare + String input = JAVA_STRING; + String expected = HUMAN_STRING; + String returned; + NamingConvention inputNamingConvention = NamingConvention.JAVA_FIELD; + NamingConvention outputNamingConvention = NamingConvention.HUMAN; + //execute + returned = NamingConventionConvertor.convert(input, inputNamingConvention, outputNamingConvention); + //assert + assertEquals(expected, returned); + } + + @Test + public void convert_database_database() { + //prepare + String input = DATABASE_STRING; + String expected = DATABASE_STRING; + String returned; + NamingConvention inputNamingConvention = NamingConvention.DATABASE; + NamingConvention outputNamingConvention = NamingConvention.DATABASE; + //execute + returned = NamingConventionConvertor.convert(input, inputNamingConvention, outputNamingConvention); + //assert + assertEquals(expected, returned); + } + + @Test + public void convert_human_human() { + //prepare + String input = HUMAN_STRING; + String expected = HUMAN_STRING; + String returned; + NamingConvention inputNamingConvention = NamingConvention.HUMAN; + NamingConvention outputNamingConvention = NamingConvention.HUMAN; + //execute + returned = NamingConventionConvertor.convert(input, inputNamingConvention, outputNamingConvention); + //assert + assertEquals(expected, returned); + } + + @Test + public void convert_java_java() { + //prepare + String input = JAVA_STRING; + String expected = JAVA_STRING; + String returned; + NamingConvention inputNamingConvention = NamingConvention.JAVA_FIELD; + NamingConvention outputNamingConvention = NamingConvention.JAVA_FIELD; + //execute + returned = NamingConventionConvertor.convert(input, inputNamingConvention, outputNamingConvention); + //assert + assertEquals(expected, returned); + } + + @Test(expected = UtilsException.class) + public void convert_java_unknwon() { + //prepare + String input = JAVA_STRING; + String expected = UNKNOWN_STRING; + String returned; + NamingConvention inputNamingConvention = NamingConvention.JAVA_FIELD; + NamingConvention outputNamingConvention = NamingConvention.UNKNOWN; + //execute + returned = NamingConventionConvertor.convert(input, inputNamingConvention, outputNamingConvention); + //assert + assertEquals(expected, returned); + } + + @Test(expected = UtilsException.class) + public void convert_exception() { + //prepare + String input = JAVA_STRING; + String expected = JAVA_STRING; + String returned; + NamingConvention inputNamingConvention = NamingConvention.JAVA_FIELD; + NamingConvention outputNamingConvention = null; + //execute + returned = NamingConventionConvertor.convert(input, inputNamingConvention, outputNamingConvention); + //assert + assertEquals(expected, returned); + } + @Test(expected = UtilsException.class) + public void convert_invalidArguments_exception() { + //prepare + String input = HUMAN_STRING; + String expected = DATABASE_STRING; + String returned; + NamingConvention inputNamingConvention = NamingConvention.JAVA_FIELD; + NamingConvention outputNamingConvention = NamingConvention.DATABASE; + //execute + returned = NamingConventionConvertor.convert(input, inputNamingConvention, outputNamingConvention); + //assert + assertEquals(expected, returned); + } + + @Test + public void detectNamingConvention() { + assertEquals(NamingConvention.DATABASE, NamingConventionConvertor.detectNamingConvention("ABC_DEF_GHI")); + assertEquals(NamingConvention.HUMAN, NamingConventionConvertor.detectNamingConvention("abc def ghi")); + assertEquals(NamingConvention.JAVA_FIELD, NamingConventionConvertor.detectNamingConvention("abcDefGhi")); + } + @Test(expected = UtilsException.class) + public void detectNamingConvention2() { + assertEquals(NamingConvention.DATABASE, NamingConventionConvertor.detectNamingConvention("ABC_DEF GHI")); + } + + @Test(expected = UtilsException.class) + public void convert_unknwon_java() { + //prepare + String input = UNKNOWN_STRING; + String expected = JAVA_STRING; + String returned; + NamingConvention inputNamingConvention = NamingConvention.UNKNOWN; + NamingConvention outputNamingConvention = NamingConvention.JAVA_FIELD; + //execute + returned = NamingConventionConvertor.convert(input, inputNamingConvention, outputNamingConvention); + //assert + assertEquals(expected, returned); + } +} diff --git a/power-utils/src/test/java/org/nanoboot/powerframework/utils/StringUtilsTest.java b/power-utils/src/test/java/org/nanoboot/powerframework/utils/StringUtilsTest.java new file mode 100644 index 0000000..20c4e72 --- /dev/null +++ b/power-utils/src/test/java/org/nanoboot/powerframework/utils/StringUtilsTest.java @@ -0,0 +1,55 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils; + +import org.junit.Test; + +import static org.junit.Assert.*; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class StringUtilsTest { + + @Test + public void appendObjects() { + String result = StringUtils.appendObjects(6, "b", true, 5l, "gf", "abc"); + assertEquals("6btrue5gfabc", result); + } + + @Test + public void isEmpty() { + assertTrue(StringUtils.isEmpty("")); + assertFalse(StringUtils.isEmpty("abc")); + } + + @Test + public void toInt() { + assertEquals(5, StringUtils.toInt("5")); + } + + @Test + public void toLines() { + assertArrayEquals(new String[] {"a", "b", "c"}, StringUtils.toLines("a\nb\nc")); + } +} diff --git a/power-utils/src/test/java/org/nanoboot/powerframework/utils/UtilsExceptionTest.java b/power-utils/src/test/java/org/nanoboot/powerframework/utils/UtilsExceptionTest.java new file mode 100644 index 0000000..a492ed7 --- /dev/null +++ b/power-utils/src/test/java/org/nanoboot/powerframework/utils/UtilsExceptionTest.java @@ -0,0 +1,37 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils; + +import org.junit.Test; + +import static org.junit.Assert.*; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class UtilsExceptionTest { + @Test + public void constructor_String() { + assertEquals("An error", new UtilsException("An error").getMessage()); + } +} diff --git a/power-utils/src/test/java/org/nanoboot/powerframework/utils/dependencies/DependencyResolverJGraphTImplTest.java b/power-utils/src/test/java/org/nanoboot/powerframework/utils/dependencies/DependencyResolverJGraphTImplTest.java new file mode 100644 index 0000000..b7b71b6 --- /dev/null +++ b/power-utils/src/test/java/org/nanoboot/powerframework/utils/dependencies/DependencyResolverJGraphTImplTest.java @@ -0,0 +1,83 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.utils.dependencies; + +import org.junit.Test; + +import static org.junit.Assert.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class DependencyResolverJGraphTImplTest { + + public DependencyResolverJGraphTImplTest() { + } + + /** + * Test of resolve method, of class DependencyResolverJGraphTImpl. + */ + @Test + public void testResolve() { + System.out.println("resolve"); + //prepare + List dependencyNodes = new ArrayList<>(); + + dependencyNodes.add(new DependencyNode("development", Arrays.asList("task"))); + dependencyNodes.add(new DependencyNode("task")); + dependencyNodes.add(new DependencyNode("person", Arrays.asList("task"))); + dependencyNodes.add(new DependencyNode("encyclopedia")); + dependencyNodes.add(new DependencyNode("system")); + dependencyNodes.add(new DependencyNode("favorite", Arrays.asList())); + dependencyNodes.add(new DependencyNode("action-log", Arrays.asList())); + dependencyNodes.add(new DependencyNode("pinning", Arrays.asList())); + dependencyNodes.add(new DependencyNode("reminder", Arrays.asList())); + dependencyNodes.add(new DependencyNode("whining", Arrays.asList())); + for (DependencyNode dn : dependencyNodes) { + if (!dn.getName().equals("system")) { + dn.getDependencies().add("system"); + } + if (dn.getName().equals("action-log") || dn.getName().equals("favorite") || dn.getName().equals("pinning") || dn.getName().equals("reminder") || dn.getName().equals("whining") || dn.getName().equals("system")) { + //nothing to do + } else { + dn.getDependencies().addAll(Arrays.asList("action-log", "favorite", "pinning", "reminder", "whining")); + } + } + + DependencyResolverJGraphTImpl instance = new DependencyResolverJGraphTImpl(); + List expResult = new ArrayList<>(); + expResult.addAll(Arrays.asList("system", "favorite", "action-log", "pinning", "reminder", "whining", "task", "encyclopedia", "development", "person")); + //execute + List result = instance.resolve(dependencyNodes); + for (String s : result) { + } + //assert + assertEquals(expResult, result); + } + +} diff --git a/power-view/pom.xml b/power-view/pom.xml new file mode 100644 index 0000000..af7e0f3 --- /dev/null +++ b/power-view/pom.xml @@ -0,0 +1,66 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-view + jar + + Power View + View functionality for the Power library + + 19 + + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + + org.nanoboot.powerframework + power-random + ${power.version} + + + + junit + junit + 4.12 + test + + + org.openjfx + javafx-controls + ${javafx.version} + + + diff --git a/power-view/src/main/java/module-info.java b/power-view/src/main/java/module-info.java new file mode 100644 index 0000000..2707477 --- /dev/null +++ b/power-view/src/main/java/module-info.java @@ -0,0 +1,38 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +module powerframework.view { + requires javafx.graphics; + requires javafx.controls; + requires java.logging; + requires powerframework.random; + requires powerframework.core; + exports org.nanoboot.powerframework.view; + exports org.nanoboot.powerframework.view.window; + exports org.nanoboot.powerframework.view.window.controls; + exports org.nanoboot.powerframework.view.layouts; + exports org.nanoboot.powerframework.view.boxes; +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/EnumColour.java b/power-view/src/main/java/org/nanoboot/powerframework/view/EnumColour.java similarity index 81% rename from src/main/java/org/nanoboot/powerframework/simplicity/EnumColour.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/EnumColour.java index bea95c4..882c9ce 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/EnumColour.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/EnumColour.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,16 +18,24 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity; +package org.nanoboot.powerframework.view; -import org.nanoboot.powerframework.PowerRuntimeException; -import org.nanoboot.powerframework.pseudorandom.PseudoRandomGenerator; +import org.nanoboot.powerframework.random.generators.linearcongruent.combined.w5.W5RandomGenerator; /** * Represents one of 16 colours, or there is no colour. * - * @author Robert Vokac robertvokac@nanoboot.org + * @author Robert Vokáč robertvokac@nanoboot.org */ +//To be removed +@Deprecated +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + public enum EnumColour { /** @@ -113,14 +121,15 @@ public enum EnumColour { /** * - * @param number - * @return + * @param numberIn number representation of the enum EnumColour + * + * @return EnumColour instance based on the numberIn value */ - public static EnumColour convertNumberToEnumColour(int number) {//NOSONAR - if (!isNumberRepresentationValid(number)) { - throw new PowerRuntimeException("Number you want co convert to EnumColour must be at least 0 and at most 16."); + public static EnumColour convertNumberToEnumColour(int numberIn) {//NOSONAR + if(!isNumberRepresentationValid(numberIn)) { + throw new ViewException("Number you want co convert to EnumColour must be at least 0 and at most 16."); } - switch (number) { + switch (numberIn) { case 0: return EnumColour.NOCOLOUR; case 1: @@ -170,7 +179,7 @@ public enum EnumColour { * @return random EnumColour */ public static EnumColour getRandom() { - int i = PseudoRandomGenerator.getInstance().getInt(1, 16); + int i = W5RandomGenerator.getStaticInstance().nextInt(1, 16); return EnumColour.convertNumberToEnumColour(i); } } diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/JavaFXApplication.java b/power-view/src/main/java/org/nanoboot/powerframework/view/JavaFXApplication.java similarity index 83% rename from src/main/java/org/nanoboot/powerframework/simplicity/JavaFXApplication.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/JavaFXApplication.java index c956140..1ccec08 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/JavaFXApplication.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/JavaFXApplication.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,30 +18,31 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity; +package org.nanoboot.powerframework.view; -import javafx.application.Application; -import javafx.stage.Stage; +import javafx.application.*; +import javafx.stage.*; /** * Represents Java FX application. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public class JavaFXApplication extends Application { - void launchJavaFXApplication() { - launch(); - } - static void startJavaFXApplication() { JavaFXApplication javaFXApplication = new JavaFXApplication(); javaFXApplication.launchJavaFXApplication(); } + void launchJavaFXApplication() { + launch(); + } + @Override public void start(final Stage stage) { Screen.initScreen(); - Simplicity.getSimplicityRunner().run(); + View.getSimplicityRunner().runApp(); } } diff --git a/power-view/src/main/java/org/nanoboot/powerframework/view/PowerApplication.java b/power-view/src/main/java/org/nanoboot/powerframework/view/PowerApplication.java new file mode 100644 index 0000000..5b2da6c --- /dev/null +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/PowerApplication.java @@ -0,0 +1,43 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.view; + +/** + * Power application. + * + * @author Robert Vokac + * @since 0.0.0 + */ +public final class PowerApplication { + /** + * Constructor. + */ + private PowerApplication() { + //Not meant to be instantiated. + } + /** + * Runs the Power application. + * @param classInstance class instance + */ + public static void run(final Class classInstance) { + //todo + } +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/Screen.java b/power-view/src/main/java/org/nanoboot/powerframework/view/Screen.java similarity index 91% rename from src/main/java/org/nanoboot/powerframework/simplicity/Screen.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/Screen.java index 9e7d43a..ccdebf0 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/Screen.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/Screen.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,30 +18,22 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity; +package org.nanoboot.powerframework.view; import javafx.geometry.Rectangle2D; /** * Represents screen. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ -public final class Screen { +public class Screen { private static double dpmm; private static double dpi; private static double zoom = 100; - /** - * Constructor - * - * Not meant to be instantiated. - */ - private Screen() { - //Not meant to be instantiated. - } - /** * Initialises screen. */ @@ -71,12 +63,12 @@ public final class Screen { */ private static void updateDpmm() { double currentDpi = getDpi(); - if (currentDpi > 0) { + if(currentDpi > 0) { dpmm = currentDpi / 25.4; } else { dpmm = 6; } - dpmm = dpmm * (getZoom() / 100); + dpmm *= (getZoom() / 100); } /** @@ -97,7 +89,7 @@ public final class Screen { /** * - * @param zoom 100% is 100, 100% is default + * @param newZoom 100 for 100% */ public static void setZoom(double newZoom) { zoom = newZoom; @@ -143,4 +135,13 @@ public final class Screen { public static int getVisualHeight() { return (int) getVisualBounds().getHeight(); } + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private Screen() { + //Not meant to be instantiated. + } } diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/Simplicity.java b/power-view/src/main/java/org/nanoboot/powerframework/view/View.java similarity index 73% rename from src/main/java/org/nanoboot/powerframework/simplicity/Simplicity.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/View.java index 14fc4da..8f21c2f 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/Simplicity.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/View.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,39 +18,33 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity; +package org.nanoboot.powerframework.view; import javafx.application.Platform; -import org.nanoboot.powerframework.simplicity.window.WindowColourSkin; +import org.nanoboot.powerframework.view.window.WindowColourSkin; /** * Represents Simplicity package main class. * - * @author Robert Vokac robertvokac@nanoboot.org + * + * @author Robert Vokac + * @since 0.0.0 */ -public final class Simplicity { +public class View { - private static SimplicityRunnerI simplicityRunner; + private static ViewRunner simplicityRunner; private static WindowColourSkin defaultWindowColourSkin; - /** - * Constructor - * - * Not meant to be instantiated. - */ - private Simplicity() { - //Not meant to be instantiated. - Platform.setImplicitExit(false); - } /** * This method must be called before using Simplicity. * * @param runner This object implements runObjectI interface and its method * run contains some logic. - * @param defaultWindowColourSkin + * @param defaultWindowColourSkin WindowColourSkin instance used as default in the Simplicity library. */ - public static void startSimplicity(SimplicityRunnerI runner, WindowColourSkin defaultWindowColourSkin) { - Simplicity.setDefaultWindowColourSkin(defaultWindowColourSkin); + public static void startSimplicity(ViewRunner runner, + WindowColourSkin defaultWindowColourSkin) { + View.setDefaultWindowColourSkin(defaultWindowColourSkin); simplicityRunner = runner; JavaFXApplication.startJavaFXApplication(); } @@ -66,7 +60,7 @@ public final class Simplicity { * * @return Simplicity runner */ - public static SimplicityRunnerI getSimplicityRunner() { + public static ViewRunner getSimplicityRunner() { return simplicityRunner; } @@ -84,21 +78,25 @@ public final class Simplicity { * @return default window colour skin */ public static WindowColourSkin getDefaultWindowColourSkin() { - return Simplicity.defaultWindowColourSkin; + return View.defaultWindowColourSkin; } /** * - * @param windowColourSkin + * @param windowColourSkin WindowColourSkin instance */ public static void setDefaultWindowColourSkin(WindowColourSkin windowColourSkin) { - Simplicity.defaultWindowColourSkin = windowColourSkin; + View.defaultWindowColourSkin = windowColourSkin; } + /** + * + * @return information about Simplicity as String + */ public static String getInformation() { StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("\ndefaultWindowColourSkin: ").append(Simplicity.getDefaultWindowColourSkin()); - stringBuilder.append("\ndpmm: ").append(Simplicity.getDpmm()); + stringBuilder.append("\ndefaultWindowColourSkin: ").append(View.getDefaultWindowColourSkin()); + stringBuilder.append("\ndpmm: ").append(View.getDpmm()); stringBuilder.append("\nzoom: ").append(Screen.getZoom()); stringBuilder.append("\ndpi: ").append(Screen.getDpi()); stringBuilder.append("\nheight: ").append(Screen.getHeight()); @@ -107,4 +105,14 @@ public final class Simplicity { stringBuilder.append("\nvisual width: ").append(Screen.getVisualWidth()); return stringBuilder.toString(); } + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private View() { + //Not meant to be instantiated. + Platform.setImplicitExit(false); + } } diff --git a/power-view/src/main/java/org/nanoboot/powerframework/view/ViewException.java b/power-view/src/main/java/org/nanoboot/powerframework/view/ViewException.java new file mode 100644 index 0000000..5bc0b2b --- /dev/null +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/ViewException.java @@ -0,0 +1,41 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.view; + +import org.nanoboot.powerframework.core.PowerException; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class ViewException extends PowerException { + + /** + * + * @param messageIn exception description + */ + public ViewException(String messageIn) { + super(messageIn); + } + +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/SimplicityRunnerI.java b/power-view/src/main/java/org/nanoboot/powerframework/view/ViewRunner.java similarity index 82% rename from src/main/java/org/nanoboot/powerframework/simplicity/SimplicityRunnerI.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/ViewRunner.java index 7fdf9a8..212cf18 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/SimplicityRunnerI.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/ViewRunner.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,19 +18,20 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity; +package org.nanoboot.powerframework.view; /** * Represents entry point for Simplicity application. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ @FunctionalInterface -public interface SimplicityRunnerI { +public interface ViewRunner { /** * Contains logic called after Simplicity was started. */ - public void run(); + public void runApp(); } diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/boxes/AlertBox.java b/power-view/src/main/java/org/nanoboot/powerframework/view/boxes/AlertBox.java similarity index 66% rename from src/main/java/org/nanoboot/powerframework/simplicity/boxes/AlertBox.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/boxes/AlertBox.java index ac2c7b0..f448860 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/boxes/AlertBox.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/boxes/AlertBox.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,42 +18,46 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.boxes; +package org.nanoboot.powerframework.view.boxes; -import org.nanoboot.powerframework.simplicity.Simplicity; -import org.nanoboot.powerframework.simplicity.window.controls.Button; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.scene.transform.Rotate; +import org.nanoboot.powerframework.view.View; +import org.nanoboot.powerframework.view.window.controls.Button; /** * Represents a alert box- a window used to alarm user. * - * @author Robert Vokac robertvokac@nanoboot.orgt Vokáč robertvokac@nanoboot.org + * + * @author Robert Vokac + * @since 0.0.0 */ public class AlertBox extends Box { - private AlertBox(String titleText, String text) { - super(titleText, text); - } - /** * - * @param windowColourSkin * @param titleText * @param text */ - public static void showBox(String titleText, String text) { + public static void showBox(String titleText, + String text) { AlertBox alertBox = new AlertBox(titleText, text); alertBox.showAndWait(); } - void init() { + private AlertBox(String titleText, + String text) { + super(titleText, text); + } + + @Override + void initBox() { circle.setFill(Color.rgb(237, 103, 103)); - Rectangle rectangle1 = new Rectangle(2 * Simplicity.getDpmm(), 8 * Simplicity.getDpmm()); - Rectangle rectangle2 = new Rectangle(2 * Simplicity.getDpmm(), 8 * Simplicity.getDpmm()); - Rotate rotate45 = new Rotate(45, 1.0 * Simplicity.getDpmm(), 4.0 * Simplicity.getDpmm()); - Rotate rotateMinus45 = new Rotate(-45, 1.0 * Simplicity.getDpmm(), 4.0 * Simplicity.getDpmm()); + Rectangle rectangle1 = new Rectangle(2 * View.getDpmm(), 8 * View.getDpmm()); + Rectangle rectangle2 = new Rectangle(2 * View.getDpmm(), 8 * View.getDpmm()); + Rotate rotate45 = new Rotate(45, 1.0 * View.getDpmm(), 4.0 * View.getDpmm()); + Rotate rotateMinus45 = new Rotate(-45, 1.0 * View.getDpmm(), 4.0 * View.getDpmm()); rectangle1.getTransforms().addAll(rotate45); rectangle2.getTransforms().addAll(rotateMinus45); this.icon.getChildren().addAll(rectangle1, rectangle2); @@ -64,7 +68,7 @@ public class AlertBox extends Box { Button okButton = new Button("OK"); this.placeForButtons.getChildren().add(okButton); - okButton.setMaxWidth(20 * Simplicity.getDpmm()); + okButton.setMaxWidth(20 * View.getDpmm()); okButton.setOnAction(this::handleOKButtonAction); } } diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/boxes/Box.java b/power-view/src/main/java/org/nanoboot/powerframework/view/boxes/Box.java similarity index 68% rename from src/main/java/org/nanoboot/powerframework/simplicity/boxes/Box.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/boxes/Box.java index f1cef56..2136b10 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/boxes/Box.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/boxes/Box.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,11 +18,8 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.boxes; +package org.nanoboot.powerframework.view.boxes; -import org.nanoboot.powerframework.simplicity.window.SLayout; -import org.nanoboot.powerframework.simplicity.Simplicity; -import org.nanoboot.powerframework.simplicity.window.Window; import javafx.event.ActionEvent; import javafx.geometry.Pos; import javafx.geometry.VPos; @@ -33,11 +30,16 @@ import javafx.scene.shape.Circle; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Modality; +import org.nanoboot.powerframework.view.View; +import org.nanoboot.powerframework.view.layouts.SLayout; +import org.nanoboot.powerframework.view.window.Window; /** * Represents a box- a window used to give information to user. * - * @author Robert Vokac robertvokac@nanoboot.orgt Vokáč robertvokac@nanoboot.org + * + * @author Robert Vokac + * @since 0.0.0 */ abstract class Box extends Window { @@ -46,10 +48,11 @@ abstract class Box extends Window { protected StackPane icon = new StackPane(); protected StackPane icon2 = new StackPane(); protected SLayout gridLayout = new SLayout(); - Circle circle = new Circle(6 * Simplicity.getDpmm()); + Circle circle = new Circle(6 * View.getDpmm()); protected StackPane placeForButtons = new StackPane(); - Box(String titleText, String text) { + Box(String titleText, + String text) { initModality(Modality.APPLICATION_MODAL); this.setWindowTitle(titleText); this.text = text; @@ -58,16 +61,16 @@ abstract class Box extends Window { this.showOnlyTheCloseButton(); RowConstraints rc2 = new RowConstraints(); - rc2.setMinHeight(12 * Simplicity.getDpmm()); - rc2.setMaxHeight(12 * Simplicity.getDpmm()); + rc2.setMinHeight(12 * View.getDpmm()); + rc2.setMaxHeight(12 * View.getDpmm()); rc2.setValignment(VPos.CENTER); ColumnConstraints cc1 = new ColumnConstraints(); - cc1.setMinWidth(12 * Simplicity.getDpmm()); - cc1.setMaxWidth(12 * Simplicity.getDpmm()); + cc1.setMinWidth(12 * View.getDpmm()); + cc1.setMaxWidth(12 * View.getDpmm()); ColumnConstraints cc2 = new ColumnConstraints(); - cc2.setMinWidth(text.length() * 4 * Simplicity.getDpmm()); - cc2.setMaxWidth(text.length() * 4 * Simplicity.getDpmm()); + cc2.setMinWidth(text.length() * 4 * View.getDpmm()); + cc2.setMaxWidth(text.length() * 4 * View.getDpmm()); this.gridLayout.getRowConstraints().addAll(rc2, this.gridLayout.getDataRowConstraint()); this.gridLayout.getColumnConstraints().addAll(cc1, cc2); @@ -77,20 +80,20 @@ abstract class Box extends Window { this.gridLayout.add(icon, 0, 0); Text newText = new Text(text); - newText.setFont(Font.font(3 * Simplicity.getDpmm())); + newText.setFont(Font.font(3 * View.getDpmm())); newText.setText(text); this.gridLayout.add(newText, 1, 0); this.gridLayout.add(this.placeForButtons, 0, 1, 2, 1); this.placeForButtons.setAlignment(Pos.CENTER); this.applicationArea.getChildren().add(gridLayout); - this.setHeight(4.5 * Simplicity.getDpmm() + 3 * 3 * Simplicity.getDpmm() + 12 * Simplicity.getDpmm() + 6 * Simplicity.getDpmm() + 2 / 3 * Simplicity.getDpmm()); - this.setWidth(text.length() * 2 * Simplicity.getDpmm() + 2 / 3 * Simplicity.getDpmm() + 9 * Simplicity.getDpmm() + 16 * Simplicity.getDpmm()); + this.setHeight(4.5 * View.getDpmm() + 3 * 3 * View.getDpmm() + 12 * View.getDpmm() + 6 * View.getDpmm() + 2 / 3 * View.getDpmm()); + this.setWidth(text.length() * 2 * View.getDpmm() + 2 / 3 * View.getDpmm() + 9 * View.getDpmm() + 16 * View.getDpmm()); - this.init(); + this.initBox(); } - abstract void init(); + abstract void initBox(); protected void handleOKButtonAction(ActionEvent event) { // Button was clicked, do something... @@ -99,7 +102,7 @@ abstract class Box extends Window { } @Override - public void initAreaForUserInteraction() { + public void initAreaForUserInteraction(Object... args) { } } diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/boxes/MessageBox.java b/power-view/src/main/java/org/nanoboot/powerframework/view/boxes/MessageBox.java similarity index 66% rename from src/main/java/org/nanoboot/powerframework/simplicity/boxes/MessageBox.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/boxes/MessageBox.java index 121fdd3..374a698 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/boxes/MessageBox.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/boxes/MessageBox.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,53 +18,58 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.boxes; +package org.nanoboot.powerframework.view.boxes; -import org.nanoboot.powerframework.simplicity.Simplicity; -import org.nanoboot.powerframework.simplicity.window.controls.Button; import javafx.geometry.Pos; +import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; +import org.nanoboot.powerframework.view.View; +import org.nanoboot.powerframework.view.window.controls.Button; /** * Represents a message box- a window used to inform user about something. * - * @author Robert Vokac robertvokac@nanoboot.orgt Vokáč robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ -public class MessageBox extends Box { - private MessageBox(String titleText, String text) { - super(titleText, text); - } +public class MessageBox extends Box { /** * - * @param windowColourSkin * @param titleText * @param text */ - public static void showBox(String titleText, String text) { + public static void showBox(String titleText, + String text) { MessageBox messageBox = new MessageBox(titleText, text); messageBox.showAndWait(); } - void init() { + private MessageBox(String titleText, + String text) { + super(titleText, text); + } + + @Override + void initBox() { circle.setFill(Color.rgb(114, 159, 207)); - Rectangle rectangle1 = new Rectangle(2 * Simplicity.getDpmm(), 5 * Simplicity.getDpmm()); - Rectangle rectangle2 = new Rectangle(2 * Simplicity.getDpmm(), 2 * Simplicity.getDpmm()); + Rectangle rectangle1 = new Rectangle(2 * View.getDpmm(), 5 * View.getDpmm()); + Rectangle rectangle2 = new Rectangle(2 * View.getDpmm(), 2 * View.getDpmm()); this.icon2.getChildren().addAll(rectangle1, rectangle2); this.icon.getChildren().add(icon2); - this.icon2.setAlignment(rectangle1, Pos.BOTTOM_CENTER); - this.icon2.setAlignment(rectangle2, Pos.TOP_CENTER); - this.icon2.setMaxHeight(8 * Simplicity.getDpmm()); + StackPane.setAlignment(rectangle1, Pos.BOTTOM_CENTER); + StackPane.setAlignment(rectangle2, Pos.TOP_CENTER); + this.icon2.setMaxHeight(8 * View.getDpmm()); rectangle1.setFill(Color.rgb(238, 238, 238)); rectangle2.setFill(Color.rgb(238, 238, 238)); Button okButton = new Button("OK"); this.placeForButtons.getChildren().add(okButton); - okButton.setMaxWidth(20 * Simplicity.getDpmm()); + okButton.setMaxWidth(20 * View.getDpmm()); okButton.setOnAction(this::handleOKButtonAction); } } diff --git a/power-view/src/main/java/org/nanoboot/powerframework/view/clocks/AnalogClock.java b/power-view/src/main/java/org/nanoboot/powerframework/view/clocks/AnalogClock.java new file mode 100644 index 0000000..87fda7c --- /dev/null +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/clocks/AnalogClock.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.view.clocks; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class AnalogClock { + +} diff --git a/power-view/src/main/java/org/nanoboot/powerframework/view/clocks/Clock.java b/power-view/src/main/java/org/nanoboot/powerframework/view/clocks/Clock.java new file mode 100644 index 0000000..c6633f7 --- /dev/null +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/clocks/Clock.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.view.clocks; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Clock { + +} diff --git a/power-view/src/main/java/org/nanoboot/powerframework/view/clocks/DigitalClock.java b/power-view/src/main/java/org/nanoboot/powerframework/view/clocks/DigitalClock.java new file mode 100644 index 0000000..7f97f92 --- /dev/null +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/clocks/DigitalClock.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.view.clocks; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class DigitalClock { + +} diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/CellLayout.java b/power-view/src/main/java/org/nanoboot/powerframework/view/layouts/CellLayout.java similarity index 74% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/CellLayout.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/layouts/CellLayout.java index 9432ce7..37b36e6 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/CellLayout.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/layouts/CellLayout.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,7 +18,7 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window; +package org.nanoboot.powerframework.view.layouts; import java.util.ArrayList; import java.util.List; @@ -29,27 +29,28 @@ import javafx.scene.layout.AnchorPane; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.RowConstraints; -import org.nanoboot.powerframework.PowerRuntimeException; -import org.nanoboot.powerframework.simplicity.Simplicity; +import org.nanoboot.powerframework.view.View; +import org.nanoboot.powerframework.view.ViewException; /** + * * - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ -public class CellLayout extends AnchorPane { + +public final class CellLayout extends AnchorPane { private static final RowConstraints dataRowConstraint = new RowConstraints(); private static final String PERCENT = "%"; private static final String MM = "mm"; - private final GridPane gridPane = new GridPane(); - static { - dataRowConstraint.setMinHeight(6 * Simplicity.getDpmm()); - dataRowConstraint.setMaxHeight(6 * Simplicity.getDpmm()); + dataRowConstraint.setMinHeight(6 * View.getDpmm()); + dataRowConstraint.setMaxHeight(6 * View.getDpmm()); dataRowConstraint.setValignment(VPos.CENTER); } + private final GridPane gridPane = new GridPane(); private final int rows; private final int columns; @@ -60,7 +61,9 @@ public class CellLayout extends AnchorPane { * @param columns * @param columnConstraintsString */ - public CellLayout(int columns, int rows, String columnConstraintsString) { + public CellLayout(int columns, + int rows, + String columnConstraintsString) { this.getChildren().add(gridPane); AnchorPane.setTopAnchor(gridPane, 0d); @@ -88,20 +91,20 @@ public class CellLayout extends AnchorPane { private void setColumnConstraints(String columnConstraintsString) { String[] columnConstraint = columnConstraintsString.split("\\s+"); - List list = new ArrayList(); + List list = new ArrayList<>(); for (String element : columnConstraint) { int number; ColumnConstraints tempColumnConstraints = new ColumnConstraints(); - if (element.endsWith(PERCENT)) { + if(element.endsWith(PERCENT)) { number = Integer.parseInt(element.substring(0, element.length() - 1)); tempColumnConstraints.setPercentWidth(number); - } else if (element.endsWith(MM)) { + } else if(element.endsWith(MM)) { number = Integer.parseInt(element.substring(0, element.length() - 2)); - double mmLenght = number * Simplicity.getDpmm(); + double mmLenght = number * View.getDpmm(); tempColumnConstraints.setMaxWidth(mmLenght); tempColumnConstraints.setMinWidth(mmLenght); } else { - throw new PowerRuntimeException("Column constraint string is not valid. " + element + " is not valid."); + throw new ViewException("Column constraint string is not valid. " + "Element " + element + " is not valid."); } list.add(tempColumnConstraints); } @@ -114,7 +117,9 @@ public class CellLayout extends AnchorPane { * @param column from 1 * @param row from 1 */ - public void addNode(Node node, int column, int row) { + public void addNode(Node node, + int column, + int row) { gridPane.add(node, column - 1, row - 1); } @@ -126,7 +131,11 @@ public class CellLayout extends AnchorPane { * @param columnSpan * @param rowSpan */ - public void addNode(Node node, int column, int row, int columnSpan, int rowSpan) { + public void addNode(Node node, + int column, + int row, + int columnSpan, + int rowSpan) { gridPane.add(node, column - 1, row - 1, columnSpan, rowSpan); } @@ -136,7 +145,8 @@ public class CellLayout extends AnchorPane { * @param row starting from 1 * @param nodes */ - public void addNodes(int row, Node... nodes) { + public void addNodes(int row, + Node... nodes) { gridPane.addRow(row - 1, nodes); } @@ -145,10 +155,10 @@ public class CellLayout extends AnchorPane { * @param value */ public void setSpacing(boolean value) { - if (value) { - gridPane.setVgap(3 * Simplicity.getDpmm()); - gridPane.setHgap(3 * Simplicity.getDpmm()); - gridPane.setPadding(new Insets(3 * Simplicity.getDpmm())); + if(value) { + gridPane.setVgap(3 * View.getDpmm()); + gridPane.setHgap(3 * View.getDpmm()); + gridPane.setPadding(new Insets(3 * View.getDpmm())); } else { gridPane.setVgap(0); gridPane.setHgap(0); @@ -176,11 +186,13 @@ public class CellLayout extends AnchorPane { * * @param col * @param row + * * @return */ - public Node getNodeFromGridPane(int col, int row) { + public Node getNodeFromGridPane(int col, + int row) { for (Node node : this.getChildren()) { - if (GridPane.getColumnIndex(node) == col && GridPane.getRowIndex(node) == row) { + if(GridPane.getColumnIndex(node) == col && GridPane.getRowIndex(node) == row) { return node; } } diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/SLayout.java b/power-view/src/main/java/org/nanoboot/powerframework/view/layouts/SLayout.java similarity index 73% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/SLayout.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/layouts/SLayout.java index 951666a..66889f9 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/SLayout.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/layouts/SLayout.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,19 +18,20 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window; +package org.nanoboot.powerframework.view.layouts; -import org.nanoboot.powerframework.simplicity.Simplicity; import javafx.geometry.Insets; import javafx.geometry.VPos; import javafx.scene.Node; import javafx.scene.layout.GridPane; import javafx.scene.layout.RowConstraints; +import org.nanoboot.powerframework.view.View; /** * Represents a layout. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public class SLayout extends GridPane { @@ -42,8 +43,8 @@ public class SLayout extends GridPane { public SLayout() { this.setSpacing(true); - dataRowConstraint.setMinHeight(6 * Simplicity.getDpmm()); - dataRowConstraint.setMaxHeight(6 * Simplicity.getDpmm()); + dataRowConstraint.setMinHeight(6 * View.getDpmm()); + dataRowConstraint.setMaxHeight(6 * View.getDpmm()); dataRowConstraint.setValignment(VPos.CENTER); } @@ -52,10 +53,10 @@ public class SLayout extends GridPane { * @param value */ public void setSpacing(boolean value) { - if (value) { - this.setVgap(3 * Simplicity.getDpmm()); - this.setHgap(3 * Simplicity.getDpmm()); - this.setPadding(new Insets(3 * Simplicity.getDpmm())); + if(value) { + this.setVgap(3 * View.getDpmm()); + this.setHgap(3 * View.getDpmm()); + this.setPadding(new Insets(3 * View.getDpmm())); } else { this.setVgap(0); this.setHgap(0); @@ -76,11 +77,14 @@ public class SLayout extends GridPane { * @param gridPane * @param col * @param row + * * @return */ - public Node getNodeFromGridPane(GridPane gridPane, int col, int row) { + public Node getNodeFromGridPane(GridPane gridPane, + int col, + int row) { for (Node node : gridPane.getChildren()) { - if (GridPane.getColumnIndex(node) == col && GridPane.getRowIndex(node) == row) { + if(GridPane.getColumnIndex(node) == col && GridPane.getRowIndex(node) == row) { return node; } } diff --git a/power-view/src/main/java/org/nanoboot/powerframework/view/package-info.java b/power-view/src/main/java/org/nanoboot/powerframework/view/package-info.java new file mode 100644 index 0000000..5f73db1 --- /dev/null +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/package-info.java @@ -0,0 +1,27 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * View classes. + * + * @author Robert Vokac + * @since 0.0.0 + */ +package org.goldrabbit.powerframework.view; diff --git a/power-view/src/main/java/org/nanoboot/powerframework/view/svg/.gitkeep b/power-view/src/main/java/org/nanoboot/powerframework/view/svg/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/ColourVariant.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/ColourVariant.java similarity index 85% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/ColourVariant.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/ColourVariant.java index 2541454..dc69fb0 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/ColourVariant.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/ColourVariant.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,12 +18,13 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window; +package org.nanoboot.powerframework.view.window; /** * Colour variants of a window colour skin. * - * @author Robert Vokac robertvokac@nanoboot.orgt Vokáč robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public enum ColourVariant { diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/MoveableArea.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/MoveableArea.java similarity index 77% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/MoveableArea.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/MoveableArea.java index e50c12c..29d794d 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/MoveableArea.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/MoveableArea.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,9 +18,14 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +package org.nanoboot.powerframework.view.window; -import org.nanoboot.powerframework.simplicity.Simplicity; import javafx.geometry.Insets; import javafx.geometry.Pos; import static javafx.scene.layout.HBox.setHgrow; @@ -28,14 +33,15 @@ import javafx.scene.layout.Priority; import javafx.scene.layout.StackPane; import javafx.scene.text.Font; import javafx.scene.text.Text; +import org.nanoboot.powerframework.view.View; /** * Represents the part of window, where is the window title placed and is used * to move window * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokáč e-mail: robertvokac@nanoboot.org */ -public class MoveableArea extends StackPane { +public final class MoveableArea extends StackPane { private final Text titleText = new Text(""); private final Window window; @@ -49,15 +55,15 @@ public class MoveableArea extends StackPane { public MoveableArea(Window window) { this.window = window; getChildren().add(titleText); - setStyle("-fx-background-color: rgb(" + Simplicity.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK) + ");"); + setStyle("-fx-background-color: rgb(" + View.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK) + ");"); setAlignment(Pos.CENTER_LEFT); setHgrow(this, Priority.ALWAYS); - titleText.setFont(Font.font(Simplicity.getDpmm() * 3)); - titleText.setFill(Simplicity.getDefaultWindowColourSkin().getColourForText(ColourVariant.DARK)); + titleText.setFont(Font.font(View.getDpmm() * 3)); + titleText.setFill(View.getDefaultWindowColourSkin().getColourForText(ColourVariant.DARK)); titleText.setScaleX(1.2); - setPadding(new Insets(0, 0, 0, Simplicity.getDpmm())); + setPadding(new Insets(0, 0, 0, View.getDpmm())); this.setCanBeMoved(true); } @@ -67,7 +73,7 @@ public class MoveableArea extends StackPane { */ public void setCanBeMoved(boolean value) { moveable = value; - if (value) { + if(value) { setOnMousePressed(window::handleMovingWindowStarted); setOnMouseDragged(window::handleMovingWindowEnded); } else { diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/ResizingGrid.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/ResizingGrid.java similarity index 78% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/ResizingGrid.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/ResizingGrid.java index 87cd570..55e9600 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/ResizingGrid.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/ResizingGrid.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,25 +18,25 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window; +package org.nanoboot.powerframework.view.window; import javafx.scene.layout.GridPane; -import org.nanoboot.powerframework.simplicity.Simplicity; +import org.nanoboot.powerframework.view.View; /** * Represents place used to resize window. * - * @author Robert Vokac robertvokac@nanoboot.orgt Vokáč robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public class ResizingGrid extends GridPane { /** * - * @param windowColourSkin */ public ResizingGrid() { - this.setMaxHeight(Simplicity.getDpmm() * 6); - this.setMaxWidth(Simplicity.getDpmm() * 6); + this.setMaxHeight(View.getDpmm() * 6); + this.setMaxWidth(View.getDpmm() * 6); this.add(new ResizingGridRectangle(), 3, 0); this.add(new ResizingGridRectangle(), 2, 1); this.add(new ResizingGridRectangle(), 3, 1); @@ -48,7 +48,7 @@ public class ResizingGrid extends GridPane { this.add(new ResizingGridRectangle(), 2, 3); this.add(new ResizingGridRectangle(), 3, 3); this.setStyle("-fx-padding: 0;-fx-insets: 0;"); - this.setHgap(Simplicity.getDpmm() / 2); - this.setVgap(Simplicity.getDpmm() / 2); + this.setHgap(View.getDpmm() / 2); + this.setVgap(View.getDpmm() / 2); } } diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/ResizingGridRectangle.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/ResizingGridRectangle.java similarity index 73% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/ResizingGridRectangle.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/ResizingGridRectangle.java index 7b0cb52..72dafe2 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/ResizingGridRectangle.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/ResizingGridRectangle.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,15 +18,16 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window; +package org.nanoboot.powerframework.view.window; import javafx.scene.shape.Rectangle; -import org.nanoboot.powerframework.simplicity.Simplicity; +import org.nanoboot.powerframework.view.View; /** * Represents button used to resize the window. * - * @author Robert Vokac robertvokac@nanoboot.orgt Vokáč robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public class ResizingGridRectangle extends Rectangle { @@ -34,8 +35,8 @@ public class ResizingGridRectangle extends Rectangle { * Constructor */ public ResizingGridRectangle() { - this.setFill(Simplicity.getDefaultWindowColourSkin().getColour(ColourVariant.DARK)); - this.setHeight(Simplicity.getDpmm()); - this.setWidth(Simplicity.getDpmm()); + this.setFill(View.getDefaultWindowColourSkin().getColour(ColourVariant.DARK)); + this.setHeight(View.getDpmm()); + this.setWidth(View.getDpmm()); } } diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/TitleBar.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/TitleBar.java similarity index 84% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/TitleBar.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/TitleBar.java index 3bb3933..8660f69 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/TitleBar.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/TitleBar.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,19 +18,20 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window; +package org.nanoboot.powerframework.view.window; -import org.nanoboot.powerframework.simplicity.Simplicity; -import org.nanoboot.powerframework.simplicity.window.titlebuttons.CloseButton; -import org.nanoboot.powerframework.simplicity.window.titlebuttons.MaximizeRestoreButton; -import org.nanoboot.powerframework.simplicity.window.titlebuttons.MinimizeButton; import javafx.geometry.Insets; import javafx.scene.layout.HBox; +import org.nanoboot.powerframework.view.View; +import org.nanoboot.powerframework.view.window.titlebuttons.CloseButton; +import org.nanoboot.powerframework.view.window.titlebuttons.MaximizeRestoreButton; +import org.nanoboot.powerframework.view.window.titlebuttons.MinimizeButton; /** * Represents title bar of a window. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public class TitleBar extends HBox { @@ -41,7 +42,7 @@ public class TitleBar extends HBox { /** * Space between buttons in millimeters. */ - private final Insets spaceBeforeButtons = new Insets(0, 0, 0, Simplicity.getDpmm() * 1.5); + private final Insets spaceBeforeButtons = new Insets(0, 0, 0, View.getDpmm() * 1.5); /** * StackPane for title bar icon. */ @@ -68,14 +69,13 @@ public class TitleBar extends HBox { /** * - * @param windowColourSkin * @param window */ public TitleBar(Window window) { - WindowColourSkin tempWindowColourSkin = Simplicity.getDefaultWindowColourSkin(); + WindowColourSkin tempWindowColourSkin = View.getDefaultWindowColourSkin(); setFillHeight(true); - setMinHeight(Simplicity.getDpmm() * TITLEBARHEIGHT); - setMaxHeight(Simplicity.getDpmm() * TITLEBARHEIGHT); + setMinHeight(View.getDpmm() * TITLEBARHEIGHT); + setMaxHeight(View.getDpmm() * TITLEBARHEIGHT); titleIcon = new TitleIcon(); moveableArea = new MoveableArea(window); @@ -153,7 +153,7 @@ public class TitleBar extends HBox { */ public void showOnlyTheCloseButton() { - if (!this.isShowedOnlyTheCloseButton()) { + if(!this.isShowedOnlyTheCloseButton()) { getChildren().removeAll(minimizeButton, maximizeRestoreButton); } @@ -173,7 +173,7 @@ public class TitleBar extends HBox { */ public void showAllTitleButtons() { - if (this.isShowedOnlyTheCloseButton()) { + if(this.isShowedOnlyTheCloseButton()) { getChildren().addAll(minimizeButton, maximizeRestoreButton); setMargin(minimizeButton, spaceBeforeButtons); setMargin(maximizeRestoreButton, spaceBeforeButtons); diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/TitleIcon.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/TitleIcon.java similarity index 75% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/TitleIcon.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/TitleIcon.java index 0bc0412..e0e2236 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/TitleIcon.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/TitleIcon.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,34 +18,34 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window; +package org.nanoboot.powerframework.view.window; -import org.nanoboot.powerframework.simplicity.Simplicity; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.StackPane; +import org.nanoboot.powerframework.view.View; /** * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public class TitleIcon extends StackPane { + private static final double TITLEICONHEIGHT = 4.5; /** * Title bar icon image. */ private final ImageView imageView = new ImageView(); - private static final double TITLEICONHEIGHT = 4.5; /** * Constructor * - * @param windowColourSkin */ TitleIcon() { - setStyle("-fx-background-color: rgb(" + Simplicity.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK) + ");"); - imageView.setFitWidth(Simplicity.getDpmm() * TITLEICONHEIGHT); - imageView.setFitHeight(Simplicity.getDpmm() * TITLEICONHEIGHT); + setStyle("-fx-background-color: rgb(" + View.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK) + ");"); + imageView.setFitWidth(View.getDpmm() * TITLEICONHEIGHT); + imageView.setFitHeight(View.getDpmm() * TITLEICONHEIGHT); imageView.setPreserveRatio(true); imageView.setSmooth(true); imageView.setCache(true); @@ -57,6 +57,7 @@ public class TitleIcon extends StackPane { * @param path */ public void setIcon(String path) { + System.out.println("path="+path); Image image = new Image(path); imageView.setImage(image); } diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/Window.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/Window.java similarity index 82% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/Window.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/Window.java index 5ec7da5..cbd5dc9 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/Window.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/Window.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,34 +18,40 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window; +package org.nanoboot.powerframework.view.window; import static java.lang.Thread.sleep; + import java.util.logging.Level; import java.util.logging.Logger; -import org.nanoboot.powerframework.simplicity.Simplicity; -import javafx.event.EventHandler; + +import javafx.event.Event; import javafx.geometry.Pos; +import javafx.geometry.Rectangle2D; import javafx.scene.Scene; import javafx.scene.input.MouseEvent; -import javafx.scene.layout.VBox; import javafx.scene.layout.Priority; import javafx.scene.layout.StackPane; +import javafx.scene.layout.VBox; +import javafx.stage.Screen; import javafx.stage.Stage; import javafx.stage.StageStyle; -import javafx.geometry.Rectangle2D; -import javafx.stage.Screen; -import javafx.stage.WindowEvent; +import org.nanoboot.powerframework.view.View; /** * Represents window. Window is place for everything player sees. * - * @author Robert Vokac robertvokac@nanoboot.orgt Vokáč robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public abstract class Window extends Stage { private VBox windowVBox; - private TitleBar titleBar; + private final TitleBar titleBar; + + /** + * + */ protected StackPane applicationArea = new StackPane(); private ResizingGrid resizingGrid = null; @@ -65,8 +71,7 @@ public abstract class Window extends Stage { /** * Constructor */ - public Window() { - + public Window(Object... args) { this.centerOnScreen(); titleBar = new TitleBar(this); @@ -75,7 +80,7 @@ public abstract class Window extends Stage { setDefaultSizeAndPosition(); - initAreaForUserInteraction(); + initAreaForUserInteraction(args); setValuesForRestoredWindow(); if (this.canBeResized()) { this.resizingGrid.toFront(); @@ -83,27 +88,21 @@ public abstract class Window extends Stage { } private void setDefaultSizeAndPosition() { - setWidth((org.nanoboot.powerframework.simplicity.Screen.getVisualWidth()) / 2); - setHeight((org.nanoboot.powerframework.simplicity.Screen.getVisualHeight()) / 8 * 6); - setX((org.nanoboot.powerframework.simplicity.Screen.getVisualWidth() - this.getWidth()) / 2); - setY((org.nanoboot.powerframework.simplicity.Screen.getVisualHeight() - this.getHeight()) / 2); + setWidth((org.nanoboot.powerframework.view.Screen.getVisualWidth()) / 2); + setHeight((org.nanoboot.powerframework.view.Screen.getVisualHeight()) / 8 * 6); + setX((org.nanoboot.powerframework.view.Screen.getVisualWidth() - this.getWidth()) / 2); + setY((org.nanoboot.powerframework.view.Screen.getVisualHeight() - this.getHeight()) / 2); } private void initWindowVBox() { - this.setOnCloseRequest(new EventHandler() { - @Override - public void handle(final WindowEvent event) { - - event.consume(); - } - }); + this.setOnCloseRequest(Event::consume); this.initStyle(StageStyle.TRANSPARENT); windowVBox = new VBox(); windowVBox.setFillWidth(true); this.setScene(new Scene(windowVBox, 400, 300)); this.setFullScreenExitHint(""); - windowVBox.setVgrow(applicationArea, Priority.ALWAYS); + VBox.setVgrow(applicationArea, Priority.ALWAYS); windowVBox.getChildren().addAll(applicationArea); } @@ -116,7 +115,6 @@ public abstract class Window extends Stage { } /** - * * @param path */ public void setIcon(String path) { @@ -128,7 +126,6 @@ public abstract class Window extends Stage { } /** - * * @param title */ public void setWindowTitle(String title) { @@ -137,7 +134,6 @@ public abstract class Window extends Stage { } /** - * * @return title */ public String getWindowTitle() { @@ -163,7 +159,6 @@ public abstract class Window extends Stage { } /** - * * @return boolean value */ public boolean isShowedOnlyTheCloseButton() { @@ -179,7 +174,6 @@ public abstract class Window extends Stage { } /** - * * @return boolean value */ public boolean areShowedAllTitleButtons() { @@ -193,7 +187,7 @@ public abstract class Window extends Stage { resizingGrid = new ResizingGrid(); resizingGrid.setOnMouseDragged(this::handleResizeWindowAction); applicationArea.getChildren().add(resizingGrid); - applicationArea.setAlignment(resizingGrid, Pos.BOTTOM_RIGHT); + StackPane.setAlignment(resizingGrid, Pos.BOTTOM_RIGHT); } else { this.applicationArea.getChildren().remove(this.resizingGrid); this.resizingGrid = null; @@ -250,7 +244,7 @@ public abstract class Window extends Stage { } /** - ** Window's size and position can not be changed. The size is the biggest + * * Window's size and position can not be changed. The size is the biggest */ public void switchToFullScreen() { this.windowSizeMode = WindowSizeMode.FULLSCREEN; @@ -277,31 +271,35 @@ public abstract class Window extends Stage { Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex); Thread.currentThread().interrupt(); } - for(int i=0;i<=10;i++) - {try { - sleep(50); - } catch (InterruptedException ex) { - Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex); - Thread.currentThread().interrupt(); + for (int i = 0; i <= 10; i++) { + try { + sleep(50); + } catch (InterruptedException ex) { + Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex); + Thread.currentThread().interrupt(); + } + this.onResizingWindow(); } - this.onResizingWindow();} - + }); thread.setDaemon(true); thread.start(); } + /** + * @return + */ public WindowSizeMode getWindowSizeMode() { return this.windowSizeMode; } private void setBorder(boolean value) { if (value) { - windowVBox.setStyle("-fx-background-color: rgb(" + Simplicity.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.LIGHT) + ");" - + "-fx-border-width: " + Simplicity.getDpmm() / 3 + ";" - + "-fx-border-color: rgb(" + Simplicity.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK) + ");"); + windowVBox.setStyle("-fx-background-color: rgb(" + View.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.LIGHT) + ");" + + "-fx-border-width: " + View.getDpmm() / 3 + ";" + + "-fx-border-color: rgb(" + View.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK) + ");"); } else { - windowVBox.setStyle("-fx-background-color: rgb(" + Simplicity.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.LIGHT) + ");" + windowVBox.setStyle("-fx-background-color: rgb(" + View.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.LIGHT) + ");" + "-fx-border-width: 0;"); } @@ -320,7 +318,6 @@ public abstract class Window extends Stage { } /** - * * @param e */ public void handleMovingWindowStarted(MouseEvent e) { @@ -329,7 +326,6 @@ public abstract class Window extends Stage { } /** - * * @param e */ public void handleMovingWindowEnded(MouseEvent e) { @@ -339,7 +335,6 @@ public abstract class Window extends Stage { } /** - * * @param event */ public void handleMinimizeButtonAction(MouseEvent event) { @@ -347,7 +342,6 @@ public abstract class Window extends Stage { } /** - * * @param event */ public void handleMaximizeRestoreButtonAction(MouseEvent event) { @@ -359,7 +353,6 @@ public abstract class Window extends Stage { } /** - * * @param value */ public void setCloseable(boolean value) { @@ -367,7 +360,6 @@ public abstract class Window extends Stage { } /** - * * @return */ public boolean isCloseable() { @@ -375,7 +367,6 @@ public abstract class Window extends Stage { } /** - * * @param event */ public void handleCloseButtonAction(MouseEvent event) { @@ -385,6 +376,9 @@ public abstract class Window extends Stage { } } + /** + * + */ protected void onClosingWindow() { } @@ -406,12 +400,24 @@ public abstract class Window extends Stage { this.onResizingWindow(); } + /** + * + */ protected void onResizingWindow() { } + /** + * + */ protected void onMovingWindow() { } - protected abstract void initAreaForUserInteraction(); + + /** + * + */ + protected void initAreaForUserInteraction(Object... args) { + + } } diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/WindowColourSkin.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/WindowColourSkin.java similarity index 91% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/WindowColourSkin.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/WindowColourSkin.java index b67aaff..a561475 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/WindowColourSkin.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/WindowColourSkin.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,15 +18,16 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window; +package org.nanoboot.powerframework.view.window; -import org.nanoboot.powerframework.simplicity.EnumColour; import javafx.scene.paint.Color; +import org.nanoboot.powerframework.view.EnumColour; /** * Represents colour skin of Window. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public class WindowColourSkin { @@ -75,7 +76,7 @@ public class WindowColourSkin { colour[1][16] = Color.rgb(75, 83, 32); } - private EnumColour enumColour; + private final EnumColour enumColour; /** * @@ -88,10 +89,11 @@ public class WindowColourSkin { /** * * @param colourVariant + * * @return */ public Color getColour(ColourVariant colourVariant) { - if (colourVariant == ColourVariant.LIGHT) { + if(colourVariant == ColourVariant.LIGHT) { return colour[0][enumColour.ordinal()]; } else { return colour[1][enumColour.ordinal()]; @@ -125,19 +127,20 @@ public class WindowColourSkin { /** * * @param lightOrDarkBackground + * * @return */ public Color getColourForText(ColourVariant lightOrDarkBackground) { int colourNumber = this.getEnumColour().getNumber(); - if (lightOrDarkBackground == ColourVariant.DARK) { + if(lightOrDarkBackground == ColourVariant.DARK) { int[] intArray = {3, 6, 7, 14, 16}; for (int element : intArray) { - if (colourNumber == element) { + if(colourNumber == element) { return Color.rgb(255, 255, 255); } } } else { - if (colourNumber == 14) { + if(colourNumber == 14) { return Color.rgb(255, 255, 255); } } @@ -150,6 +153,7 @@ public class WindowColourSkin { * with commas. * * @param lightOrDark + * * @return css String representation of colour */ public String getRGBStringForCSS(ColourVariant lightOrDark) { @@ -163,6 +167,7 @@ public class WindowColourSkin { /** * * @param color + * * @return */ public String getRGBStringForCSS(Color color) { diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/WindowSizeMode.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/WindowSizeMode.java similarity index 88% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/WindowSizeMode.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/WindowSizeMode.java index de416aa..2c050c2 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/WindowSizeMode.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/WindowSizeMode.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,12 +18,13 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window; +package org.nanoboot.powerframework.view.window; /** * Window size modes. * - * @author Robert Vokac robertvokac@nanoboot.orgt Vokáč robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public enum WindowSizeMode { diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/Button.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/Button.java similarity index 75% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/controls/Button.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/Button.java index 2e77e6e..ae3b701 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/Button.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/Button.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,41 +18,43 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window.controls; +package org.nanoboot.powerframework.view.window.controls; -import org.nanoboot.powerframework.simplicity.Simplicity; -import org.nanoboot.powerframework.simplicity.window.ColourVariant; import javafx.geometry.Insets; import javafx.scene.input.MouseEvent; import javafx.scene.text.Font; +import org.nanoboot.powerframework.view.View; +import org.nanoboot.powerframework.view.window.ColourVariant; /** + * * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ + public class Button extends javafx.scene.control.Button { - private String setStyleStartString + private final String setStyleStartString = new StringBuilder("-fx-border-insets:0;-fx-background-insets:0;-fx-background-radius:0;-fx-background-color: rgb(") - .append(Simplicity.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK)) + .append(View.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK)) .append(");-fx-border-color:rgb(") .toString(); - private String setStyleEndString = new StringBuilder(");-fx-border-width: ") - .append(Simplicity.getDpmm() / 2) + private final String setStyleEndString = new StringBuilder(");-fx-border-width: ") + .append(View.getDpmm() / 2) .append(";") .toString(); /** * - * @param windowColourSkin * @param text */ public Button(String text) { super(text); this.setMaxWidth(Double.MAX_VALUE); - this.setMaxHeight(6 * Simplicity.getDpmm()); + this.setMaxHeight(6 * View.getDpmm()); this.setPadding(new Insets(0, 0, 0, 0)); - this.setFont(Font.font(3 * Simplicity.getDpmm())); + this.setFont(Font.font(3 * View.getDpmm())); this.setStyle(getSetStyleString("186, 186, 186")); setOnMouseEntered(this::handleMouseEnteredAction); setOnMouseExited(this::handleMouseExitedAction); diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/NumericMinusPlus.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/NumericMinusPlus.java similarity index 83% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/controls/NumericMinusPlus.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/NumericMinusPlus.java index dbf2281..c79a9c3 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/NumericMinusPlus.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/NumericMinusPlus.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,12 +18,13 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window.controls; +package org.nanoboot.powerframework.view.window.controls; /** * Represents numeric minus plus control. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public class NumericMinusPlus { diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/PasswordField.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/PasswordField.java similarity index 68% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/controls/PasswordField.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/PasswordField.java index 2d56594..ac7cf05 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/PasswordField.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/PasswordField.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,15 +18,17 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window.controls; +package org.nanoboot.powerframework.view.window.controls; -import org.nanoboot.powerframework.simplicity.Simplicity; -import org.nanoboot.powerframework.simplicity.window.ColourVariant; import javafx.scene.text.Font; +import org.nanoboot.powerframework.view.View; +import org.nanoboot.powerframework.view.window.ColourVariant; /** + * * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public class PasswordField extends javafx.scene.control.PasswordField { @@ -34,8 +36,8 @@ public class PasswordField extends javafx.scene.control.PasswordField { * Constructor */ public PasswordField() { - this.setFont(Font.font(3 * Simplicity.getDpmm())); - this.setMaxHeight(6 * Simplicity.getDpmm()); - this.setStyle("-fx-padding:0;-fx-border-insets:0;-fx-background-insets:0;-fx-background-radius:0;-fx-background-color: rgb(255,255,255);-fx-border-color:rgb(" + Simplicity.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK) + ");-fx-border-width: " + Simplicity.getDpmm() / 2 + ";"); + this.setFont(Font.font(3 * View.getDpmm())); + this.setMaxHeight(6 * View.getDpmm()); + this.setStyle("-fx-padding:0;-fx-border-insets:0;-fx-background-insets:0;-fx-background-radius:0;-fx-background-color: rgb(255,255,255);-fx-border-color:rgb(" + View.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK) + ");-fx-border-width: " + View.getDpmm() / 2 + ";"); } } diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/RadioButton.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/RadioButton.java similarity index 70% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/controls/RadioButton.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/RadioButton.java index 0d41386..e28b113 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/RadioButton.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/RadioButton.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,29 +18,32 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window.controls; +package org.nanoboot.powerframework.view.window.controls; import javafx.scene.paint.Color; import javafx.scene.text.Font; -import org.nanoboot.powerframework.simplicity.Simplicity; -import org.nanoboot.powerframework.simplicity.window.ColourVariant; +import org.nanoboot.powerframework.view.View; +import org.nanoboot.powerframework.view.window.ColourVariant; /** * Represents radio button. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public class RadioButton extends javafx.scene.control.RadioButton { -/** - * Constructor - * - * @param text - */ + + /** + * Constructor + * + * @param text + */ public RadioButton(String text) { super(text); - - setFont(Font.font(3 * Simplicity.getDpmm())); - Color color=Simplicity.getDefaultWindowColourSkin().getColourForText(ColourVariant.LIGHT); + + setFont(Font.font(3 * View.getDpmm())); + Color color = View.getDefaultWindowColourSkin().getColourForText(ColourVariant.LIGHT); this.setTextFill(color); } + } diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/RadioButtonGroup.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/RadioButtonGroup.java similarity index 82% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/controls/RadioButtonGroup.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/RadioButtonGroup.java index b58360b..8707270 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/RadioButtonGroup.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/RadioButtonGroup.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,12 +18,14 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window.controls; +package org.nanoboot.powerframework.view.window.controls; /** + * * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public class RadioButtonGroup { - + } diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/SCheckBox.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/SCheckBox.java similarity index 71% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/controls/SCheckBox.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/SCheckBox.java index 3414631..a2ba8cd 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/SCheckBox.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/SCheckBox.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,10 +18,8 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window.controls; +package org.nanoboot.powerframework.view.window.controls; -import org.nanoboot.powerframework.simplicity.Simplicity; -import org.nanoboot.powerframework.simplicity.window.ColourVariant; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.input.MouseEvent; @@ -29,37 +27,41 @@ import javafx.scene.layout.HBox; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.shape.Line; +import org.nanoboot.powerframework.view.View; +import org.nanoboot.powerframework.view.window.ColourVariant; /** + * * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ -public class SCheckBox extends HBox { +public final class SCheckBox extends HBox { private StackPane checkBoxStackPane = new StackPane(); private SLabel checkBoxSLabel = new SLabel(); private boolean selected = false; private boolean disabled = false; - Line line1 = new Line(0, 0, 3 * Simplicity.getDpmm(), 3 * Simplicity.getDpmm()); - Line line2 = new Line(0, 3 * Simplicity.getDpmm(), 3 * Simplicity.getDpmm(), 0); + Line line1 = new Line(0, 0, 3 * View.getDpmm(), 3 * View.getDpmm()); + Line line2 = new Line(0, 3 * View.getDpmm(), 3 * View.getDpmm(), 0); /** * Constructor */ public SCheckBox() { this.line1.setStroke(Color.rgb(153, 153, 153)); - this.line1.setStrokeWidth(0.5 * Simplicity.getDpmm()); + this.line1.setStrokeWidth(0.5 * View.getDpmm()); this.line2.setStroke(Color.rgb(153, 153, 153)); - this.line2.setStrokeWidth(0.5 * Simplicity.getDpmm()); + this.line2.setStrokeWidth(0.5 * View.getDpmm()); this.setAlignment(Pos.CENTER_LEFT); this.getChildren().addAll(this.checkBoxStackPane, this.checkBoxSLabel); - setMargin(checkBoxStackPane, new Insets(0, 1 * Simplicity.getDpmm(), 0, 0)); + setMargin(checkBoxStackPane, new Insets(0, 1 * View.getDpmm(), 0, 0)); setOnMouseClicked(this::handleMouseClicked); - this.checkBoxStackPane.setMinSize(6 * Simplicity.getDpmm(), 6 * Simplicity.getDpmm()); - this.checkBoxStackPane.setMaxSize(6 * Simplicity.getDpmm(), 6 * Simplicity.getDpmm()); - this.checkBoxStackPane.setStyle("-fx-background-radius:0;-fx-background-color: rgb(255,255,255);-fx-border-color:rgb(" + Simplicity.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK) + ");-fx-border-width: " + Simplicity.getDpmm() / 2 + ";"); + this.checkBoxStackPane.setMinSize(6 * View.getDpmm(), 6 * View.getDpmm()); + this.checkBoxStackPane.setMaxSize(6 * View.getDpmm(), 6 * View.getDpmm()); + this.checkBoxStackPane.setStyle("-fx-background-radius:0;-fx-background-color: rgb(255,255,255);-fx-border-color:rgb(" + View.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK) + ");-fx-border-width: " + View.getDpmm() / 2 + ";"); } /** @@ -91,10 +93,14 @@ public class SCheckBox extends HBox { this.setSelected(!this.isSelected()); } + /** + * + * @param value + */ public void setSelected(boolean value) { this.selected = value; this.checkBoxStackPane.getChildren().clear(); - if (value) { + if(value) { this.checkBoxStackPane.getChildren().addAll(this.line1, this.line2); } } @@ -113,11 +119,11 @@ public class SCheckBox extends HBox { */ public void turnDisabled(boolean value) { this.disabled = value; - if (value) { - this.checkBoxStackPane.setStyle("-fx-background-color: rgb(192,192,192);-fx-border-color:rgb(153,153,153);-fx-border-width: " + Simplicity.getDpmm() / 2 + ";"); + if(value) { + this.checkBoxStackPane.setStyle("-fx-background-color: rgb(192,192,192);-fx-border-color:rgb(153,153,153);-fx-border-width: " + View.getDpmm() / 2 + ";"); setOnMouseClicked(null); } else { - this.checkBoxStackPane.setStyle("-fx-background-color: rgb(255,255,255);-fx-border-color:rgb(" + Simplicity.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK) + ");-fx-border-width: " + Simplicity.getDpmm() / 2 + ";"); + this.checkBoxStackPane.setStyle("-fx-background-color: rgb(255,255,255);-fx-border-color:rgb(" + View.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK) + ");-fx-border-width: " + View.getDpmm() / 2 + ";"); setOnMouseClicked(this::handleMouseClicked); } } diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/SComboBox.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/SComboBox.java similarity index 72% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/controls/SComboBox.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/SComboBox.java index e6e970b..6f071fb 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/SComboBox.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/SComboBox.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,16 +18,17 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window.controls; +package org.nanoboot.powerframework.view.window.controls; import javafx.scene.control.ComboBox; import javafx.scene.text.Font; -import org.nanoboot.powerframework.simplicity.Simplicity; -import org.nanoboot.powerframework.simplicity.window.ColourVariant; +import org.nanoboot.powerframework.view.View; +import org.nanoboot.powerframework.view.window.ColourVariant; /** * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public class SComboBox extends ComboBox { @@ -35,15 +36,15 @@ public class SComboBox extends ComboBox { * Constructor */ public SComboBox() { - this.setMaxHeight(6 * Simplicity.getDpmm()); + this.setMaxHeight(6 * View.getDpmm()); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("-fx-padding:0;-fx-border-insets:0;-fx-background-insets:0;-fx-background-radius:0;-fx-background-color: rgb(255,255,255);-fx-border-color:rgb("); - stringBuilder.append(Simplicity.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK)); + stringBuilder.append(View.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK)); stringBuilder.append(");-fx-border-width: "); - stringBuilder.append(Simplicity.getDpmm() / 2); + stringBuilder.append(View.getDpmm() / 2); stringBuilder.append(";-fx-font-size: "); - stringBuilder.append(Font.font(3 * Simplicity.getDpmm())); + stringBuilder.append(Font.font(3 * View.getDpmm())); stringBuilder.append(";"); this.setStyle(stringBuilder.toString()); } diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/SLabel.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/SLabel.java similarity index 71% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/controls/SLabel.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/SLabel.java index edeca13..15c1777 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/SLabel.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/SLabel.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,16 +18,18 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window.controls; +package org.nanoboot.powerframework.view.window.controls; import javafx.scene.paint.Color; -import org.nanoboot.powerframework.simplicity.Simplicity; import javafx.scene.text.Font; -import org.nanoboot.powerframework.simplicity.window.ColourVariant; +import org.nanoboot.powerframework.view.View; +import org.nanoboot.powerframework.view.window.ColourVariant; /** + * * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public class SLabel extends javafx.scene.control.Label { @@ -46,10 +48,11 @@ public class SLabel extends javafx.scene.control.Label { * @param text * @param colourVariant */ - public SLabel(String text, ColourVariant colourVariant) { + public SLabel(String text, + ColourVariant colourVariant) { super(text); - setFont(Font.font(3 * Simplicity.getDpmm())); - Color color = Simplicity.getDefaultWindowColourSkin().getColourForText(colourVariant); + setFont(Font.font(3 * View.getDpmm())); + Color color = View.getDefaultWindowColourSkin().getColourForText(colourVariant); this.setTextFill(color); } @@ -57,7 +60,7 @@ public class SLabel extends javafx.scene.control.Label { * Constructor */ public SLabel() { - setFont(Font.font(3 * Simplicity.getDpmm())); + setFont(Font.font(3 * View.getDpmm())); } } diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/TabPane.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/TabPane.java similarity index 82% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/controls/TabPane.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/TabPane.java index 68b0ab2..b0705d1 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/TabPane.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/TabPane.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,14 +18,19 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window.controls; +package org.nanoboot.powerframework.view.window.controls; /** + * * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public class TabPane extends javafx.scene.control.TabPane { + /** + * + */ public TabPane() { //Not yet implemented. } diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/TextField.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/TextField.java similarity index 72% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/controls/TextField.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/TextField.java index 77a13f5..f73e8af 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/controls/TextField.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/controls/TextField.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,22 +18,25 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window.controls; +package org.nanoboot.powerframework.view.window.controls; -import org.nanoboot.powerframework.simplicity.Simplicity; -import org.nanoboot.powerframework.simplicity.window.ColourVariant; import javafx.scene.text.Font; +import org.nanoboot.powerframework.view.View; +import org.nanoboot.powerframework.view.window.ColourVariant; /** * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * + * @author Robert Vokac + * @since 0.0.0 */ public class TextField extends javafx.scene.control.TextField { -/** - * Constructor - * - * @param value - */ + + /** + * Constructor + * + * @param value + */ public TextField(String value) { super(value); setTextField(); @@ -47,14 +50,14 @@ public class TextField extends javafx.scene.control.TextField { } private void setTextField() { - this.setFont(Font.font(3 * Simplicity.getDpmm())); - this.setMaxHeight(6 * Simplicity.getDpmm()); + this.setFont(Font.font(3 * View.getDpmm())); + this.setMaxHeight(6 * View.getDpmm()); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("-fx-padding:0;-fx-border-insets:0;-fx-background-insets:0;-fx-background-radius:0;-fx-background-color: rgb(255,255,255);-fx-border-color:rgb("); - stringBuilder.append(Simplicity.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK)); + stringBuilder.append(View.getDefaultWindowColourSkin().getRGBStringForCSS(ColourVariant.DARK)); stringBuilder.append(");-fx-border-width: "); - stringBuilder.append(Simplicity.getDpmm() / 2); + stringBuilder.append(View.getDpmm() / 2); stringBuilder.append(";"); this.setStyle(stringBuilder.toString()); } diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/CloseButton.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/titlebuttons/CloseButton.java similarity index 73% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/CloseButton.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/titlebuttons/CloseButton.java index c009794..259648a 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/CloseButton.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/titlebuttons/CloseButton.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,36 +18,39 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window.titlebuttons; +package org.nanoboot.powerframework.view.window.titlebuttons; import javafx.geometry.Pos; import javafx.scene.shape.Line; -import org.nanoboot.powerframework.simplicity.Simplicity; -import org.nanoboot.powerframework.simplicity.window.Window; -import org.nanoboot.powerframework.simplicity.window.WindowColourSkin; +import org.nanoboot.powerframework.view.View; +import org.nanoboot.powerframework.view.window.Window; +import org.nanoboot.powerframework.view.window.WindowColourSkin; /** * Represents close button. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * + * @author Robert Vokac + * @since 0.0.0 */ public class CloseButton extends WindowTitleButton { - Line line1 = new Line(0, 0, 5 * Simplicity.getDpmm(), 2.5 * Simplicity.getDpmm()); - Line line2 = new Line(0, 2.5 * Simplicity.getDpmm(), 5 * Simplicity.getDpmm(), 0); + Line line1 = new Line(0, 0, 5 * View.getDpmm(), 2.5 * View.getDpmm()); + Line line2 = new Line(0, 2.5 * View.getDpmm(), 5 * View.getDpmm(), 0); /** * * @param windowColourSkin * @param window */ - public CloseButton(WindowColourSkin windowColourSkin, Window window) { + public CloseButton(WindowColourSkin windowColourSkin, + Window window) { super(windowColourSkin); setOnMouseClicked(window::handleCloseButtonAction); line1.setStroke(this.windowColourSkin.getColourForInactiveWindowTitleButton()); - line1.setStrokeWidth(0.5 * Simplicity.getDpmm()); + line1.setStrokeWidth(0.5 * View.getDpmm()); line2.setStroke(this.windowColourSkin.getColourForInactiveWindowTitleButton()); - line2.setStrokeWidth(0.5 * Simplicity.getDpmm()); + line2.setStrokeWidth(0.5 * View.getDpmm()); getChildren().addAll(line1, line2); setAlignment(line1, Pos.CENTER); setAlignment(line2, Pos.CENTER); diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/LineInWindowTitleButton.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/titlebuttons/LineInWindowTitleButton.java similarity index 80% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/LineInWindowTitleButton.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/titlebuttons/LineInWindowTitleButton.java index 6205bcb..e8ca4d6 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/LineInWindowTitleButton.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/titlebuttons/LineInWindowTitleButton.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,19 +18,23 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window.titlebuttons; +package org.nanoboot.powerframework.view.window.titlebuttons; import javafx.scene.paint.Color; import javafx.scene.shape.Line; -import org.nanoboot.powerframework.simplicity.Simplicity; +import org.nanoboot.powerframework.view.View; /** * Represents a line of a window title button * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public class LineInWindowTitleButton extends Line { + /** + * + */ protected Color inactiveLinesColour = Color.rgb(153, 153, 153); /** @@ -38,6 +42,6 @@ public class LineInWindowTitleButton extends Line { */ public LineInWindowTitleButton() { setStroke(inactiveLinesColour); - setStrokeWidth(0.5 * Simplicity.getDpmm()); + setStrokeWidth(0.5 * View.getDpmm()); } } diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/MaximizeRestoreButton.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/titlebuttons/MaximizeRestoreButton.java similarity index 61% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/MaximizeRestoreButton.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/titlebuttons/MaximizeRestoreButton.java index 1f42a84..1a536bf 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/MaximizeRestoreButton.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/titlebuttons/MaximizeRestoreButton.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,55 +18,58 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window.titlebuttons; +package org.nanoboot.powerframework.view.window.titlebuttons; import javafx.geometry.Pos; import javafx.scene.paint.Color; import javafx.scene.shape.Polyline; -import org.nanoboot.powerframework.simplicity.Simplicity; -import org.nanoboot.powerframework.simplicity.window.Window; -import org.nanoboot.powerframework.simplicity.window.WindowColourSkin; +import org.nanoboot.powerframework.view.View; +import org.nanoboot.powerframework.view.window.Window; +import org.nanoboot.powerframework.view.window.WindowColourSkin; /** * Represents maximize/restore button. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * + * @author Robert Vokac + * @since 0.0.0 */ -public class MaximizeRestoreButton extends WindowTitleButton { +public final class MaximizeRestoreButton extends WindowTitleButton { - private Polyline restorePolyline = new Polyline( - 1.5 * Simplicity.getDpmm(), 1 * Simplicity.getDpmm(), - 1.5 * Simplicity.getDpmm(), 0, - 5.5 * Simplicity.getDpmm(), 0, - 5.5 * Simplicity.getDpmm(), 2.0 * Simplicity.getDpmm(), - 4 * Simplicity.getDpmm(), 2.0 * Simplicity.getDpmm(), - 4 * Simplicity.getDpmm(), 3.0 * Simplicity.getDpmm(), - 0 * Simplicity.getDpmm(), 3.0 * Simplicity.getDpmm(), - 0 * Simplicity.getDpmm(), 1 * Simplicity.getDpmm(), - 4 * Simplicity.getDpmm(), 1 * Simplicity.getDpmm(), - 4 * Simplicity.getDpmm(), 2.0 * Simplicity.getDpmm() + private final Polyline restorePolyline = new Polyline( + 1.5 * View.getDpmm(), 1 * View.getDpmm(), + 1.5 * View.getDpmm(), 0, + 5.5 * View.getDpmm(), 0, + 5.5 * View.getDpmm(), 2.0 * View.getDpmm(), + 4 * View.getDpmm(), 2.0 * View.getDpmm(), + 4 * View.getDpmm(), 3.0 * View.getDpmm(), + 0 * View.getDpmm(), 3.0 * View.getDpmm(), + 0 * View.getDpmm(), 1 * View.getDpmm(), + 4 * View.getDpmm(), 1 * View.getDpmm(), + 4 * View.getDpmm(), 2.0 * View.getDpmm() ); - private Polyline maximizePolyline = new Polyline( - 0.25 * Simplicity.getDpmm(), 0.25 * Simplicity.getDpmm(), - 5.25 * Simplicity.getDpmm(), 0.25 * Simplicity.getDpmm(), - 5.25 * Simplicity.getDpmm(), 3 * Simplicity.getDpmm(), - 0.25 * Simplicity.getDpmm(), 3 * Simplicity.getDpmm(), - 0.25 * Simplicity.getDpmm(), 0.25 * Simplicity.getDpmm()); + private final Polyline maximizePolyline = new Polyline( + 0.25 * View.getDpmm(), 0.25 * View.getDpmm(), + 5.25 * View.getDpmm(), 0.25 * View.getDpmm(), + 5.25 * View.getDpmm(), 3 * View.getDpmm(), + 0.25 * View.getDpmm(), 3 * View.getDpmm(), + 0.25 * View.getDpmm(), 0.25 * View.getDpmm()); /** * * @param windowColourSkin * @param window */ - public MaximizeRestoreButton(WindowColourSkin windowColourSkin, Window window) { + public MaximizeRestoreButton(WindowColourSkin windowColourSkin, + Window window) { super(windowColourSkin); setOnMouseClicked(window::handleMaximizeRestoreButtonAction); restorePolyline.setStroke(this.windowColourSkin.getColourForInactiveWindowTitleButton()); - restorePolyline.setStrokeWidth(0.5 * Simplicity.getDpmm()); + restorePolyline.setStrokeWidth(0.5 * View.getDpmm()); restorePolyline.setFill(Color.TRANSPARENT); maximizePolyline.setStroke(this.windowColourSkin.getColourForInactiveWindowTitleButton()); - maximizePolyline.setStrokeWidth(0.5 * Simplicity.getDpmm()); + maximizePolyline.setStrokeWidth(0.5 * View.getDpmm()); maximizePolyline.setFill(Color.TRANSPARENT); this.setAlignment(Pos.CENTER); diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/MinimizeButton.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/titlebuttons/MinimizeButton.java similarity index 69% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/MinimizeButton.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/titlebuttons/MinimizeButton.java index bb64449..09580d2 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/MinimizeButton.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/titlebuttons/MinimizeButton.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,37 +18,39 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window.titlebuttons; +package org.nanoboot.powerframework.view.window.titlebuttons; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.shape.Line; -import org.nanoboot.powerframework.simplicity.Simplicity; -import org.nanoboot.powerframework.simplicity.window.Window; -import org.nanoboot.powerframework.simplicity.window.WindowColourSkin; +import org.nanoboot.powerframework.view.View; +import org.nanoboot.powerframework.view.window.Window; +import org.nanoboot.powerframework.view.window.WindowColourSkin; /** * Represents minimize button. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public class MinimizeButton extends WindowTitleButton { - Line line1 = new Line(1 * Simplicity.getDpmm(), 3.5 * Simplicity.getDpmm(), 6 * Simplicity.getDpmm(), 3.5 * Simplicity.getDpmm()); + Line line1 = new Line(1 * View.getDpmm(), 3.5 * View.getDpmm(), 6 * View.getDpmm(), 3.5 * View.getDpmm()); /** * * @param windowColourSkin * @param window */ - public MinimizeButton(WindowColourSkin windowColourSkin, Window window) { + public MinimizeButton(WindowColourSkin windowColourSkin, + Window window) { super(windowColourSkin); setOnMouseClicked(window::handleMinimizeButtonAction); line1.setStroke(this.windowColourSkin.getColourForInactiveWindowTitleButton()); - line1.setStrokeWidth(0.5 * Simplicity.getDpmm()); + line1.setStrokeWidth(0.5 * View.getDpmm()); getChildren().addAll(line1); setAlignment(line1, Pos.BOTTOM_CENTER); - this.setPadding(new Insets(Simplicity.getDpmm(), Simplicity.getDpmm(), Simplicity.getDpmm(), Simplicity.getDpmm())); + this.setPadding(new Insets(View.getDpmm(), View.getDpmm(), View.getDpmm(), View.getDpmm())); } diff --git a/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/WindowTitleButton.java b/power-view/src/main/java/org/nanoboot/powerframework/view/window/titlebuttons/WindowTitleButton.java similarity index 81% rename from src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/WindowTitleButton.java rename to power-view/src/main/java/org/nanoboot/powerframework/view/window/titlebuttons/WindowTitleButton.java index 26e5edb..e577512 100644 --- a/src/main/java/org/nanoboot/powerframework/simplicity/window/titlebuttons/WindowTitleButton.java +++ b/power-view/src/main/java/org/nanoboot/powerframework/view/window/titlebuttons/WindowTitleButton.java @@ -5,7 +5,7 @@ // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; +// License as published by the Free Software Foundation; // version 2.1 of the License only. // // This library is distributed in the hope that it will be useful, @@ -18,24 +18,28 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /////////////////////////////////////////////////////////////////////////////////////////////// -package org.nanoboot.powerframework.simplicity.window.titlebuttons; +package org.nanoboot.powerframework.view.window.titlebuttons; import javafx.scene.input.MouseEvent; import javafx.scene.layout.StackPane; import javafx.scene.shape.Line; -import org.nanoboot.powerframework.simplicity.Simplicity; -import org.nanoboot.powerframework.simplicity.window.ColourVariant; -import org.nanoboot.powerframework.simplicity.window.WindowColourSkin; +import org.nanoboot.powerframework.view.View; +import org.nanoboot.powerframework.view.window.ColourVariant; +import org.nanoboot.powerframework.view.window.WindowColourSkin; /** * Represents window title button. * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org + * @author Robert Vokac + * @since 0.0.0 */ public abstract class WindowTitleButton extends StackPane { private static final int BUTTONWIDTH = 7; + /** + * + */ protected WindowColourSkin windowColourSkin; /** @@ -45,8 +49,8 @@ public abstract class WindowTitleButton extends StackPane { public WindowTitleButton(WindowColourSkin windowColourSkin) { this.windowColourSkin = windowColourSkin; this.setStyle("-fx-background-color: rgb(" + windowColourSkin.getRGBStringForCSS(ColourVariant.DARK) + ");"); - setMinWidth(BUTTONWIDTH * Simplicity.getDpmm()); - setMaxWidth(BUTTONWIDTH * Simplicity.getDpmm()); + setMinWidth(BUTTONWIDTH * View.getDpmm()); + setMaxWidth(BUTTONWIDTH * View.getDpmm()); setOnMouseEntered(this::handleMouseEnteredAction); setOnMouseExited(this::handleMMouseExitedAction); @@ -65,7 +69,7 @@ public abstract class WindowTitleButton extends StackPane { */ public void makeLine(Line line) { line.setStroke(this.windowColourSkin.getColourForInactiveWindowTitleButton()); - line.setStrokeWidth(0.5 * Simplicity.getDpmm()); + line.setStrokeWidth(0.5 * View.getDpmm()); } private void handleMouseEnteredAction(MouseEvent event) {//NOSONAR diff --git a/power-view/src/main/resources/.gitkeep b/power-view/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-view/src/test/java/.gitkeep b/power-view/src/test/java/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-web/pom.xml b/power-web/pom.xml new file mode 100644 index 0000000..5bf9d78 --- /dev/null +++ b/power-web/pom.xml @@ -0,0 +1,67 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-web + jar + + Power Web + Web functionality for the Power library + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + org.nanoboot.powerframework + power-xml + ${power.version} + + + + + junit + junit + 4.12 + test + + + org.projectlombok + lombok + + + org.jsoup + jsoup + 1.12.1 + + + diff --git a/power-web/src/main/java/module-info.java b/power-web/src/main/java/module-info.java new file mode 100644 index 0000000..0eef5f6 --- /dev/null +++ b/power-web/src/main/java/module-info.java @@ -0,0 +1,36 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +module powerframework.web { + requires lombok; + requires org.jsoup; + requires powerframework.xml; + exports org.nanoboot.powerframework.web.html; + exports org.nanoboot.powerframework.web.html.attributes; + exports org.nanoboot.powerframework.web.html.tags; + exports org.nanoboot.powerframework.web; +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/PowerWebException.java b/power-web/src/main/java/org/nanoboot/powerframework/web/PowerWebException.java new file mode 100644 index 0000000..3d3b67f --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/PowerWebException.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class PowerWebException extends RuntimeException { + public PowerWebException(String s) { + super(s); + } +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/PrettyPrinter.java b/power-web/src/main/java/org/nanoboot/powerframework/web/PrettyPrinter.java new file mode 100644 index 0000000..c104624 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/PrettyPrinter.java @@ -0,0 +1,37 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web; + +import org.jsoup.Jsoup; +import org.jsoup.nodes.Document; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class PrettyPrinter { + public static String makePretty(String html) { + Document doc = Jsoup.parse(html); + return doc.toString(); + } + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/TestMain.java b/power-web/src/main/java/org/nanoboot/powerframework/web/TestMain.java new file mode 100644 index 0000000..5b5229e --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/TestMain.java @@ -0,0 +1,66 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web; + +import org.nanoboot.powerframework.web.html.WebPage; +import org.nanoboot.powerframework.web.html.attributes.Content; +import org.nanoboot.powerframework.web.html.attributes.Href; +import org.nanoboot.powerframework.web.html.attributes.HttpEquiv; +import org.nanoboot.powerframework.web.html.attributes.Rel; +import org.nanoboot.powerframework.web.html.tags.*; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class TestMain { + public static void main(String[] args) { + WebPage page=new WebPage(); + Html html=page.getRootElement(); + + Head head = getHead(); + + + Body body = getBody(); + + html.add(head,body); + System.out.println(page.build()); + } + + private static Head getHead() { + Head head=new Head(); + Meta meta=new Meta(); + meta.add(new HttpEquiv("content-type"),new Content("text/html; charset=UTF-8")); + head.add(meta); + head.add(new Title("Tree Base | Home")); + head.add(new Link(new Rel("stylesheet"),new Href("/styles/styles.css"))); + + return head; + } + + private static Body getBody() { + Body body=new Body(); + return body; + } + + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/css/CssStyle.java b/power-web/src/main/java/org/nanoboot/powerframework/web/css/CssStyle.java new file mode 100644 index 0000000..5b10832 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/css/CssStyle.java @@ -0,0 +1,62 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.css; + +import org.nanoboot.powerframework.web.PowerWebException; +import lombok.Getter; +import lombok.Setter; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class CssStyle { + @Getter + private final String name; + @Getter + @Setter + private String value; + + public CssStyle(String nameValue) { + String[] a=nameValue.split(":"); + if(a.length!=2){ + throw new PowerWebException("nameValue "+nameValue+"is not a valid css style. Because just one colon : is expected"); + } + this.name=a[0]; + this.value=a[1]; + + } + + public CssStyle(String name, String value) { + this.name=name; + this.value=value; + + } + public String build() { + return name + ':'+ value; + } + + public String toString() { + return build(); + } +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/css/CssStyles.java b/power-web/src/main/java/org/nanoboot/powerframework/web/css/CssStyles.java new file mode 100644 index 0000000..730dff0 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/css/CssStyles.java @@ -0,0 +1,117 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.css; + +import lombok.Getter; + +import java.util.ArrayList; +import java.util.List; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class CssStyles { + + public static final String SEPARATOR = "; "; + + @Getter + private final List cssStyles = new ArrayList<>(); + + public CssStyles(String moreStyles){ + String[] a=moreStyles.split(";"); + for(String e:a){ + if(e.isEmpty()){ + continue; + } + this.add(new CssStyle(e)); + } + } + + public CssStyles(CssStyle... cssStyles) { + this.addAll(cssStyles); + } + + + public void add(String name, String value) { + cssStyles.add(new CssStyle(name, value)); + } + + public void add(CssStyle cssStyle) { + + cssStyles.add(cssStyle); + } + + public void addAll(CssStyle... cssStyle) { + + for (CssStyle a : cssStyle) { + cssStyles.add(a); + } + } + + public boolean has(String name) { + if (this.cssStyles == null) { + return false; + } + for (CssStyle a : this.cssStyles) { + if (a.getName().equals(name)) { + + return true; + } + } + return false; + } + + public String get(String name) { + + for (CssStyle a : this.cssStyles) { + if (a.getName().equals(name)) { + return a.getValue(); + } + } + throw new RuntimeException("There is no style " + name); + } + + public void set(String name, String value) { + if (!has(name)) { + throw new RuntimeException("There is no style " + name); + } + for (CssStyle a : this.cssStyles) { + if (a.getName().equals(name)) { + a.setValue(value); + return; + } + } + throw new RuntimeException("There is no style " + name); + } + public String build() { + StringBuilder sb = new StringBuilder(); + for (CssStyle a : this.getCssStyles()) { + sb.append(a); + sb.append(SEPARATOR);} + sb.toString(); + return sb.toString(); + } + + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/css/CssStylesSelector.java b/power-web/src/main/java/org/nanoboot/powerframework/web/css/CssStylesSelector.java new file mode 100644 index 0000000..99e2854 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/css/CssStylesSelector.java @@ -0,0 +1,42 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.css; + +import lombok.AllArgsConstructor; +import lombok.Data; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@Data +@AllArgsConstructor +public class CssStylesSelector { + private String selector; + private CssStyles cssStyles; + public String build(){ + StringBuilder sb=new StringBuilder(); + sb.append(selector).append(" ").append("{").append(cssStyles.build()).append("}").append("\n\n"); + return sb.toString(); + } +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/css/CssStylesSelectors.java b/power-web/src/main/java/org/nanoboot/powerframework/web/css/CssStylesSelectors.java new file mode 100644 index 0000000..1aae4a5 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/css/CssStylesSelectors.java @@ -0,0 +1,53 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.css; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@Data +@AllArgsConstructor +public class CssStylesSelectors { + +private final String uuid= UUID.randomUUID().toString(); +private final List list=new ArrayList<>(); +public String build(){ + if(list.isEmpty()){ + return ""; + } + StringBuilder sb=new StringBuilder(); + for(CssStylesSelector e:list){ + sb.append(e.build()).append("\n"); + } + return sb.toString(); +} + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/WebElement.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/WebElement.java new file mode 100644 index 0000000..aedfb14 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/WebElement.java @@ -0,0 +1,71 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html; + +import org.nanoboot.powerframework.web.css.CssStylesSelectors; +import org.nanoboot.powerframework.xml.ElementType; +import org.nanoboot.powerframework.xml.Element; +import org.nanoboot.powerframework.xml.XmlTypeI; +import lombok.Getter; + +/** + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class WebElement extends Element { + + @Getter + private final CssStylesSelectors cssStylesSelectors=new CssStylesSelectors(); + + public WebElement(String elementName, String content) { + super(elementName, content); + } + public WebElement(String elementName, XmlTypeI... xmlTypes) { + super(elementName, xmlTypes); + } + + public WebElement(String elementName, ElementType elementType, XmlTypeI... xmlTypes) { + super(elementName, elementType, xmlTypes); + + } + + /** + * Creates new paired element + * + * @param elementName + */ + public WebElement(String elementName) { + super(elementName); + } + + /** + * Creates new element with the specified type + * + * @param elementName + * @param elementType + */ + public WebElement(String elementName, ElementType elementType) { + super(elementName, elementType); + } + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/WebPage.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/WebPage.java new file mode 100644 index 0000000..ac0d6ac --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/WebPage.java @@ -0,0 +1,119 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html; + +import org.nanoboot.powerframework.web.PrettyPrinter; +import org.nanoboot.powerframework.web.css.CssStylesSelectors; +import org.nanoboot.powerframework.web.html.tags.Head; +import org.nanoboot.powerframework.web.html.tags.Html; +import org.nanoboot.powerframework.web.html.tags.Style; +import org.nanoboot.powerframework.xml.Buildable; +import org.nanoboot.powerframework.xml.Element; +import lombok.Data; +import lombok.Getter; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class WebPage implements Buildable { + @Getter + private Html rootElement = new Html(); + + public WebPage() { + Map allCssStylesSelectors = loadAllCssStylesSelectors(); + if (!allCssStylesSelectors.isEmpty()) { + Head head = (Head) this.getElementByNamePath(("html.head")); + Style style = (Style) head.getByElementName("style"); + if (style == null) { + style = new Style(); + head.add(style); + } + for (Map.Entry entry : allCssStylesSelectors.entrySet()) { + + style.getElements().addInnerText(entry.getValue().build()); + } + } + } + + + public String build() { + String result = " \n" + rootElement.build(); + String prettyResult = null; + try { + prettyResult = PrettyPrinter.makePretty(result); + } catch (Exception e) { + System.err.println(e); + } + return prettyResult == null ? result : prettyResult; + } + + @Override + public boolean isModified() { + return false; + } + + @Override + public String getCache() { + return null; + } + + /** + * Remove me + * + * @param elementNamePath + * @return + */ + @Deprecated + public WebElement getElementByNamePath(String elementNamePath) { + return null; + } + + private Map loadAllCssStylesSelectors() { + Map map = new HashMap<>(); + + for (Element e : loadAllElements()) { + WebElement we = (WebElement) e; + if (we.getCssStylesSelectors() == null) { + break; + } + if (map.containsKey(we.getCssStylesSelectors().getUuid())) { + continue; + } + map.put(we.getCssStylesSelectors().getUuid(), we.getCssStylesSelectors()); + + } + + + return map; + } + + private List loadAllElements() { + return this.rootElement.getElements().loadElements(); + + + } +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Action.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Action.java new file mode 100644 index 0000000..b3f6ab6 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Action.java @@ -0,0 +1,40 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.attributes; + +import org.nanoboot.powerframework.xml.Attribute; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Action extends Attribute { + public static final String NAME="action"; + + public Action(String value) { + super(NAME,value); + } + + + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Charset.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Charset.java new file mode 100644 index 0000000..5674b6c --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Charset.java @@ -0,0 +1,41 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.attributes; + + +import org.nanoboot.powerframework.xml.Attribute; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Charset extends Attribute { + public static final String NAME="charset"; + + public Charset(String value) { + super(NAME,value); + } + + + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Class.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Class.java new file mode 100644 index 0000000..b0ebde4 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Class.java @@ -0,0 +1,40 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.attributes; + +import org.nanoboot.powerframework.xml.Attribute; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Class extends Attribute { + public static final String NAME="class"; + + public Class(String value) { + super(NAME,value); + } + + + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Content.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Content.java new file mode 100644 index 0000000..526382d --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Content.java @@ -0,0 +1,40 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.attributes; + +import org.nanoboot.powerframework.xml.Attribute; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Content extends Attribute { + public static final String NAME="content"; + + public Content(String value) { + super(NAME,value); + } + + + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Height.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Height.java new file mode 100644 index 0000000..780be56 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Height.java @@ -0,0 +1,40 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.attributes; + +import org.nanoboot.powerframework.xml.Attribute; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Height extends Attribute { + public static final String NAME="height"; + + public Height(String value) { + super(NAME,value); + } + + + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Href.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Href.java new file mode 100644 index 0000000..53f8554 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Href.java @@ -0,0 +1,40 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.attributes; + +import org.nanoboot.powerframework.xml.Attribute; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Href extends Attribute { + public static final String NAME="href"; + + public Href(String value) { + super(NAME,value); + } + + + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/HttpEquiv.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/HttpEquiv.java new file mode 100644 index 0000000..5db43fe --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/HttpEquiv.java @@ -0,0 +1,41 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.attributes; + + +import org.nanoboot.powerframework.xml.Attribute; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class HttpEquiv extends Attribute { + public static final String NAME="http-equiv"; + + public HttpEquiv(String value) { + super(NAME,value); + } + + + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Id.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Id.java new file mode 100644 index 0000000..7b03887 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Id.java @@ -0,0 +1,40 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.attributes; + +import org.nanoboot.powerframework.xml.Attribute; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Id extends Attribute { + public static final String NAME="id"; + + public Id(String value) { + super(NAME,value); + } + + + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Method.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Method.java new file mode 100644 index 0000000..bd4b7c3 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Method.java @@ -0,0 +1,40 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.attributes; + + +import org.nanoboot.powerframework.xml.Attribute; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class Method extends Attribute { + public static final String NAME="method"; + + public Method(String value) { + super(NAME,value); + } + + + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Name.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Name.java new file mode 100644 index 0000000..f6ad1a4 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Name.java @@ -0,0 +1,41 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.attributes; + + +import org.nanoboot.powerframework.xml.Attribute; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Name extends Attribute { + public static final String NAME="name"; + + public Name(String value) { + super(NAME,value); + } + + + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Rel.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Rel.java new file mode 100644 index 0000000..ea7c2b4 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Rel.java @@ -0,0 +1,40 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.attributes; + + +import org.nanoboot.powerframework.xml.Attribute; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class Rel extends Attribute { + public static final String NAME="rel"; + + public Rel(String value) { + super(NAME,value); + } + + + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Src.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Src.java new file mode 100644 index 0000000..e10975d --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Src.java @@ -0,0 +1,40 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.attributes; + + +import org.nanoboot.powerframework.xml.Attribute; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class Src extends Attribute { + public static final String NAME="src"; + + public Src(String value) { + super(NAME,value); + } + + + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Style.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Style.java new file mode 100644 index 0000000..b201d1b --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Style.java @@ -0,0 +1,60 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.attributes; + +import org.nanoboot.powerframework.xml.Attribute; +import org.nanoboot.powerframework.web.css.CssStyle; +import org.nanoboot.powerframework.web.css.CssStyles; +import lombok.Getter; +import lombok.Setter; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class Style extends Attribute { + public static final String NAME="style"; + + @Getter + @Setter + private CssStyles cssStyles = new CssStyles(); + + public Style(String moreStyles) { + this(new CssStyles(moreStyles)); + } + + public Style(CssStyle cssStyle) { + super(NAME, cssStyle.build());//?? + this.cssStyles.add(cssStyle); + } + public Style(CssStyles cssStyles) { + super(NAME, cssStyles.build()); + for(CssStyle e: cssStyles.getCssStyles()){ + this.cssStyles.add(e); + } + } + public String build(){ + this.setValue(cssStyles.build()); + return super.build(); + } + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Template.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Template.java new file mode 100644 index 0000000..0d13152 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Template.java @@ -0,0 +1,40 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.attributes; + + +import org.nanoboot.powerframework.xml.Attribute; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class Template extends Attribute { + public static final String NAME="id"; + + public Template(String value) { + super(NAME,value); + } + + + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Title.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Title.java new file mode 100644 index 0000000..54630ef --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Title.java @@ -0,0 +1,40 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.attributes; + + +import org.nanoboot.powerframework.xml.Attribute; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class Title extends Attribute { + public static final String NAME="title"; + + public Title(String value) { + super(NAME,value); + } + + + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Type.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Type.java new file mode 100644 index 0000000..9be842a --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Type.java @@ -0,0 +1,39 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.attributes; + +import org.nanoboot.powerframework.xml.Attribute; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class Type extends Attribute { + public static final String NAME="type"; + + public Type(String value) { + super(NAME,value); + } + + + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Value.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Value.java new file mode 100644 index 0000000..89a6d25 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Value.java @@ -0,0 +1,39 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.attributes; + +import org.nanoboot.powerframework.xml.Attribute; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class Value extends Attribute { + public static final String NAME="value"; + + public Value(String value) { + super(NAME,value); + } + + + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Width.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Width.java new file mode 100644 index 0000000..fe7fb26 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/attributes/Width.java @@ -0,0 +1,39 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.attributes; + +import org.nanoboot.powerframework.xml.Attribute; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class Width extends Attribute { + public static final String NAME="width"; + + public Width(String value) { + super(NAME,value); + } + + + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/A.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/A.java new file mode 100644 index 0000000..7067830 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/A.java @@ -0,0 +1,73 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +import org.nanoboot.powerframework.xml.XmlUtils; +import org.nanoboot.powerframework.web.html.attributes.Href; +import org.nanoboot.powerframework.web.html.attributes.Title; +import org.nanoboot.powerframework.web.html.WebElement; +import org.nanoboot.powerframework.xml.XmlTypeI; +import lombok.Data; + +import java.util.Set; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class A extends WebElement { + public static final String NAME = "a"; + + public static final Set ALLOWED_ATTRIBUTES + = XmlUtils.createNewSet(Href.NAME, Title.NAME); + + public A(XmlTypeI xmlTypes) { + this(); + add(xmlTypes); + } + + public A() { + super(NAME); + + } + + public A(String href) { + this(href, href); + + + } + + public A(String href, String title) { + this(); + this.add(new Href(href)); + if (title != null) { + this.add(new Title(title)); + } + } + + + @Override + public Set getAllowedAttributes() { + return ALLOWED_ATTRIBUTES; + } + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Body.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Body.java new file mode 100644 index 0000000..4a3bd58 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Body.java @@ -0,0 +1,59 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +import org.nanoboot.powerframework.xml.XmlUtils; +import org.nanoboot.powerframework.web.html.WebElement; +import org.nanoboot.powerframework.xml.XmlTypeI; +import lombok.Data; + +import java.util.Set; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@Data +public class Body extends WebElement { + public static final String NAME = "body"; + + public static final Set ALLOWED_ATTRIBUTES + = XmlUtils.createNewSet(); + public Body(XmlTypeI xmlTypes) { + this(); + add(xmlTypes); + } + + public Body() { + super(NAME); + + } + + + @Override + public Set getAllowedAttributes() { + return ALLOWED_ATTRIBUTES; + } + + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Br.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Br.java new file mode 100644 index 0000000..0dd4329 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Br.java @@ -0,0 +1,43 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +import org.nanoboot.powerframework.web.html.WebElement; +import org.nanoboot.powerframework.xml.ElementType; +import lombok.Data; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@Data +public final class Br extends WebElement { + public static final String NAME = "br"; + + public Br() { + super(NAME, ElementType.NOT_PAIRED); + + } + + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Div.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Div.java new file mode 100644 index 0000000..a4067a8 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Div.java @@ -0,0 +1,59 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +import org.nanoboot.powerframework.xml.XmlUtils; +import org.nanoboot.powerframework.web.html.WebElement; +import org.nanoboot.powerframework.xml.XmlTypeI; +import lombok.Data; + +import java.util.Set; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Div extends WebElement { + private static final String NAME = "div"; + + + public static final Set ALLOWED_ATTRIBUTES + = XmlUtils.createNewSet(""); + + public Div(XmlTypeI xmlTypes) { + this(); + add(xmlTypes); + } + + public Div() { + super(NAME); + + } + + @Override + public Set getAllowedAttributes() { + return ALLOWED_ATTRIBUTES; + } + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Form.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Form.java new file mode 100644 index 0000000..cdef108 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Form.java @@ -0,0 +1,83 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +import org.nanoboot.powerframework.web.html.attributes.Id; +import org.nanoboot.powerframework.xml.XmlUtils; +import org.nanoboot.powerframework.web.html.attributes.Action; +import org.nanoboot.powerframework.web.html.attributes.Method; +import org.nanoboot.powerframework.web.html.attributes.Name; +import org.nanoboot.powerframework.web.html.WebElement; +import org.nanoboot.powerframework.xml.NoElement; +import org.nanoboot.powerframework.xml.XmlTypeI; + +import java.util.Set; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Form extends WebElement { + + public static final String NAME = "form"; + public static final Set ALLOWED_ELEMENTS + = XmlUtils.createNewSet(Input.NAME, Br.NAME, Label.NAME, Select.NAME); + + public static final Set ALLOWED_ATTRIBUTES + = XmlUtils.createNewSet(Name.NAME, Action.NAME, Method.NAME, NoElement.NAME, Id.NAME); + + public Form(XmlTypeI xmlTypes) { + this(); + add(xmlTypes); + } + + public Form() { + super(NAME); + + } + + public Form(String action, FormMethod method) { + this(); + getAttributes().add("action", action); + getAttributes().add("method", method.name()); + + } + + public Form(String action, String method) { + this(); + getAttributes().add("action", action); + getAttributes().add("method", method); + + } + + @Override + public Set getAllowedElements() { + return ALLOWED_ELEMENTS; + } + + @Override + public Set getAllowedAttributes() { + return ALLOWED_ATTRIBUTES; + } + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/FormMethod.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/FormMethod.java new file mode 100644 index 0000000..97cca6d --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/FormMethod.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public enum FormMethod { + GET, POST; +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/H1.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/H1.java new file mode 100644 index 0000000..65a1468 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/H1.java @@ -0,0 +1,62 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +import org.nanoboot.powerframework.web.html.WebElement; +import org.nanoboot.powerframework.xml.XmlTypeI; +import org.nanoboot.powerframework.xml.XmlUtils; +import lombok.Data; + +import java.util.Set; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class H1 extends WebElement { + private static final String NAME = "h1"; + + + public static final Set ALLOWED_ATTRIBUTES + = XmlUtils.createNewSet(""); + + public H1(XmlTypeI xmlTypes) { + this(); + add(xmlTypes); + } + + public H1() { + super(NAME); + + } + + public H1(String title) { + this(); + setInnerText(title); + } + @Override + public Set getAllowedAttributes() { + return ALLOWED_ATTRIBUTES; + } + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/H2.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/H2.java new file mode 100644 index 0000000..accedd2 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/H2.java @@ -0,0 +1,62 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +import org.nanoboot.powerframework.web.html.WebElement; +import org.nanoboot.powerframework.xml.XmlTypeI; +import org.nanoboot.powerframework.xml.XmlUtils; +import lombok.Data; + +import java.util.Set; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class H2 extends WebElement { + private static final String NAME = "h2"; + + + public static final Set ALLOWED_ATTRIBUTES + = XmlUtils.createNewSet(""); + + public H2(XmlTypeI xmlTypes) { + this(); + add(xmlTypes); + } + + public H2() { + super(NAME); + + } + + public H2(String title) { + this(); + setInnerText(title); + } + @Override + public Set getAllowedAttributes() { + return ALLOWED_ATTRIBUTES; + } + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/H3.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/H3.java new file mode 100644 index 0000000..24ebaac --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/H3.java @@ -0,0 +1,62 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +import org.nanoboot.powerframework.web.html.WebElement; +import org.nanoboot.powerframework.xml.XmlTypeI; +import org.nanoboot.powerframework.xml.XmlUtils; +import lombok.Data; + +import java.util.Set; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class H3 extends WebElement { + private static final String NAME = "h3"; + + + public static final Set ALLOWED_ATTRIBUTES + = XmlUtils.createNewSet(""); + + public H3(XmlTypeI xmlTypes) { + this(); + add(xmlTypes); + } + + public H3() { + super(NAME); + + } + + public H3(String title) { + this(); + setInnerText(title); + } + @Override + public Set getAllowedAttributes() { + return ALLOWED_ATTRIBUTES; + } + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Head.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Head.java new file mode 100644 index 0000000..22d8178 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Head.java @@ -0,0 +1,57 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +import org.nanoboot.powerframework.xml.XmlUtils; +import org.nanoboot.powerframework.web.html.WebElement; +import org.nanoboot.powerframework.xml.XmlTypeI; +import lombok.Data; + +import java.util.Set; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@Data +public class Head extends WebElement { + public static final String NAME="head"; + public static final Set ALLOWED_ELEMENTS= XmlUtils.createNewSet(Meta.NAME,Title.NAME,Link.NAME); + public static final Set ALLOWED_ATTRIBUTES + = XmlUtils.createNewSet(); + + + public Head(XmlTypeI xmlTypes) { + this(); + } + + public Head() { + super(NAME); + } + + @Override + public Set getAllowedAttributes() { + return ALLOWED_ATTRIBUTES; + } + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/HiddenInput.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/HiddenInput.java new file mode 100644 index 0000000..ce873a3 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/HiddenInput.java @@ -0,0 +1,34 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class HiddenInput extends Input { + public HiddenInput(String name, String value) { + super(InputType.HIDDEN, name, value); + } +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Hr.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Hr.java new file mode 100644 index 0000000..0015f8a --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Hr.java @@ -0,0 +1,55 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +import org.nanoboot.powerframework.web.html.WebElement; +import org.nanoboot.powerframework.xml.XmlTypeI; +import org.nanoboot.powerframework.xml.XmlUtils; +import lombok.Data; + +import java.util.Set; +import org.nanoboot.powerframework.xml.ElementType; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Hr extends WebElement { + private static final String NAME = "hr"; + + + public static final Set ALLOWED_ATTRIBUTES + = XmlUtils.createNewSet(""); + + + public Hr() { + super(NAME, ElementType.NOT_PAIRED); + + } + + @Override + public Set getAllowedAttributes() { + return ALLOWED_ATTRIBUTES; + } + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Html.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Html.java new file mode 100644 index 0000000..90e97c1 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Html.java @@ -0,0 +1,54 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +import org.nanoboot.powerframework.xml.XmlUtils; +import org.nanoboot.powerframework.web.html.WebElement; +import org.nanoboot.powerframework.xml.XmlTypeI; +import lombok.Data; + +import java.util.Set; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@Data +public final class Html extends WebElement { + public static final String NAME = "html"; + public static final Set ALLOWED_ELEMENTS= XmlUtils.createNewSet(Head.NAME,Body.NAME); + + public Html() { + super(NAME); + } + + public Html(XmlTypeI xmlTypes) { + this(); + add(xmlTypes); + } + + @Override + public Set getAllowedElements() { + return ALLOWED_ELEMENTS; + } +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/HtmlElement.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/HtmlElement.java new file mode 100644 index 0000000..40dd292 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/HtmlElement.java @@ -0,0 +1,65 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +import org.nanoboot.powerframework.web.html.WebElement; +import org.nanoboot.powerframework.xml.ElementType; +import org.nanoboot.powerframework.xml.XmlTypeI; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@Deprecated +public class HtmlElement extends WebElement { + + //private final CssStylesSelectors cssStylesSelectors=new CssStylesSelectors(); + public HtmlElement(String elementName, XmlTypeI... xmlTypes) { + super(elementName, xmlTypes); + } + + public HtmlElement(String elementName, ElementType elementType, XmlTypeI... xmlTypes) { + super(elementName, elementType, xmlTypes); + + } + + /** + * Creates new paired element + * + * @param elementName + */ + public HtmlElement(String elementName) { + super(elementName); + } + + /** + * Creates new element with the specified type + * + * @param elementName + * @param elementType + */ + public HtmlElement(String elementName, ElementType elementType) { + super(elementName, elementType); + } + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Img.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Img.java new file mode 100644 index 0000000..391693c --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Img.java @@ -0,0 +1,63 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +import org.nanoboot.powerframework.xml.XmlUtils; +import org.nanoboot.powerframework.web.html.WebElement; +import org.nanoboot.powerframework.xml.ElementType; +import org.nanoboot.powerframework.xml.XmlTypeI; +import lombok.Data; +import org.nanoboot.powerframework.web.html.attributes.Height; +import org.nanoboot.powerframework.web.html.attributes.Src; +import org.nanoboot.powerframework.web.html.attributes.Width; + +import java.util.Set; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@Data +public final class Img extends WebElement { + public static final String NAME = "img"; + + + public static final Set ALLOWED_ATTRIBUTES + = XmlUtils.createNewSet(Src.NAME, Width.NAME, Height.NAME); + + public Img(XmlTypeI xmlTypes) { + this(); + add(xmlTypes); + } + + public Img() { + super(NAME, ElementType.NOT_PAIRED); + + } + + @Override + public Set getAllowedAttributes() { + return ALLOWED_ATTRIBUTES; + } + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Input.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Input.java new file mode 100644 index 0000000..baf4a0b --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Input.java @@ -0,0 +1,101 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +import org.nanoboot.powerframework.xml.ElementType; +import org.nanoboot.powerframework.xml.XmlUtils; +import org.nanoboot.powerframework.web.html.attributes.Name; +import org.nanoboot.powerframework.web.html.attributes.Type; +import org.nanoboot.powerframework.web.html.attributes.Value; +import org.nanoboot.powerframework.web.html.WebElement; +import org.nanoboot.powerframework.xml.XmlTypeI; + +import java.util.Set; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Input extends WebElement { + + public static final String NAME = "input"; + + public static final Set ALLOWED_ATTRIBUTES + = XmlUtils.createNewSet(Name.NAME, Type.NAME, Value.NAME); + + public Input(XmlTypeI xmlTypes) { + this(); + add(xmlTypes); + } + + public Input() { + super(NAME, ElementType.NOT_PAIRED); + + } + + public Input(String name, String value) { + this(null, name, value); + } + + public Input(InputType type, String name, String value) { + this(); + if (type != null) { + withType(type); + } + withNameAndValue(name, value); + } + + public Input withType(InputType type) { + this.add(new Type(type.name().toLowerCase())); + return this; + } + + public Input withType(String type) { + this.add(new Type(type)); + return this; + } + + public Input withNameAndValue(String name, String value) { + withName(name); + withValue(value); + return this; + } + + public Input withName(String name) { + if (name != null) { + this.add(new Name(name)); + } + return this; + } + + public Input withValue(String value) { + this.add(new Value(value)); + return this; + } + + @Override + public Set getAllowedAttributes() { + return ALLOWED_ATTRIBUTES; + } + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/InputType.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/InputType.java new file mode 100644 index 0000000..a7f98ef --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/InputType.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public enum InputType { + TEXT, PASSWORD, HIDDEN, RADIO, CHECKBOX, SUBMIT; +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Label.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Label.java new file mode 100644 index 0000000..143107e --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Label.java @@ -0,0 +1,58 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +import org.nanoboot.powerframework.web.html.WebElement; +import org.nanoboot.powerframework.xml.XmlUtils; + +import java.util.Set; +import org.nanoboot.powerframework.xml.Attribute; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Label extends WebElement { + public static final String NAME = "label"; + + + public static final Set ALLOWED_ATTRIBUTES + = XmlUtils.createNewSet("for"); + + public Label(String title, String forId) { + this(title); + this.add(new Attribute("for",forId)); + } + + public Label(String title) { + super(NAME); + setInnerText(title); + + } + + @Override + public Set getAllowedAttributes() { + return ALLOWED_ATTRIBUTES; + } + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Li.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Li.java new file mode 100644 index 0000000..d9213bb --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Li.java @@ -0,0 +1,60 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +import org.nanoboot.powerframework.web.html.WebElement; +import org.nanoboot.powerframework.xml.NoElement; +import org.nanoboot.powerframework.xml.XmlTypeI; +import org.nanoboot.powerframework.xml.XmlUtils; + +import java.util.Set; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public final class Li extends WebElement { + public static final String NAME = "li"; + + public static final Set ALLOWED_ATTRIBUTES + = XmlUtils.createNewSet(); + + public Li(String string) { + this(new NoElement(string)); + } + public Li(XmlTypeI xmlTypes) { + this(); + add(xmlTypes); + } + + public Li() { + super(NAME); + + } + + @Override + public Set getAllowedAttributes() { + return ALLOWED_ATTRIBUTES; + } + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Link.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Link.java new file mode 100644 index 0000000..76a43f6 --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Link.java @@ -0,0 +1,63 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +import org.nanoboot.powerframework.xml.XmlUtils; +import org.nanoboot.powerframework.web.html.attributes.Href; +import org.nanoboot.powerframework.web.html.attributes.Rel; +import org.nanoboot.powerframework.web.html.attributes.Type; +import org.nanoboot.powerframework.web.html.WebElement; +import org.nanoboot.powerframework.xml.ElementType; +import org.nanoboot.powerframework.xml.XmlTypeI; +import lombok.Data; + +import java.util.Set; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +@Data +public final class Link extends WebElement { + public static final String NAME = "link"; + + public static final Set ALLOWED_ATTRIBUTES + = XmlUtils.createNewSet(Rel.NAME, Href.NAME, Type.NAME); + + + public Link() { + super(NAME,ElementType.NOT_PAIRED); + + } + public Link(XmlTypeI... xmlTypes) { + this(); + + this.add(xmlTypes); + } + + @Override + public Set getAllowedAttributes() { + return ALLOWED_ATTRIBUTES; + } + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Meta.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Meta.java new file mode 100644 index 0000000..a623e9f --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Meta.java @@ -0,0 +1,57 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +import org.nanoboot.powerframework.xml.XmlUtils; +import org.nanoboot.powerframework.web.html.attributes.Charset; +import org.nanoboot.powerframework.web.html.attributes.Content; +import org.nanoboot.powerframework.web.html.attributes.HttpEquiv; +import org.nanoboot.powerframework.web.html.WebElement; +import org.nanoboot.powerframework.xml.ElementType; +import lombok.Data; + +import java.util.Set; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public final class Meta extends WebElement { + public static final String NAME = "meta"; + + public static final Set ALLOWED_ATTRIBUTES + = XmlUtils.createNewSet(HttpEquiv.NAME, Content.NAME, Charset.NAME); + + public Meta() { + super(NAME, ElementType.NOT_PAIRED); + + } + + + + @Override + public Set getAllowedAttributes() { + return ALLOWED_ATTRIBUTES; + } + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Ol.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Ol.java new file mode 100644 index 0000000..620de6b --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Ol.java @@ -0,0 +1,56 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +import org.nanoboot.powerframework.web.html.WebElement; +import org.nanoboot.powerframework.xml.NoElement; +import org.nanoboot.powerframework.xml.XmlTypeI; +import org.nanoboot.powerframework.xml.XmlUtils; + +import java.util.Set; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public final class Ol extends WebElement { + public static final String NAME = "ol"; + + public static final Set ALLOWED_ATTRIBUTES + = XmlUtils.createNewSet(); + + public Ol(XmlTypeI xmlTypes) { + this(); + add(xmlTypes); + } + + public Ol() { + super(NAME); + + } + + @Override + public Set getAllowedAttributes() { + return ALLOWED_ATTRIBUTES; + } + +} diff --git a/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Option.java b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Option.java new file mode 100644 index 0000000..8264d5e --- /dev/null +++ b/power-web/src/main/java/org/nanoboot/powerframework/web/html/tags/Option.java @@ -0,0 +1,74 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.web.html.tags; + +import org.nanoboot.powerframework.web.html.WebElement; +import org.nanoboot.powerframework.web.html.attributes.Id; +import org.nanoboot.powerframework.web.html.attributes.Name; +import org.nanoboot.powerframework.xml.XmlUtils; + +import java.util.Set; +import org.nanoboot.powerframework.xml.Attribute; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class Option extends WebElement { + public static final String NAME = "option"; + + public static final Set ALLOWED_ATTRIBUTES + = XmlUtils.createNewSet("label", "value", "selected"); + + public Option() { + super(NAME); + + } + public Option(String title) { + this(); + setInnerText(title); + + } + public Option withSelected() { + this.add(new Attribute("selected", "selected")); + return this; + } + public Option withValue(String value) { + this.add(new Attribute("value", value)); + return this; + } + public Option withLabel(String label) { + this.add(new Attribute("label", label)); + return this; + } + public Option withEmptyLabel() { + this.add(new Attribute("label", " ")); + return this; + } + @Override + public Set getAllowedAttributes() { + return ALLOWED_ATTRIBUTES; + } +} +// +//

"; + public static final String H1_END = "

"; + public static final String H2_START = "

"; + public static final String H2_END = "

"; + public static final String H3_START = "

"; + public static final String H3_END = "

"; + public static final String H4_START = "

"; + public static final String H4_END = "

"; + public static final String H5_START = "
"; + public static final String H5_END = "
"; + public static final String H6_START = "
"; + public static final String H6_END = "
"; + + public static final String OL_START = "
    "; + public static final String OL_END = "
"; + public static final String UL_START = "
    "; + public static final String UL_END = "
"; + public static final String LI_START = "
  • "; + public static final String LI_END = "
  • "; + public static final String P_START = "

    "; + public static final String P_END = "

    "; + + public static final String TABLE_START = ""; + public static final String TABLE_END = "
    "; + public static final String TR_START = ""; + public static final String TR_END = ""; + public static final String TH_START = ""; + public static final String TH_END = ""; + public static final String TD_START = ""; + public static final String TD_END = ""; + + public static final String HR4 = "
    "; + public static final String HR5 = "
    "; + public static final String HR6 = "
    "; + public static final String HR7 = "
    "; + public static final String HR8 = "
    "; + public static final String HR9 = "
    "; + public static final String HR10 = "
    "; + + public static final String COMMENT_TEMPLATE = ""; + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private HtmlTags() { + } + +} diff --git a/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/Macro.java b/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/Macro.java new file mode 100644 index 0000000..e508312 --- /dev/null +++ b/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/Macro.java @@ -0,0 +1,65 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.wiki; + +/** + * Here goes the description of this class. + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Macro { + + /** + * Logger for this class. + */ + private static final org.nanoboot.powerframework.log.Logger LOG = org.nanoboot.powerframework.log.Logger.getLogger(Macro.class); + + /** + * Constant description + */ + private static final String CONSTANT = "constant"; + + /** + * Field description + */ + private String content; + private final String value; + + /** + * Constructor + * + * Constructor description + * + * @param nameIn + */ + public Macro(String content, TextProcessorI processor) { + this.content = content; + this.value = processor.process(content); + } + + public String getValue() { + return value; + } + +} diff --git a/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/StringSource.java b/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/StringSource.java new file mode 100644 index 0000000..2b23885 --- /dev/null +++ b/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/StringSource.java @@ -0,0 +1,75 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.wiki; + +/** + * Here goes the description of this class. + * + * @author Robert Vokac + * @since 0.0.0 + * + */ +public class StringSource { + + /** + * Logger for this class. + */ + private static final org.nanoboot.powerframework.log.Logger LOG = org.nanoboot.powerframework.log.Logger.getLogger(StringSource.class); + + /** + * Constant description + */ + private static final String CONSTANT = "constant"; + + /** + * Field description + */ + private String string; + private int position = 0; + + /** + * Constructor + * + */ + public StringSource(String string) { + this.string = string; + } + + public char getNext() { + return string.charAt(position++); + } + + public char getLast() { + if(position - 1 == 0) { + return ' '; + } + return string.charAt(position - 1); + } + + public boolean hasNext() { + return position <= string.length() - 1; + } + + public char get(int number) { + return string.charAt(position + number); + } + +} diff --git a/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/TextFormatter.java b/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/TextFormatter.java new file mode 100644 index 0000000..e560e48 --- /dev/null +++ b/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/TextFormatter.java @@ -0,0 +1,81 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.wiki; + +/** + * Here goes the description of this class. + * + * + * @author Robert Vokac + * @since 0.0.0 + * + */ +public class TextFormatter { + + /** + * Logger for this class. + */ + private static final org.nanoboot.powerframework.log.Logger LOG = org.nanoboot.powerframework.log.Logger.getLogger(TextFormatter.class); + + /** + * Constant description + */ + private static final String CONSTANT = "constant"; + + /** + * Field description + */ + private String name; + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private TextFormatter() { + } + + public static String format(String text) { + StringSource stringSource = new StringSource(text); + StringBuilder out = new StringBuilder(); + StringBuilder buffer = new StringBuilder(); + while (stringSource.hasNext()) { + char ch = stringSource.getNext(); + + if(ch == '[' && stringSource.getLast() == '[') { + ch = stringSource.getNext(); + while (!(ch == ']' && stringSource.get(1) == ']')) { + buffer.append(ch); + if(!stringSource.hasNext()) { + break; + } + ch = stringSource.getNext(); + } + out.append(buffer.toString()); + buffer.delete(0, buffer.length()); + }; + + } + + return out.toString(); + } + +} diff --git a/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/TextProcessorI.java b/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/TextProcessorI.java new file mode 100644 index 0000000..8d44412 --- /dev/null +++ b/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/TextProcessorI.java @@ -0,0 +1,34 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.wiki; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public interface TextProcessorI { + + public String process(String text); + + public String getName(); +} diff --git a/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/WikiException.java b/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/WikiException.java new file mode 100644 index 0000000..f825fda --- /dev/null +++ b/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/WikiException.java @@ -0,0 +1,53 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.wiki; + +import org.nanoboot.powerframework.core.PowerException; + +/** + * Here goes the description of this class. + * + * @author Robert Vokac + * @since 0.0.0 + * + */ +public class WikiException extends PowerException { + + /** + * Logger for this class. + */ + private static final org.nanoboot.powerframework.log.Logger LOG = org.nanoboot.powerframework.log.Logger.getLogger(WikiException.class); + + /** + * Constant description + */ + private static final String CONSTANT = "constant"; + + /** + * Field description + */ + private String name; + + public WikiException(String messageIn) { + super(messageIn); + } + +} diff --git a/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/WikiMarks.java b/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/WikiMarks.java new file mode 100644 index 0000000..df0d2ba --- /dev/null +++ b/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/WikiMarks.java @@ -0,0 +1,108 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.wiki; + +/** + * Here goes the description of this class. + * + * @author Robert Vokac + * @since 0.0.0 + * + */ +public class WikiMarks { + + /** + * Logger for this class. + */ + private static final org.nanoboot.powerframework.log.Logger LOG = org.nanoboot.powerframework.log.Logger.getLogger(WikiMarks.class); + + /** + * Constant description + */ + private static final String CONSTANT = "constant"; + + public static final String BOLD = "\\*\\*"; + public static final String ITALIC = "//"; + public static final String UNDERLINED = "__"; + public static final String COLOURED = "$$"; + public static final String BACKGROUND_HIGHLIGHTED = "##"; + public static final String SUPERSCRIPT = "^"; + public static final String SUBSCRIPT = ",,"; + public static final String MONOSPACE = "`"; + public static final String STROKE = "--"; + public static final String SMALLER_START = "~-"; + public static final String SMALLER_END = "-~"; + public static final String LARGER_START = "~+"; + public static final String LARGER_END = "+~"; + + public static final String LINK_START = "[["; + public static final String LINK_END = "]]"; + public static final String EMBED_START = "{{"; + public static final String EMBED_END = "}}"; + public static final String SIZE = "&&"; + + public static final String MACRO_START = "<<"; + public static final String MACRO_END = ">>"; + + public static final String PARSER_START = "{{{"; + public static final String PARSER_END = "}}}"; + + public static final String HEADING1_START = "= "; + public static final String HEADING2_START = "== "; + public static final String HEADING3_START = "=== "; + public static final String HEADING4_START = "==== "; + public static final String HEADING5_START = "===== "; + public static final String HEADING6_START = "====== "; + public static final String HEADING1_END = " ="; + public static final String HEADING2_END = " =="; + public static final String HEADING3_END = " ==="; + public static final String HEADING4_END = " ===="; + public static final String HEADING5_END = " ====="; + public static final String HEADING6_END = " ======"; + public static final String UNORDERED_LIST = " *"; + public static final String ORDERED_LIST = " 1."; + public static final String TABLE_BORDER = " || "; + public static final String TABLE_COLOURED = "$$$"; + public static final String TABLE_BACKGROUND_HIGHLIGHTED = "###"; + + public static final String HORIZONTAL_RULE_4 = "----"; + public static final String HORIZONTAL_RULE_5 = "-----"; + public static final String HORIZONTAL_RULE_6 = "------"; + public static final String HORIZONTAL_RULE_7 = "-------"; + public static final String HORIZONTAL_RULE_8 = "--------"; + public static final String HORIZONTAL_RULE_9 = "---------"; + public static final String HORIZONTAL_RULE_10 = "----------"; + public static final String COMMENT_LINE_BEGINNING = "####"; + + /** + * Field description + */ + private String name; + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private WikiMarks() { + } + +} diff --git a/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/WikiParser.java b/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/WikiParser.java new file mode 100644 index 0000000..149771f --- /dev/null +++ b/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/WikiParser.java @@ -0,0 +1,192 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.wiki; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Pattern; +import org.nanoboot.powerframework.utils.StringUtils; + +/** + * Here goes the description of this class. + * + * @author Robert Vokac + * @since 0.0.0 + * + */ +public class WikiParser { + + /** + * Logger for this class. + */ + //private static final org.nanoboot.powerframework.logging.Logger LOG = org.nanoboot.powerframework.logging.Logger.getLogger(WikiParser.class); + /** + * Constant description + */ + private static final String CONSTANT = "constant"; + + /** + * Field description + */ + private static TextProcessorI linkProcessor; + private static final Map macroProcessorsList = new HashMap<>(); + + /** + * Constructor + * + * Not meant to be instantiated. + */ + public static void setLinkProcessor(TextProcessorI linkProcessorIn) { + linkProcessor = linkProcessorIn; + } + + public String convertWiki(String wikiText) { + System.out.println("Converting wiki text:\n\n"+wikiText); + ArrayList blocks = splitWikiTextToBlocks(wikiText); + StringBuilder stringBuilder = new StringBuilder(); + for (Block block : blocks) { + System.out.println("\n====================\n"+block.getBlockType()+"\n\n"); + String html = block.toHtml(); + System.out.println(block.getOrig()); + System.out.println("VVVVVVVVVVVVVVVVVVVV"); +System.out.println(html); + stringBuilder.append(html).append('\n').append('\n'); + } + String string = stringBuilder.toString(); + return string; + } + + public void setStyle(String string) { + + } + + public void addMacroProcessor(TextProcessorI macroProcessor) { + macroProcessorsList.put(macroProcessor.getName(), macroProcessor); + } + + public TextProcessorI getMacroProcessor(String macroName) { + return macroProcessorsList.get(macroName); + } + + @Deprecated + public static String convert(String wikiText) { + + //System.err.println("\n\n\nWIKI" + "\n{\n" + wikiText + "\n}######$$$"); + while (true) { + if(wikiText.contains(WikiMarks.BOLD)) { + wikiText = wikiText.replaceFirst(WikiMarks.BOLD, HtmlTags.B_START); + //System.err.println(String.format("Replacing %s by %s", BOLD, B_START)); + } + if(wikiText.contains(WikiMarks.BOLD)) { + wikiText = wikiText.replaceFirst(WikiMarks.BOLD, HtmlTags.B_END); + //System.err.println(String.format("Replacing %s by %s", BOLD, B_END)); + } + + if(!wikiText.contains(WikiMarks.BOLD)) { + break; + } + } + + while (true) { + + if(wikiText.contains(WikiMarks.ITALIC)) { + wikiText = wikiText.replaceFirst(WikiMarks.ITALIC, HtmlTags.I_START); + //System.err.println(String.format("Replacing %s by %s", ITALIC, I_START)); + } + if(wikiText.contains(WikiMarks.ITALIC)) { + wikiText = wikiText.replaceFirst(WikiMarks.ITALIC, HtmlTags.I_END); + //System.err.println(String.format("Replacing %s by %s", ITALIC, I_END)); + } + if(!wikiText.contains(WikiMarks.ITALIC)) { + break; + } + } + StringBuilder stringBuilder = new StringBuilder(); + + ArrayList blocks = splitWikiTextToBlocks(wikiText); + +// StringBuilder stringBuilder2 = new StringBuilder("Adding block\n\n"); +// for (Block block : blocks) { +// stringBuilder2.append("\n###{\n").append(block.toHtml()).append("\n}\n"); +// } + //System.err.println(stringBuilder2); +// try { +// Thread.sleep(10000); +// } catch (InterruptedException ex) { +// Logger.getLogger(WikiParser.class.getName()).log(Level.SEVERE, null, ex); +// } + for (Block block : blocks) { + String html = block.toHtml(); + + stringBuilder.append(html).append('\n').append('\n'); + } + String string = stringBuilder.toString(); + //System.out.println("Wiki convertor returned\n\n\n{\n" + string + "\n}\n\n\n"); + return string; + } + + @Deprecated + private String processText(String text) { + StringSource stringSource = new StringSource(text); + StringBuilder out = new StringBuilder(); + StringBuilder buffer = new StringBuilder(); + while (stringSource.hasNext()) { + char ch = stringSource.getNext(); + + if(ch == '[' && stringSource.getLast() == '[') { + ch = stringSource.getNext(); + while (!(ch == ']' && stringSource.get(1) == ']')) { + buffer.append(ch); + if(!stringSource.hasNext()) { + break; + } + ch = stringSource.getNext(); + } + out.append(buffer.toString()); + buffer.delete(0, buffer.length()); + }; + + } + + return out.toString(); + } + + @Deprecated + public static void replaceOccurences(StringBuilder stringBuilder, String what, String replacement) { + Pattern.compile(what).matcher(stringBuilder).replaceAll(replacement); + } + + public static ArrayList splitWikiTextToBlocks(String wikiText) { + BlockList blockList = new BlockList(); + + ArrayList blocks; + String[] lines = StringUtils.toLines(wikiText); + + for (String line : lines) { + blockList.addLine(line); + } + blocks = blockList.getList(); + + return blocks; + } + +} diff --git a/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/convertors/ListConvertor.java b/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/convertors/ListConvertor.java new file mode 100644 index 0000000..124c680 --- /dev/null +++ b/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/convertors/ListConvertor.java @@ -0,0 +1,89 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.wiki.convertors; + +import org.nanoboot.powerframework.core.PowerObject; + +/** + * Here goes the description of this class. + * + * @author Robert Vokac + * @since 0.0.0 + * + */ +public class ListConvertor extends PowerObject { + + /** + * Logger for this class. + */ + private static final org.nanoboot.powerframework.log.Logger LOG = org.nanoboot.powerframework.log.Logger.getLogger(ListConvertor.class); + + /** + * Constant description + */ + private static final String CONSTANT = "constant"; + + /** + * Field description + */ + private String name; + + /** + * Constructor + * + * Not meant to be instantiated. + */ + private ListConvertor() { + } + + /** + * Constructor + * + * Constructor description + * + * @param nameIn + */ + public ListConvertor(String nameIn) { + this.name = nameIn; + } + + /** + * Setter for name. + * + * @param nameIn + */ + public void setName(String nameIn) { + LOG.traceStartOfMethod(this, "setName", "name", name); + this.name = nameIn; + } + + /** + * Getter for name. + * + * @return name + */ + public String getName() { + LOG.traceStartOfMethod(this, "getName"); + return this.name; + } + + +} diff --git a/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/macroprocessors/.gitkeep b/power-wiki/src/main/java/org/nanoboot/powerframework/wiki/macroprocessors/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-wiki/src/main/resources/.gitkeep b/power-wiki/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-wiki/src/test/java/org/nanoboot/powerframework/wiki/.gitkeep b/power-wiki/src/test/java/org/nanoboot/powerframework/wiki/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-xml/pom.xml b/power-xml/pom.xml new file mode 100644 index 0000000..c7e4fb7 --- /dev/null +++ b/power-xml/pom.xml @@ -0,0 +1,62 @@ + + + + 4.0.0 + + + org.nanoboot.powerframework + power-framework + 2.0.0-SNAPSHOT + + + power-xml + jar + + Power XML + XML for the Power library + + + + + org.nanoboot.powerframework + power-core + ${power.version} + + + org.nanoboot.powerframework + power-log + ${power.version} + + + + + junit + junit + 4.12 + test + + + org.projectlombok + lombok + + + diff --git a/power-xml/src/main/java/module-info.java b/power-xml/src/main/java/module-info.java new file mode 100644 index 0000000..50af5ba --- /dev/null +++ b/power-xml/src/main/java/module-info.java @@ -0,0 +1,31 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +module powerframework.xml { + exports org.nanoboot.powerframework.xml; + requires lombok; + requires powerframework.core; +} diff --git a/power-xml/src/main/java/org/nanoboot/powerframework/xml/.gitkeep b/power-xml/src/main/java/org/nanoboot/powerframework/xml/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-xml/src/main/java/org/nanoboot/powerframework/xml/Attribute.java b/power-xml/src/main/java/org/nanoboot/powerframework/xml/Attribute.java new file mode 100644 index 0000000..727d33a --- /dev/null +++ b/power-xml/src/main/java/org/nanoboot/powerframework/xml/Attribute.java @@ -0,0 +1,76 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.xml; + +import lombok.Getter; +import lombok.Setter; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Attribute implements XmlTypeI,Buildable{ + @Getter + private final String name; + @Getter + @Setter + private String value; + + public Attribute(String name) { + this(name, null); + } + + public Attribute(String name, String value) { + this.name=name; + this.value=value; + } + + public final Attribute copy() { + return new Attribute(name, value); + } + + public String build() { + if (value == null) { + return name; + } + return name + '=' + '"' + value + '"'; + } + + @Override + public boolean isModified() { + return false; + } + + @Override + public String getCache() { + return null; + } + + public String toString() { + return build(); + } + + public XmlType getXmlType(){ + return XmlType.ATTRIBUTE; + } +} diff --git a/power-xml/src/main/java/org/nanoboot/powerframework/xml/Attributes.java b/power-xml/src/main/java/org/nanoboot/powerframework/xml/Attributes.java new file mode 100644 index 0000000..2e77323 --- /dev/null +++ b/power-xml/src/main/java/org/nanoboot/powerframework/xml/Attributes.java @@ -0,0 +1,208 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.xml; + +import org.nanoboot.powerframework.core.PowerException; +import lombok.Getter; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Attributes implements Buildable { + + public static final char ELEMENT_SPACE = ' '; + + @Getter + private final List list = new ArrayList<>(); + private final Set allowedAttributes; + private boolean allowAnyAttribute = false; + + public boolean isAllowAnyAttribute() { + return allowAnyAttribute; + } + + public void setAllowAnyAttribute(boolean allowAnyAttribute) { + this.allowAnyAttribute = allowAnyAttribute; + } + + + public Attributes(Set allowedAttributes) { + + this.allowedAttributes = allowedAttributes; + } + + public void add(String name, String value) { + + list.add(new Attribute(name, value)); + } + + + public void add(Attribute attribute) { + if (allowedAttributes != null) { + String attributeName = attribute.getName(); + boolean attributeIsAllowed = XmlUtils.containsSetTheValue(allowedAttributes, attributeName) || allowAnyAttribute; + boolean attributeIsId = attributeName.equals("id"); + boolean attributeIsClass = attributeName.equals("class"); + if (!(attributeIsAllowed || attributeIsId || attributeIsClass)) { + throw new PowerException("Attribute " + attribute.getName() + " is not allowed. Only listed attributes are allowed: " + allowedAttributes.toString()); + } + } + + list.add(attribute); + } + + public void addAll(Attribute... attribute) { + + for (Attribute a : attribute) { + add(a); + } + } + + /** + * @param name + * @return removed attribute, if the attribute was found, otherwise null + */ + public Attribute remove(String name) { + if (this.list == null) { + return null; + } + Attribute attributeToBeRemoved = null; + for (Attribute a : this.list) { + if (a.getName().equals(name)) { + attributeToBeRemoved = a; + break; + } + } + if (attributeToBeRemoved != null) { + this.getList().remove(attributeToBeRemoved); + return attributeToBeRemoved; + } else { + return null; + } + + } + + public boolean has(String name) { + if (this.list == null) { + return false; + } + for (Attribute a : this.list) { + if (a.getName().equals(name)) { + + return true; + } + } + return false; + } + + public String get(String name) { + return getAsAttribute(name).getValue(); + + } + + public Attribute getAsAttribute(String name) { + + //System.out.println("seaching attribute " + name + " this.list size is " + this.list.size()); + for(int i = 0; i toList() { + List listToReturn = new ArrayList<>(); + for (Attribute a : this.list) { + listToReturn.add(a.copy()); + } + return listToReturn; + } + + @Override + public boolean isModified() { + return false; + } + + @Override + public String getCache() { + return null; + } + + public Attributes copy() { + Set set = this.allowedAttributes == null ? null : new HashSet<>(); + if (set != null) { + for (String e : this.allowedAttributes) { + set.add(e); + } + } + + Attributes as = new Attributes(this.allowedAttributes); + + List list2 = new ArrayList<>();//todo + for (Attribute a : this.list) { + as.add(a.copy()); + } + + return as; + } +} diff --git a/power-xml/src/main/java/org/nanoboot/powerframework/xml/Buildable.java b/power-xml/src/main/java/org/nanoboot/powerframework/xml/Buildable.java new file mode 100644 index 0000000..89579b5 --- /dev/null +++ b/power-xml/src/main/java/org/nanoboot/powerframework/xml/Buildable.java @@ -0,0 +1,39 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.xml; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public interface Buildable { + public String build(); + + public boolean isModified(); + + public String getCache(); + + default boolean hasCache() { + return getCache() != null; + } +} diff --git a/power-xml/src/main/java/org/nanoboot/powerframework/xml/Constants.java b/power-xml/src/main/java/org/nanoboot/powerframework/xml/Constants.java new file mode 100644 index 0000000..7c773c5 --- /dev/null +++ b/power-xml/src/main/java/org/nanoboot/powerframework/xml/Constants.java @@ -0,0 +1,32 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.xml; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +class Constants { + + static final char NEW_LINE = '\n'; +} diff --git a/power-xml/src/main/java/org/nanoboot/powerframework/xml/Element.java b/power-xml/src/main/java/org/nanoboot/powerframework/xml/Element.java new file mode 100644 index 0000000..6efba6f --- /dev/null +++ b/power-xml/src/main/java/org/nanoboot/powerframework/xml/Element.java @@ -0,0 +1,220 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.xml; + +import org.nanoboot.powerframework.core.PowerException; +import lombok.Getter; +import lombok.Setter; + +import java.util.Set; + +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Element implements XmlTypeI, Buildable { + public static final char TAG_START = '<'; + public static final char TAG_END = '>'; + public static final char ELEMENT_END = '/'; + public static final char ELEMENT_SPACE = ' '; + + @Getter + private final String elementName; + + @Getter + private final ElementType elementType; + + @Getter + @Setter + private Elements elements = new Elements(this, this.getAllowedElements()); + + @Getter + @Setter + private Attributes attributes = new Attributes(this.getAllowedAttributes()); + + /** + * @return null if all attributes are allowed + */ + public Set getAllowedAttributes() { + return null; + } + + /** + * @return null if all attributes are allowed + */ + public Set getAllowedElements() { + return null; + } + + + public Element(String elementName, String content) { + this(elementName); + this.getNoElement().setPlainText(content); + } + public Element(String elementName, XmlTypeI... xmlTypes) { + this(elementName); + add(xmlTypes); + } + + public Element(String elementName, ElementType elementType, XmlTypeI... xmlTypes) { + this(elementName, elementType); + add(xmlTypes); + + } + + public void add(XmlTypeI... xmlTypeIs) { + for (XmlTypeI e : xmlTypeIs) { + add(e); + } + } + public void add(XmlTypeI xmlTypeIs) { + boolean isElement = xmlTypeIs instanceof Element; + boolean isAttribute = xmlTypeIs instanceof Attribute; + if (isElement) { + Element var = (Element) xmlTypeIs; + this.getElements().add(var); + return; + } + if (isAttribute) { + Attribute var = (Attribute) xmlTypeIs; + this.getAttributes().add(var); + return; + } + throw new PowerException("It is not an XmlTypeI"); + + } + /** + * Creates new paired element + * + * @param elementName + */ + public Element(String elementName) { + this(elementName, ElementType.PAIRED); + } + + /** + * Creates new element with the specified type + * + * @param elementName + * @param elementType + */ + public Element(String elementName, ElementType elementType) { + this.elementName = elementName; + this.elementType = elementType; + } + + public Element getByElementName(String elementName) { + return elements.getByElementName(elementName); + } + + public boolean isPaired() { + return this.elementType == ElementType.PAIRED; + } + + public Element setInnerText(String text) { + this.getNoElement().setPlainText(text); + return this; + } + + public NoElement getNoElement() { + NoElement ne = null; + try { + ne = (NoElement) getByElementName(NoElement.NAME); + } catch (Exception e) { + + } + + if(ne==null){ + ne = new NoElement(); + this.add(ne); + } + return ne; + + } + + public String build() { + + StringBuilder sb = new StringBuilder(); + sb.append(TAG_START); + sb.append(elementName); + if (attributes != null) { + sb.append(attributes.build()); + } + + if (isPaired()) { + sb.append(TAG_END); + + sb.append(elements.build()); + +// sb.append(Constants.NEW_LINE); + sb.append(TAG_START); + sb.append(ELEMENT_END); + sb.append(elementName); + sb.append(TAG_END); + } + if (!isPaired()) { + sb.append(ELEMENT_SPACE); + sb.append(ELEMENT_END); + sb.append(TAG_END); + } + return sb.toString(); + } + + + @Override + public boolean isModified() { + return false; + } + + @Override + public String getCache() { + return null; + } + + public String toString() { + return build(); + } + + public XmlType getXmlType() { + return XmlType.ELEMENT; + } + + public final Element copy() { + Element e = new Element(this.elementName, this.elementType); + //TODO: elements and attributes should also call a copy method. + for (Element ee : this.elements.toList()) { + e.add(ee); + } + + for (Attribute aa : this.attributes.toList()) { + e.add(aa); + } + return e; + + } + + public Elements getElements() { + return elements; + } +} diff --git a/power-xml/src/main/java/org/nanoboot/powerframework/xml/ElementType.java b/power-xml/src/main/java/org/nanoboot/powerframework/xml/ElementType.java new file mode 100644 index 0000000..33c1cab --- /dev/null +++ b/power-xml/src/main/java/org/nanoboot/powerframework/xml/ElementType.java @@ -0,0 +1,31 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.xml; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public enum ElementType { + PAIRED,NOT_PAIRED; +} diff --git a/power-xml/src/main/java/org/nanoboot/powerframework/xml/Elements.java b/power-xml/src/main/java/org/nanoboot/powerframework/xml/Elements.java new file mode 100644 index 0000000..508dae3 --- /dev/null +++ b/power-xml/src/main/java/org/nanoboot/powerframework/xml/Elements.java @@ -0,0 +1,163 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.xml; + +import org.nanoboot.powerframework.core.PowerException; +import lombok.Getter; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ + +public class Elements implements Buildable { + + @Getter + private final List list = new ArrayList<>(); + + @Getter + private final Element parent; + + private final Set allowedElements; + private boolean allowAnyElement = false; + + public boolean isAllowAnyElement() { + return allowAnyElement; + } + + public void setAllowAnyElement(boolean allowAnyElement) { + this.allowAnyElement = allowAnyElement; + } + + public Elements(Element parent, Set allowedElements) { + this.parent = parent; + this.allowedElements = allowedElements; + } + + public Elements addInnerText(String innerText) { + this.add(new NoElement(innerText)); + return this; + } + + public Elements add(Element element) { + if (!this.parent.isPaired()) { + throw new PowerException("Only paired elements can have children"); + } + if (element == null) { + throw new RuntimeException("Element is null"); + } + + if (allowedElements != null) { + if (!allowAnyElement && !XmlUtils.containsSetTheValue(allowedElements, element.getElementName())) { + throw new PowerException("Element " + element.getElementName() + " is not allowed. Only listed elements are allowed: " + allowedElements.toString()); + } + + + } + this.list.add(element); + return this; + } + + public Elements addAll(Element... elements) { + for (Element element : elements) { + + add(element); + } + return this; + } + + public void removeAll() { + this.list.clear(); + } + + + public List toList() { + List listToReturn = new ArrayList<>(); + for (Element e : this.list) { + listToReturn.add(e.copy()); + } + return listToReturn; + } + + public String build() { + if (this.list.isEmpty()) { + return ""; + } + StringBuilder sb = new StringBuilder(); + for (Element element : this.list) { + if (element == null) { + throw new RuntimeException("Element is null"); + } + sb.append(Constants.NEW_LINE); + sb.append(element.build()); + } + return sb.toString(); + } + + public Element getByElementName(String... a) { + + for (Element e : this.list) { + if (e.getElementName().equals(a[0])) { + if(a.length==1) { + return e; + }else{ + getByElementName(removeFirstField(a)); + } + + } + } + return null; + } + + public String[] removeFirstField(String[] ar){ + String[] a=new String[ar.length-1]; + for(int i=1;i loadElements(){ + List list=new ArrayList<>(); + for(Element e:this.list){ + list.addAll(e.getElements().loadElements()); + } + + return list; + } + +} diff --git a/power-xml/src/main/java/org/nanoboot/powerframework/xml/NoElement.java b/power-xml/src/main/java/org/nanoboot/powerframework/xml/NoElement.java new file mode 100644 index 0000000..5d091dc --- /dev/null +++ b/power-xml/src/main/java/org/nanoboot/powerframework/xml/NoElement.java @@ -0,0 +1,50 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.xml; + +import lombok.Getter; +import lombok.Setter; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class NoElement extends Element { + public static final String NAME = "noelement"; + + @Getter + @Setter + private String plainText; + public NoElement(){super(NAME); + } + public NoElement(String plainText){ + this(); + this.plainText=plainText; + } + public String build(){ + return this.getPlainText(); + } + public void add(XmlTypeI xmltypes) { + throw new RuntimeException("NoElement cannot have children"); + } + +} diff --git a/power-xml/src/main/java/org/nanoboot/powerframework/xml/XmlComment.java b/power-xml/src/main/java/org/nanoboot/powerframework/xml/XmlComment.java new file mode 100644 index 0000000..43ec65a --- /dev/null +++ b/power-xml/src/main/java/org/nanoboot/powerframework/xml/XmlComment.java @@ -0,0 +1,47 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.xml; + +import lombok.Getter; +import lombok.Setter; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class XmlComment extends Element { + public static final String NAME = "comment"; + + @Getter + @Setter + private String plainText; + public XmlComment(){super(NAME); + } + public XmlComment(String plainText){ + this(); + this.plainText=plainText; + } + public String build(){ + return ""; + } + +} diff --git a/power-xml/src/main/java/org/nanoboot/powerframework/xml/XmlType.java b/power-xml/src/main/java/org/nanoboot/powerframework/xml/XmlType.java new file mode 100644 index 0000000..21b8481 --- /dev/null +++ b/power-xml/src/main/java/org/nanoboot/powerframework/xml/XmlType.java @@ -0,0 +1,30 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.xml; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public enum XmlType { + ELEMENT,ATTRIBUTE; +} diff --git a/power-xml/src/main/java/org/nanoboot/powerframework/xml/XmlTypeI.java b/power-xml/src/main/java/org/nanoboot/powerframework/xml/XmlTypeI.java new file mode 100644 index 0000000..7188e53 --- /dev/null +++ b/power-xml/src/main/java/org/nanoboot/powerframework/xml/XmlTypeI.java @@ -0,0 +1,30 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.xml; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public interface XmlTypeI { + public XmlType getXmlType(); +} diff --git a/power-xml/src/main/java/org/nanoboot/powerframework/xml/XmlUtils.java b/power-xml/src/main/java/org/nanoboot/powerframework/xml/XmlUtils.java new file mode 100644 index 0000000..9bd6c0a --- /dev/null +++ b/power-xml/src/main/java/org/nanoboot/powerframework/xml/XmlUtils.java @@ -0,0 +1,52 @@ + +/////////////////////////////////////////////////////////////////////////////////////////////// +// power-framework: Java library with many purposes of usage. +// Copyright (C) 2016-2022 the original author or authors. +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; +// version 2.1 of the License only. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +/////////////////////////////////////////////////////////////////////////////////////////////// + +package org.nanoboot.powerframework.xml; + +import java.util.HashSet; +import java.util.Set; +/** + * + * + * @author Robert Vokac + * @since 0.0.0 + */ +public class XmlUtils { + private XmlUtils(){ + //instantiation not needed + } + + public static Set createNewSet(String... a){ + Set set=new HashSet<>(); + for(String e:a){ + set.add(e); + } + return set; + } + public static boolean containsSetTheValue(Set set,String string){ + for(String e:set){ + //System.err.println(e); + if(e.equals(string)){ + return true; + } + } + return false; + } +} diff --git a/power-xml/src/main/resources/.gitkeep b/power-xml/src/main/resources/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/power-xml/src/test/java/org/nanoboot/powerframework/xml/.gitkeep b/power-xml/src/test/java/org/nanoboot/powerframework/xml/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/org/nanoboot/powerframework/collections/Dictionary.java b/src/main/java/org/nanoboot/powerframework/collections/Dictionary.java deleted file mode 100644 index 561a2c0..0000000 --- a/src/main/java/org/nanoboot/powerframework/collections/Dictionary.java +++ /dev/null @@ -1,214 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.collections; - -import org.nanoboot.powerframework.PowerRuntimeException; - -/** - * Represents dictionary data structure. - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org - * @param - */ -public class Dictionary { - - private int countOfItems = 0; - - private DictionaryNode currentNode = null; - private DictionaryNode stopNode = null; - - private DictionaryNode firstNode = null; - private DictionaryNode lastNode = null; - - private DictionaryNode tempNode = null; - private DictionaryNode previousTempNode = null; - - /** - * - * @return size of this dictionary - */ - public int getCountOfItems() { - return countOfItems; - } - - /** - * - * @return result of this control - */ - public boolean isEmpty() { - return getCountOfItems() == 0; - } - - /** - * - * @param key - * @return result of this control - */ - public boolean containsValueWithKey(String key) { - DictionaryKeyIterator dictionaryKeyIterator = this.getKeyIterator(); - boolean result = false; - while (dictionaryKeyIterator.hasNext()) { - if (dictionaryKeyIterator.getNextKey().equals(key)) { - result = true; - } - } - - return result; - } - - /** - * Add new dictionary entry. - * - * @param key - * @param value - * @return - */ - public Dictionary addValue(String key, T value) { - - DictionaryNode nodeToAdd = new DictionaryNode<>(key, value); - tempNode = lastNode; - lastNode = nodeToAdd; - if (isEmpty()) { - firstNode = nodeToAdd; - } else { - tempNode.setNext(lastNode); - } - countOfItems++; - return this; - } - - /** - * Return a dictionary entry with the given key. - * - * @param key - * @return - */ - public T getValue(String key) { - moveCurrentNodeToTheNodeWithTheKey(key); - - return currentNode.getElement(); - - } - - private void moveCurrentNodeToTheNodeWithTheKey(String key) { - stopNode = stopNode == null ? firstNode : stopNode; - currentNode = stopNode; - - while (!currentNodeIsAtTheEnd(key)) { - - if (currentNode.getNext() == null) { - currentNode = firstNode; - } else { - currentNode = currentNode.getNext(); - } - } - this.stopNode = currentNode; - - if (!currentNodeHasTheKey(key)) { - throw new PowerRuntimeException("There is no element with key: " + key); - } - } - - private boolean currentNodeIsAtTheEnd(String key) { - return (currentNodeHasTheKey(key)) || (currentNodeIsBeforeStopNode()); - } - - private boolean currentNodeHasTheKey(String key) { - return currentNode.getKey().equals(key); - } - - private boolean currentNodeIsBeforeStopNode() { - if ((currentNode == lastNode) && (stopNode == firstNode)) { - return true; - } - return currentNode.getNext() == stopNode; - } - - /** - * Updates the dictionary entry with the given key to the given value. - * - * @param key - * @param value - */ - public void updateValue(String key, T value) { - moveCurrentNodeToTheNodeWithTheKey(key); - currentNode.setElement(value); - } - - /** - * Removes the dictionary entry with the given key. - * - * @param key - * @return dictionary - */ - public Dictionary removeValue(String key) { - if (isEmpty()) { - throw new PowerRuntimeException("This dictionary is empty. No dictionary entry can be removed."); - } - tempNode = firstNode; - while ((!(tempNode.getKey().equals(key))) && (tempNode.getNext() != null)) { - this.previousTempNode = tempNode; - tempNode = tempNode.getNext(); - } - if (!(tempNode.getKey().equals(key))) { - throw new PowerRuntimeException("There is no key: " + key); - } else if (tempNode == firstNode) { - firstNode = firstNode.getNext(); - } else if (tempNode == lastNode) { - lastNode = previousTempNode; - lastNode.setNext(null); - } else { - this.previousTempNode.setNext(tempNode.getNext()); - } - countOfItems--; - return this; - } - - /** - * - * @return KeyIterator for this dictionary - */ - public DictionaryKeyIterator getKeyIterator() { - return new DictionaryKeyIterator(firstNode); - } - - @Override - public String toString() { - StringBuilder stringBuilder = new StringBuilder(); - DictionaryKeyIterator dictionaryKeyIterator = this.getKeyIterator(); - String key; - T value; - String valueAsString; - final char colon = ':'; - final String newLine = "\n"; - - while (dictionaryKeyIterator.hasNext()) { - key = dictionaryKeyIterator.getNextKey(); - value = this.getValue(key); - valueAsString = value.toString(); - stringBuilder.append(key); - stringBuilder.append(colon); - stringBuilder.append(valueAsString); - stringBuilder.append(newLine); - } - return stringBuilder.toString(); - } -} diff --git a/src/main/java/org/nanoboot/powerframework/collections/DictionaryKeyIterator.java b/src/main/java/org/nanoboot/powerframework/collections/DictionaryKeyIterator.java deleted file mode 100644 index 3db1ac3..0000000 --- a/src/main/java/org/nanoboot/powerframework/collections/DictionaryKeyIterator.java +++ /dev/null @@ -1,87 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.collections; - -import org.nanoboot.powerframework.PowerRuntimeException; - -/** - * Is used to iterate entries through dictionary. - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org - */ -public class DictionaryKeyIterator { - - private final DictionaryNode firstNode; - private DictionaryNode currentNode; - private boolean currentNodeIsNotFirst = false; - - DictionaryKeyIterator(DictionaryNode value) { - this.firstNode = value; - this.reset(); - } - - /** - * - * @return next key - */ - public String getNextKey() { - String key; - if (firstNode == null) { - throw new PowerRuntimeException("Dictionary is empty. There is no key."); - } - if ((currentNode == firstNode) && (!this.currentNodeIsNotFirst)) { - key = currentNode.getKey(); - this.currentNodeIsNotFirst = true; - } else { - if (!hasNext()) { - throw new PowerRuntimeException("There is no next key."); - } - this.currentNode = this.currentNode.getNext(); - key = currentNode.getKey(); - } - return key; - } - - /** - * - * @return true if there is a next key, otherwise false - */ - public boolean hasNext() { - if (this.firstNode == null) { - return false; - } - if ((firstNode.getNext() == null) && (!currentNodeIsNotFirst)) { - return true; - } - if ((firstNode.getNext() == null) && (currentNodeIsNotFirst)) { - return false; - } - return this.currentNode.getNext() != null; - } - - /** - * Moves the current key to the first. - */ - public void reset() { - this.currentNode = this.firstNode; - currentNodeIsNotFirst = false; - } -} diff --git a/src/main/java/org/nanoboot/powerframework/collections/Queue.java b/src/main/java/org/nanoboot/powerframework/collections/Queue.java deleted file mode 100644 index 4d0de9f..0000000 --- a/src/main/java/org/nanoboot/powerframework/collections/Queue.java +++ /dev/null @@ -1,107 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.collections; - -import org.nanoboot.powerframework.PowerRuntimeException; - -/** - * Represents Queue- linear data structure. - * - * @author Robert Vokac robertvokac@nanoboot.orgt Vokáč robertvokac@nanoboot.org - * @param object - */ -public class Queue { - - private int total; - - private Node first; - private Node last; - - private class Node { - - private T element; - private Node next; - } - - /** - * - * @return size of this queue - */ - public int getCountOfItems() { - return this.total; - } - - /** - * - * @return true if this queue is empty, otherwise false - */ - public boolean isEmpty() { - return this.getCountOfItems() == 0; - } - - /** - * Enqueues new element. - * - * @param element - * @return new element - */ - public Queue enqueue(T element) { - Node current = last; - last = new Node(); - last.element = element; - - if (total++ == 0) { - first = last; - } else { - current.next = last; - } - - return this; - } - - /** - * Dequeues element. - * - * @return removed element - */ - public T dequeue() { - if (total == 0) { - throw new PowerRuntimeException("No such element"); - } - T ele = first.element; - first = first.next; - if (--total == 0) { - last = null; - } - return ele; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - Node tmp = first; - while (tmp != null) { - sb.append(tmp.element).append(", "); - tmp = tmp.next; - } - return sb.toString(); - } -} diff --git a/src/main/java/org/nanoboot/powerframework/collections/Stack.java b/src/main/java/org/nanoboot/powerframework/collections/Stack.java deleted file mode 100644 index bdfce77..0000000 --- a/src/main/java/org/nanoboot/powerframework/collections/Stack.java +++ /dev/null @@ -1,141 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.collections; - -import java.util.Iterator; -import java.util.NoSuchElementException; -import org.nanoboot.powerframework.PowerRuntimeException; - -/** - * Represents Stack- linear data structure. - * - * @author Robert Vokac robertvokac@nanoboot.orgt Vokáč robertvokac@nanoboot.org - * @param object - */ -public class Stack implements Iterable { - - private int total = 0; - - private Node first; - - @Override - public Iterator iterator() { - return new StackIterator(); - } - - private class Node { - - private T element; - private Node next; - } - - private class StackIterator implements Iterator { - - @Override - public boolean hasNext() { - return !isEmpty(); - } - - @Override - public T next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - return pop(); - } - } - - /** - * - * @return size of this stack - */ - public int getCountOfItems() { - return this.total; - } - - /** - * - * @return true if this stack is empty, otherwise false - */ - public boolean isEmpty() { - return this.getCountOfItems() == 0; - } - - /** - * Pushes new element. - * - * @param element - * @return pushed element - */ - public Stack push(T element) { - Node current = first; - first = new Node(); - first.element = element; - first.next = current; - total++; - return this; - } - - /** - * Pops element. - * - * @return popped element - */ - public T pop() { - if (first == null) { - throw new PowerRuntimeException("No such element"); - } - T element = first.element; - first = first.next; - total--; - return element; - } - - /** - * - * @return the top element of this stack without removing this element - */ - public T peek() { - if (first == null) { - throw new PowerRuntimeException("No such element"); - } - return first.element; - } -/** - * Deletes all items of this stack. - */ - public void clear() { - total = 0; - first = null; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - Node tmp = first; - while (tmp != null) { - sb.append(tmp.element).append(", "); - tmp = tmp.next; - } - return sb.toString(); - } - -} diff --git a/src/main/java/org/nanoboot/powerframework/database/DatabaseConnection.java b/src/main/java/org/nanoboot/powerframework/database/DatabaseConnection.java deleted file mode 100644 index f67e4bc..0000000 --- a/src/main/java/org/nanoboot/powerframework/database/DatabaseConnection.java +++ /dev/null @@ -1,351 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.database; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.nanoboot.powerframework.PowerRuntimeException; -import org.nanoboot.powerframework.json.*; - -/** - * Represents connection to a database. - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org - */ -public class DatabaseConnection { - - private Connection connection = null; - private Statement statement = null; - private final String databaseName; - - private final String jdbcUrl; - - DatabaseConnection(String databaseName) { - this.databaseName = databaseName; - StringBuilder stringBuilder = new StringBuilder().append("jdbc:sqlite:"); - if (databaseName != "") { - stringBuilder.append(databaseName).append(".sqlite").toString(); - } - this.jdbcUrl = stringBuilder.toString(); - } - - /** - * - * @return name of the database of this database connection - */ - public String getDatabaseName() { - return databaseName; - } - - private void setConnection() { - try { - Class.forName("org.sqlite.JDBC"); - connection = DriverManager.getConnection(jdbcUrl); - statement = connection.createStatement(); - statement.execute("PRAGMA foreign_keys = ON;"); - } catch (Exception e) { - Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, e); - } - } - - /** - * Executes sql command, which returns no result. - * - * @param command - * @return last inserted row id - */ - public int execute(String command) { - int lastInsertedRowId = 0; - setConnection(); - ResultSet resultSet = null; - try { - statement.executeUpdate(command); - resultSet = statement.executeQuery("SELECT last_insert_rowid() AS LASTINSERTEDROWID;"); - resultSet.next(); - lastInsertedRowId = resultSet.getInt(1); - resultSet.close(); - connection.close(); - } catch (Exception e) { - Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, e); - } finally { - if (resultSet != null) { - try { - resultSet.close(); - } catch (SQLException ex) { - Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex); - } - } - - } - return lastInsertedRowId; - } - - /** - * Executes sql commands from the command queue. - * - * @param commandQueue - */ - public void executeMoreCommands(SqlCommandQueue commandQueue) { - setConnection(); - - try { - connection.setAutoCommit(false); - while (commandQueue.isThereANextCommand()) { - String command = commandQueue.loadNextCommand(); - statement.executeUpdate(command); - - } - - //No changes has been made in the database yet, so now we will commit - //the changes. - connection.commit(); - } catch (SQLException ex) { - Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex); - try { - //An error occured so we rollback the changes. - connection.rollback(); - } catch (SQLException ex1) { - Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex1); - throw new PowerRuntimeException("Fatal error happened. I was not able to rollback"); - } - } finally { - try { - if (statement != null) { - statement.close(); - connection.close(); - } - } catch (SQLException ex) { - Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex); - } - } - } - - /** - * Executes sql commands from the given String, which is split by ; - * character. - * - * @param commands - */ - public void executeMoreCommands(String commands) { - SqlCommandQueue commandQueue = new SqlCommandQueue(); - String[] commandsArray = commands.split(";"); - for (String part : commandsArray) { - commandQueue.add(part); - } - this.executeMoreCommands(commandQueue); - } - - /** - * Executes sql command, which returns result. - * - * @param command - * @return - */ - public ResultOfSqlQuery executeAndReturn(String command) { - JsonObject table = new JsonObject(); - - JsonArray columns = new JsonArray(); - JsonArray rows = new JsonArray(); - - table.addString("query", command); - table.addArray("columns", columns); - table.addArray("rows", rows); - - setConnection(); - ResultSet resultSet = null; - try { - resultSet = statement.executeQuery(command); - - ResultSetMetaData rsmd = resultSet.getMetaData(); - int columnCount = rsmd.getColumnCount(); - for (int i = 1; i <= columnCount; i++) { - String columnName = rsmd.getColumnName(i); - columns.addString(columnName); - } - - while (resultSet.next()) { - JsonArray row = new JsonArray(); - for (int i = 0; i < columns.getCountOfItems(); i++) { - String columnName = columns.getString(i); - String value = resultSet.getString(columnName); - row.addString(value); - } - rows.addArray(row); - } - - connection.close(); - } catch (Exception e) { - Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, e); - } finally { - closeConnectionAndResultSet(resultSet); - } - return new ResultOfSqlQuery(table); - } - - private void closeConnectionAndResultSet(ResultSet resultSet) { - try { - if (resultSet != null) { - resultSet.close(); - } - if (!connection.isClosed()) { - connection.close(); - } - } catch (Exception e) { - Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, e); - } - } - - /** - * Updates value. - * - * @param tableName - * @param id - * @param columnName - * @param newValue - */ - public void updateValue(String tableName, int id, String columnName, String newValue) { - String string - = "UPDATE " + tableName + " SET " + columnName + " = '" + newValue + "' WHERE ID = " + id; - this.execute(string); - } - - /** - * Updates value. - * - * @param tableName - * @param id - * @param columnName - * @param newValue - */ - public void updateValue(String tableName, int id, String columnName, int newValue) { - String string - = "UPDATE " + tableName + " SET " + columnName + " = " + newValue + " WHERE ID = " + id; - this.execute(string); - } - - /** - * - * @param tableName - * @param id - * @return row with the given id from the given table as a json object - */ - public JsonObject getRow(String tableName, int id) { - JsonObject row = new JsonObject(); - - JsonArray columns = new JsonArray(); - - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("select * from "); - stringBuilder.append(tableName); - stringBuilder.append(" where id="); - stringBuilder.append(id); - - String command = stringBuilder.toString(); - - setConnection(); - ResultSet resultSet = null; - try { - resultSet = statement.executeQuery(command); - - ResultSetMetaData rsmd = resultSet.getMetaData(); - int columnCount = rsmd.getColumnCount(); - for (int i = 1; i <= columnCount; i++) { - String columnName = rsmd.getColumnName(i); - columns.addString(columnName); - } - - if (!resultSet.next()) { - throw new PowerRuntimeException("There is no row with id " + id + " in table " + tableName); - } - - for (int i = 0; i < columns.getCountOfItems(); i++) { - String columnName = columns.getString(i); - String value = resultSet.getString(columnName); - row.addString(columnName, value); - } - - connection.close(); - } catch (Exception e) { - Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, e); - throw new IllegalStateException(); - } finally { - - try { - if (resultSet != null) { - resultSet.close(); - } - if (!connection.isClosed()) { - connection.close(); - } - } catch (Exception e) { - Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, e); - } - } - return row; - } - - /** - * - * @param tableName - * @return true, if the table is empty, otherwise false. - */ - public boolean isTableEmpty(String tableName) { - ResultOfSqlQuery resultOfSqlQuery = this.executeAndReturn("SELECT * FROM " + tableName); - return resultOfSqlQuery.isEmpty(); - } - - /** - * - * @param table table name - * @param column column name - * @param whereClause for example: year_of_birth>1995 - * @return String value from a table and first row - */ - public String getString(String table, String column, String whereClause) { - String command = "SELECT " + column + " FROM " + table + " WHERE " + whereClause; - String value = null; - - setConnection(); - ResultSet resultSet = null; - try { - resultSet = statement.executeQuery(command); - - if (resultSet.next()) { - value = resultSet.getString(column); - } - connection.close(); - } catch (Exception e) { - Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, e); - } finally { - - closeConnectionAndResultSet(resultSet); - - } - - return value; - } -} diff --git a/src/main/java/org/nanoboot/powerframework/datetime/DateTime.java b/src/main/java/org/nanoboot/powerframework/datetime/DateTime.java deleted file mode 100644 index 7f8fdff..0000000 --- a/src/main/java/org/nanoboot/powerframework/datetime/DateTime.java +++ /dev/null @@ -1,189 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.datetime; - -import java.text.SimpleDateFormat; - -/** - * This class represents date and time and is immutable. - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org - */ -public abstract class DateTime { - - /** - * - */ - protected static class SimpleDateTimeFormatByTimeZone extends SimpleDateFormat { - - /** - * - * @param timeZone - * @param formatText - */ - protected SimpleDateTimeFormatByTimeZone(TimeZone timeZone, String formatText) { - super(formatText); - setTimeZone(java.util.TimeZone.getTimeZone(timeZone.toString())); - } - } - - private final LocalDate date; - private final LocalTime time; - - /** - * Constructor - * - * Sets all values. - * - * @param localDate Represents a date. - * @param localTime Represents a time. - */ - DateTime(LocalDate localDate, LocalTime localTime) { - this.date = localDate; - this.time = localTime; - } - - /** - * Constructor - * - * Sets all values. - * - * @param year Represents a year. - * @param month Represents a month. - * @param day Represents a day. - * @param hour24Format Represents an hour. - * @param minute Represents a minute - * @param second Represents a second. - * @param millisecond Represents a millisecond. - */ - DateTime(int year, int month, int day, int hour24Format, int minute, int second, int millisecond) { - this.date = new LocalDate(year, month, day); - this.time = new LocalTime(hour24Format, minute, second, millisecond); - } - - /** - * Constructor - * - * Sets all values from another object. - * - * @param dateTime - */ - protected DateTime(DateTime dateTime) { - int year = dateTime.getYear(); - int month = dateTime.getMonth(); - int day = dateTime.getDay(); - date = new LocalDate(year, month, day); - - int hour24Format = dateTime.getHour(); - int minute = dateTime.getMinute(); - int second = dateTime.getSecond(); - int millisecond = dateTime.getMillisecond(); - time = new LocalTime(hour24Format, minute, second, millisecond); - } - - /** - * Constructor - * - * Sets all values from String - * - * @param dateTimeInString This String has following format: 2016-12-31 - * 24:45:14:453 yyyy-MM-dd HH:mm:ss:SSS - */ - public DateTime(String dateTimeInString) { - int year = Integer.parseInt(dateTimeInString.substring(0, 4)); - int month = Integer.parseInt(dateTimeInString.substring(5, 7)); - int day = Integer.parseInt(dateTimeInString.substring(8, 10)); - date = new LocalDate(year, month, day); - - int hour = Integer.parseInt(dateTimeInString.substring(11, 13)); - int minute = Integer.parseInt(dateTimeInString.substring(14, 16)); - int second = Integer.parseInt(dateTimeInString.substring(17, 19)); - int millisecond = Integer.parseInt(dateTimeInString.substring(20, 23)); - time = new LocalTime(hour, minute, second, millisecond); - } - - /** - * - * @return year - */ - public int getYear() { - return this.date.getYear(); - } - - /** - * - * @return month - */ - public int getMonth() { - return this.date.getMonth(); - } - - /** - * - * @return day - */ - public int getDay() { - return this.date.getDay(); - } - - /** - * - * @return hour - */ - public int getHour() { - return this.time.getHour(); - } - - /** - * - * @return minute - */ - public int getMinute() { - return this.time.getMinute(); - } - - /** - * - * @return second - */ - public int getSecond() { - return this.time.getSecond(); - } - - /** - * - * @return millisecond - */ - public int getMillisecond() { - return this.time.getMillisecond(); - } - - @Override - public String toString() { - StringBuilder stringBuffer = new StringBuilder(); - stringBuffer.append(this.date.toString()); - stringBuffer.append(" "); - stringBuffer.append(this.time.toString()); - - return stringBuffer.toString(); - } - -} diff --git a/src/main/java/org/nanoboot/powerframework/datetime/Duration.java b/src/main/java/org/nanoboot/powerframework/datetime/Duration.java deleted file mode 100644 index 4d3e0a6..0000000 --- a/src/main/java/org/nanoboot/powerframework/datetime/Duration.java +++ /dev/null @@ -1,626 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.datetime; - -import org.nanoboot.powerframework.PowerRuntimeException; -import org.nanoboot.powerframework.pseudorandom.PseudoRandomGenerator; - -/** - * Is used to do arithmetics with Date and Time. - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org - */ -public class Duration { - - private static final int MILLISECONDSPERSECOND = 1000; - private static final int SECONDSPERMINUTE = 60; - private static final int MILLISECONDSPERMINUTE = MILLISECONDSPERSECOND * SECONDSPERMINUTE; - private static final int MINUTESPERHOUR = 60; - private static final int MILLISECONDSPERHOUR = MILLISECONDSPERMINUTE * MINUTESPERHOUR; - private static final int HOURSPERDAY = 24; - private static final int MILLISECONDSPERDAY = MILLISECONDSPERHOUR * HOURSPERDAY; - private static final String PLUS = "+"; - private static final String MINUS = "-"; - private static final String COLON = ":"; - - private final long countOfTotalMilliseconds; - private final int days; - private final int hours; - private final int minutes; - private final int seconds; - private final int milliseconds; - private final boolean positive; - - /** - * Constructor - * - * Creates new Duration from count of milliseconds. - * - * @param countOfMilliseconds - */ - public Duration(long countOfMilliseconds) { - if (countOfMilliseconds >= 0) { - positive = true; - } else { - positive = false; - } - this.countOfTotalMilliseconds = Math.abs(countOfMilliseconds); - - this.days = (int) Math.floor(this.toTotalDays()); - this.hours = (int) Math.floor(this.toTotalHours()) - (days * HOURSPERDAY); - this.minutes = (int) Math.floor(this.toTotalMinutes()) - (days * HOURSPERDAY * MINUTESPERHOUR) - (hours * MINUTESPERHOUR); - this.seconds = (int) Math.floor(this.toTotalSeconds()) - (days * HOURSPERDAY * MINUTESPERHOUR * SECONDSPERMINUTE) - (hours * MINUTESPERHOUR * SECONDSPERMINUTE) - (minutes * SECONDSPERMINUTE); - this.milliseconds = (int) this.toTotalMilliseconds() - (days * HOURSPERDAY * MINUTESPERHOUR * SECONDSPERMINUTE * MILLISECONDSPERSECOND) - (hours * MINUTESPERHOUR * SECONDSPERMINUTE * MILLISECONDSPERSECOND) - (minutes * SECONDSPERMINUTE * MILLISECONDSPERSECOND) - (seconds * MILLISECONDSPERSECOND); - - } - - /** - * Constructor - * - * Creates new Duration from the given values. - * - * @param days - * @param hours - * @param minutes - * @param seconds - * @param milliseconds - */ - public Duration(long days, int hours, int minutes, int seconds, int milliseconds) { - this( - true, days, hours, minutes, seconds, milliseconds - ); - } - - /** - * Constructor - * - * Creates new Duration from the given values. - * - * @param positive - * @param days - * @param hours - * @param minutes - * @param seconds - * @param milliseconds - */ - public Duration(boolean positive, long days, int hours, int minutes, int seconds, int milliseconds) { - this( - (positive ? 1 : (-1)) - * (convertDaysToMilliseconds(days) - + convertHoursToMilliseconds(hours) - + convertMinutesToMilliseconds(minutes) - + convertSecondsToMilliseconds(seconds) - + milliseconds) - ); - TimeUnitsValidator.checkInputValuesForTimeAndIfThereIsAnInvalidOneThrowException(hours, minutes, seconds, milliseconds); - } - - /** - * Constructor - * - * Creates new Duration from the String. - * - * @param string - */ - public Duration(String string) { - String[] splitString = string.split("\\:+"); - if (splitString.length != 5) { - throw new PowerRuntimeException("Input String has wrong format."); - } - try { - this.days = Integer.parseInt(splitString[0]); - this.hours = Integer.parseInt(splitString[1]); - this.minutes = Integer.parseInt(splitString[2]); - this.seconds = Integer.parseInt(splitString[3]); - this.milliseconds = Integer.parseInt(splitString[4]); - this.countOfTotalMilliseconds = convertDaysToMilliseconds(days) - + convertHoursToMilliseconds(hours) - + convertMinutesToMilliseconds(minutes) - + convertSecondsToMilliseconds(seconds) - + milliseconds; - this.positive = string.charAt(0) == '+'; - } catch (Exception e) {//NOSONAR - throw new PowerRuntimeException("Input String has wrong format."); - } - TimeUnitsValidator.checkInputValuesForTimeAndIfThereIsAnInvalidOneThrowException(hours, minutes, seconds, milliseconds); - } - - /** - * - * @return random duration - */ - public static Duration createRandomDuration() { - Duration duration; - PseudoRandomGenerator pseudoRandomNumberGenerator = PseudoRandomGenerator.getInstance(); - long days = pseudoRandomNumberGenerator.getInt(0, 6000); - int hours = pseudoRandomNumberGenerator.getInt(0, 23); - int minutes = pseudoRandomNumberGenerator.getInt(0, 59); - int seconds = pseudoRandomNumberGenerator.getInt(0, 59); - int milliseconds = pseudoRandomNumberGenerator.getInt(0, 999); - duration = new Duration(days, hours, minutes, seconds, milliseconds); - return duration; - } - - /** - * Creates new Duration from startUniversalDateTime minus - * endUniversalDateTime. - * - * @param startUniversalDateTime - * @param endUniversalDateTime - * @return new instance of Duration - */ - public static Duration between(UniversalDateTime startUniversalDateTime, UniversalDateTime endUniversalDateTime) { - java.time.LocalDateTime javaStartLocalDateTime = startUniversalDateTime.toLocalDateTime().toJavaLocalDateTime(); - java.time.LocalDateTime javaEndLocalDateTime = endUniversalDateTime.toLocalDateTime().toJavaLocalDateTime(); - java.time.Duration javaDuration = java.time.Duration.between(javaStartLocalDateTime, javaEndLocalDateTime); - return new Duration(javaDuration.toMillis()); - - } - - /** - * Creates new Duration from startZonedDateTime minus endZonedDateTime. - * - * @param startZonedDateTime - * @param endZonedDateTime - * @return new instance of Duration - */ - public static Duration between(ZonedDateTime startZonedDateTime, ZonedDateTime endZonedDateTime) { - return between(startZonedDateTime.toUniversalDateTime(), endZonedDateTime.toUniversalDateTime()); - } - - private static int getMillisecondsPerDay() { - return MILLISECONDSPERDAY; - } - - private static long convertDaysToMilliseconds(long days) { - return days * getMillisecondsPerDay(); - } - - /** - * - * @param days - * @return an instance of Duration class with the given count of days - */ - public static Duration ofDays(long days) { - return new Duration(convertDaysToMilliseconds(days)); - } - - private static int getMillisecondsPerHour() { - return MILLISECONDSPERHOUR; - } - - private static long convertHoursToMilliseconds(long hours) { - return hours * getMillisecondsPerHour(); - } - - /** - * - * @param hours - * @return an instance of Duration class with the given count of hours - */ - public static Duration ofHours(long hours) { - return new Duration(convertHoursToMilliseconds(hours)); - } - - private static int getMillisecondsPerMinute() { - return MILLISECONDSPERMINUTE; - } - - private static long convertMinutesToMilliseconds(long minutes) { - return minutes * getMillisecondsPerMinute(); - } - - /** - * - * @param minutes - * @return an instance of Duration class with the given count of minutes - */ - public static Duration ofMinutes(long minutes) { - return new Duration(convertMinutesToMilliseconds(minutes)); - } - - private static int getMillisecondsPerSecond() { - return MILLISECONDSPERSECOND; - } - - private static long convertSecondsToMilliseconds(long seconds) { - return seconds * getMillisecondsPerSecond(); - } - - /** - * - * @param seconds - * @return an instance of Duration class with the given count of seconds - */ - public static Duration ofSeconds(long seconds) { - return new Duration(convertSecondsToMilliseconds(seconds)); - } - - /** - * - * @param milliseconds - * @return an instance of Duration class with the given count of - * milliseconds - */ - public static Duration ofMilliseconds(long milliseconds) { - return new Duration(milliseconds); - } - - /** - * - * @param universalDateTime - * @param duration - * @return add to universalDateTime duration and return result - */ - public static UniversalDateTime fromUniversalDateTimePlusDurationCreateNewUniversalDateTime(UniversalDateTime universalDateTime, Duration duration) { - return addToUniversalDateTimeDuration(universalDateTime, duration, true); - } - - /** - * - * @param universalDateTime - * @param duration - * @return subtract from universalDateTime duration and return result - */ - public static UniversalDateTime fromUniversalDateTimeMinusDurationCreateNewUniversalDateTime(UniversalDateTime universalDateTime, Duration duration) { - return addToUniversalDateTimeDuration(universalDateTime, duration, false); - } - - private static UniversalDateTime addToUniversalDateTimeDuration(UniversalDateTime universalDateTime, Duration duration, boolean trueForAddingFalseForSubtracting) { - java.time.LocalDateTime javaLocalDateTime = universalDateTime.toLocalDateTime().toJavaLocalDateTime(); - java.time.Duration javaDuration = duration.toJavaDuration(); - java.time.LocalDateTime newJavaLocalDateTime; - if (trueForAddingFalseForSubtracting) { - newJavaLocalDateTime = javaLocalDateTime.plus(javaDuration); - } else { - newJavaLocalDateTime = javaLocalDateTime.minus(javaDuration); - } - - int year = newJavaLocalDateTime.getYear(); - int day = newJavaLocalDateTime.getDayOfMonth(); - int month = newJavaLocalDateTime.getMonth().getValue(); - int hour = newJavaLocalDateTime.getHour(); - int minute = newJavaLocalDateTime.getMinute(); - int second = newJavaLocalDateTime.getSecond(); - final int nanosecondspermillisecond; - nanosecondspermillisecond = 1000000; - int millisecond = newJavaLocalDateTime.getNano() / nanosecondspermillisecond; - - return new UniversalDateTime(year, month, day, hour, minute, second, millisecond); - } - - /** - * - * @param zonedDateTime - * @param duration - * @return add to zonedDateTime duration and return result - */ - public static ZonedDateTime fromZonedDateTimePlusDurationCreateNewZonedDateTime(ZonedDateTime zonedDateTime, Duration duration) { - return addToZonedDateTimeDuration(zonedDateTime, duration, true); - } - - /** - * - * @param zonedDateTime - * @param duration - * @return subtract from zonedDateTime duration and return result - */ - public static ZonedDateTime fromZonedDateTimeMinusDurationCreateNewZonedDateTime(ZonedDateTime zonedDateTime, Duration duration) { - return addToZonedDateTimeDuration(zonedDateTime, duration, false); - } - - private static ZonedDateTime addToZonedDateTimeDuration(ZonedDateTime zonedDateTime, Duration duration, boolean trueForAddingFalseForSubtracting) { - UniversalDateTime universalDateTime = zonedDateTime.toUniversalDateTime(); - UniversalDateTime newUniversalDateTime; - if (trueForAddingFalseForSubtracting) { - newUniversalDateTime = fromUniversalDateTimePlusDurationCreateNewUniversalDateTime(universalDateTime, duration); - } else { - newUniversalDateTime = fromUniversalDateTimeMinusDurationCreateNewUniversalDateTime(universalDateTime, duration); - } - - return new ZonedDateTime(newUniversalDateTime).toZonedDateTime(zonedDateTime.getTimeZone()); - } - - /** - * - * @return count of days - * - *

    Example
    - *
    - * Duration duration=new Duration(6,19,46,12,754);
    - * long days=duration.getDays();
    - *
    - * days is 6 - */ - public long getDays() { - return days; - } - - /** - * - * @return count of hours - * - *

    Example
    - *
    - * Duration duration=new Duration(6,19,46,12,754);
    - * long hours=duration.getHours();
    - *
    - * hours is 19 - */ - public int getHours() { - return hours; - } - - /** - * - * @return count of minutes - * - *

    Example
    - *
    - * Duration duration=new Duration(6,19,46,12,754);
    - * long minutes=duration.getMinutes();
    - *
    - * minutes is 46 - */ - public int getMinutes() { - return minutes; - } - - /** - * - * @return count of seconds - * - *

    Example
    - *
    - * Duration duration=new Duration(6,19,46,12,754);
    - * long seconds=duration.getSeconds();
    - *
    - * seconds is 12 - */ - public int getSeconds() { - return seconds; - } - - /** - * - * @return count of milliseconds - * - *

    Example
    - *
    - * Duration duration=new Duration(6,19,46,12,754);
    - * long milliseconds=duration.Milliseconds();
    - *
    - * milliseconds is 754 - */ - public int getMilliseconds() { - return milliseconds; - } - - /** - * - * @return result of this control - */ - public boolean isPositive() { - return this.positive; - } - - /** - * - * @return new Duration instance created from negated this object - */ - public Duration negated() { - return new Duration(this.toTotalMilliseconds() * (-1)); - } - - /** - * - * @return new Duration instance created from this object, if this object is - * negative, returned Duration is not negative - */ - public Duration abs() { - long absCountOfTotalMilliseconds; - absCountOfTotalMilliseconds = this.countOfTotalMilliseconds >= 0 ? countOfTotalMilliseconds : (countOfTotalMilliseconds * (-1)); - return new Duration(absCountOfTotalMilliseconds); - } - - /** - * - * @param durationToAdd - * @return from this object plus the given durationToAdd new Duration - */ - public Duration plusDuration(Duration durationToAdd) { - return new Duration(this.toTotalMilliseconds() + durationToAdd.toTotalMilliseconds()); - } - - /** - * - * @param daysToAdd - * @return from this object plus the given daysToAdd new Duration - */ - public Duration plusDays(long daysToAdd) { - return this.plusMilliseconds(Duration.convertDaysToMilliseconds(daysToAdd)); - } - - /** - * - * @param hoursToAdd - * @return from this object plus the given hoursToAdd new Duration - */ - public Duration plusHours(long hoursToAdd) { - return this.plusMilliseconds(Duration.convertHoursToMilliseconds(hoursToAdd)); - } - - /** - * - * @param minutesToAdd - * @return from this object plus the given minutesToAdd new Duration - */ - public Duration plusMinutes(long minutesToAdd) { - return this.plusMilliseconds(Duration.convertMinutesToMilliseconds(minutesToAdd)); - } - - /** - * - * @param secondsToAdd - * @return from this object plus the given secondsToAdd new Duration - */ - public Duration plusSeconds(long secondsToAdd) { - return this.plusMilliseconds(Duration.convertSecondsToMilliseconds(secondsToAdd)); - } - - /** - * - * @param millisecondsToAdd - * @return from this object plus the given millisecondsToAdd new Duration - */ - public Duration plusMilliseconds(long millisecondsToAdd) { - return new Duration(this.toTotalMilliseconds() + millisecondsToAdd); - } - - /** - * - * @param durationToSubtract - * @return from this object minus the given durationToSubtract new Duration - */ - public Duration minusDuration(Duration durationToSubtract) { - return new Duration(this.toTotalMilliseconds() - durationToSubtract.toTotalMilliseconds()); - } - - /** - * - * @param daysToSubtract - * @return from this object minus the given daysToSubtract new Duration - */ - public Duration minusDays(long daysToSubtract) { - return this.minusMilliseconds(Duration.convertDaysToMilliseconds(daysToSubtract)); - } - - /** - * - * @param hoursToSubtract - * @return from this object minus the given hoursToSubtract new Duration - */ - public Duration minusHours(long hoursToSubtract) { - return this.minusMilliseconds(Duration.convertHoursToMilliseconds(hoursToSubtract)); - } - - /** - * - * @param minutesToSubtract - * @return from this object minus the given minutesToSubtract new Duration - */ - public Duration minusMinutes(long minutesToSubtract) { - return this.minusMilliseconds(Duration.convertMinutesToMilliseconds(minutesToSubtract)); - } - - /** - * - * @param secondsToSubtract - * @return from this object minus the given secondsToSubtract new Duration - */ - public Duration minusSeconds(long secondsToSubtract) { - return this.minusMilliseconds(Duration.convertSecondsToMilliseconds(secondsToSubtract)); - } - - /** - * - * @param millisecondsToSubtract - * @return from this object minus the given millisecondsToSubtract new - * Duration - */ - public Duration minusMilliseconds(long millisecondsToSubtract) { - return new Duration(this.toTotalMilliseconds() - millisecondsToSubtract); - } - - /** - * - * @return representation of this object in days - */ - public double toTotalDays() { - return countOfTotalMilliseconds / getMillisecondsPerDay(); - } - - /** - * - * @return representation of this object in hours - */ - public double toTotalHours() { - return countOfTotalMilliseconds / getMillisecondsPerHour(); - } - - /** - * - * @return representation of this object in minutes - */ - public double toTotalMinutes() { - return countOfTotalMilliseconds / getMillisecondsPerMinute(); - } - - /** - * - * @return representation of this object in seconds - */ - public double toTotalSeconds() { - return countOfTotalMilliseconds / getMillisecondsPerSecond(); - } - - /** - * - * @return representation of this object in milliseconds - */ - public long toTotalMilliseconds() { - return countOfTotalMilliseconds; - } - - /** - * - * @return java.time.duration representation of this object - */ - java.time.Duration toJavaDuration() { - java.time.Duration javaDuration = java.time.Duration.ofMillis(this.toTotalMilliseconds()); - if (!this.isPositive()) { - javaDuration.negated(); - } - return javaDuration; - } - - @Override - public String toString() { - StringBuilder stringBuilder; - stringBuilder = new StringBuilder(); - if (this.isPositive()) { - stringBuilder.append(PLUS); - } else { - stringBuilder.append(MINUS); - } - stringBuilder.append(this.getDays()); - stringBuilder.append(COLON); - stringBuilder.append(this.getHours()); - stringBuilder.append(COLON); - stringBuilder.append(this.getMinutes()); - stringBuilder.append(COLON); - stringBuilder.append(this.getSeconds()); - stringBuilder.append(COLON); - stringBuilder.append(this.getMilliseconds()); - return stringBuilder.toString(); - - } -} diff --git a/src/main/java/org/nanoboot/powerframework/datetime/LocalDateTime.java b/src/main/java/org/nanoboot/powerframework/datetime/LocalDateTime.java deleted file mode 100644 index 73432d7..0000000 --- a/src/main/java/org/nanoboot/powerframework/datetime/LocalDateTime.java +++ /dev/null @@ -1,112 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.datetime; - -import java.time.format.DateTimeFormatter; - -/** - * This class stores date time without time zone information. - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org - */ -public final class LocalDateTime extends DateTime { - - /** - * Constructor - * - * Creates new LocalDateTime from String. - * - * @param dateTimeInString - */ - protected LocalDateTime(String dateTimeInString) { - super(dateTimeInString); - } - - /** - * Constructor - * - * Creates new LocalDateTime with these parameters. - * - * @param year - * @param month - * @param day - * @param hour24Format - * @param minute - * @param second - * @param millisecond - */ - public LocalDateTime(int year, int month, int day, int hour24Format, int minute, int second, int millisecond) { - super(year, month, day, hour24Format, minute, second, millisecond); - } - - /** - * Constructor - * - * Creates new LocalDateTime from UniversalDateTime. - * - * @param universalDateTime - */ - public LocalDateTime(UniversalDateTime universalDateTime) { - super(universalDateTime); - } - - /** - * Constructor - * - * Creates new LocalDateTime from ZonedDateTime. - * - * @param zonedDateTime - */ - public LocalDateTime(ZonedDateTime zonedDateTime) { - super(zonedDateTime); - } - - /** - * - * - * @return a UniversalDateTime instance from this object - */ - public UniversalDateTime toUniversalDateTime() { - return new UniversalDateTime(this); - } - - /** - * - * - * @param timeZone time zone of new created ZonedDateTime - * @return a ZonedDateTime instance from this object - */ - public ZonedDateTime toZonedDateTime(org.nanoboot.powerframework.datetime.TimeZone timeZone) { - return new ZonedDateTime(this, timeZone); - } - - /** - * - * - * @return a java.time.LocalDateTime instance from this object - */ - java.time.LocalDateTime toJavaLocalDateTime() { - DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS"); - String stringRepresentationOfThisObject = this.toString(); - return java.time.LocalDateTime.parse(stringRepresentationOfThisObject, dateTimeFormatter); - } - -} diff --git a/src/main/java/org/nanoboot/powerframework/datetime/LocalTime.java b/src/main/java/org/nanoboot/powerframework/datetime/LocalTime.java deleted file mode 100644 index de58f35..0000000 --- a/src/main/java/org/nanoboot/powerframework/datetime/LocalTime.java +++ /dev/null @@ -1,115 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.datetime; - -import org.nanoboot.powerframework.PowerRuntimeException; - -/** - * Represents Time without date and time zone information. - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org - */ -public final class LocalTime { - - private static final String COLON = ":"; - - private final int hour; - private final int minute; - private final int second; - private final int millisecond; - - /** - * Constructor - * - * @param hour - * @param minute - * @param second - * @param millisecond - * @exception PowerRuntimeException if parameters are invalid. - */ - public LocalTime(int hour, int minute, int second, int millisecond) { - TimeUnitsValidator.checkInputValuesForTimeAndIfThereIsAnInvalidOneThrowException(hour, minute, second, millisecond); - this.hour = hour; - this.minute = minute; - this.second = second; - this.millisecond = millisecond; - } - - /** - * - * @return hour of this time. - */ - public int getHour() { - return hour; - } - - /** - * - * @return minute of this time. - */ - public int getMinute() { - return minute; - } - - /** - * - * @return second of this time. - */ - public int getSecond() { - return second; - } - - /** - * - * @return millisecond of this time. - */ - public int getMillisecond() { - return millisecond; - } - - @Override - public String toString() { - StringBuilder stringBuilder = new StringBuilder(); - - if (hour < 10) { - stringBuilder.append("0"); - } - stringBuilder.append(this.getHour()); - stringBuilder.append(COLON); - if (minute < 10) { - stringBuilder.append("0"); - } - stringBuilder.append(this.getMinute()); - stringBuilder.append(COLON); - if (second < 10) { - stringBuilder.append("0"); - } - stringBuilder.append(this.getSecond()); - stringBuilder.append(COLON); - if (millisecond < 10) { - stringBuilder.append("00"); - } else if (millisecond < 100) { - stringBuilder.append("0"); - } - stringBuilder.append(this.getMillisecond()); - return stringBuilder.toString(); - } -} diff --git a/src/main/java/org/nanoboot/powerframework/datetime/package-info.java b/src/main/java/org/nanoboot/powerframework/datetime/package-info.java deleted file mode 100644 index 65f290b..0000000 --- a/src/main/java/org/nanoboot/powerframework/datetime/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * This package contains date and time utilities. - */ -package org.nanoboot.powerframework.datetime; diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonObject.java b/src/main/java/org/nanoboot/powerframework/json/JsonObject.java deleted file mode 100644 index 03fe0a7..0000000 --- a/src/main/java/org/nanoboot/powerframework/json/JsonObject.java +++ /dev/null @@ -1,540 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.json; - -import org.nanoboot.powerframework.PowerRuntimeException; -import org.nanoboot.powerframework.collections.Dictionary; -import org.nanoboot.powerframework.collections.DictionaryKeyIterator; - -/** - * Represents json object of json. * @author Robert Vokac e-mail: - * robertvokac@nanoboot.org - */ -public class JsonObject { - - private final Dictionary dictionary = new Dictionary<>(); - - /** - * Constructor - * - * Used to create empty jsonObject. - */ - public JsonObject() { - // Used to create empty jsonObject. - } - - /** - * Constructor - * - * From String creates json object. - * - * @param textToParse - */ - public JsonObject(String textToParse) { - JsonObjectParser.parseStringToJsonObject(this, textToParse); - } - - /** - * - * @return count of items(keys and its values) of this json object - */ - public int getCountOfItems() { - return dictionary.getCountOfItems(); - } - - /** - * - * @return result of this control - */ - public boolean isEmpty() { - return dictionary.isEmpty(); - } - - /** - * - * @param key - * @return result of this control - */ - public boolean containsValueWithKey(String key) { - return this.dictionary.containsValueWithKey(key); - } - - /** - * Add to this json object new key, object is converted to the most suitable - * json value type and is set as value of the key. - * - * @param key - * @param object - * @return - */ - public JsonObject add(String key, Object object) {//NOSONAR - if (object == null) { - addNull(key); - } else { - switch (object.getClass().getName()) { - case "org.nanoboot.powerframework.json.JsonObject": - addObject(key, (JsonObject) object); - break; - case "org.nanoboot.powerframework.json.JsonArray": - addArray(key, (JsonArray) object); - break; - case "java.lang.Boolean": - addBoolean(key, (boolean) object); - break; - case "java.lang.String": - addString(key, (String) object); - break; - case "java.lang.Character": - addChar(key, (char) object); - break; - case "java.lang.Integer": - addInt(key, (int) object); - break; - case "java.lang.Long": - addLong(key, (long) object); - break; - case "java.lang.Float": - addFloat(key, (float) object); - break; - case "java.lang.Double": - addDouble(key, (double) object); - break; - default: - throw new PowerRuntimeException("I can't add the given object as value."); - } - } - return this; - } - - /** - * Add to this json object new key with null as value. - * - * @param key - * @return - */ - public JsonObject addNull(String key) { - this.dictionary.addValue(key, new JsonValue()); - return this; - } - - /** - * Add to this json object new key with json object as value. - * - * @param key - * @param value - * @return - */ - public JsonObject addObject(String key, JsonObject value) { - this.dictionary.addValue(key, new JsonValue(value)); - return this; - } - - /** - **Add to this json object new key with json array as value. - * - * @param key - * @param value - * @return - */ - public JsonObject addArray(String key, JsonArray value) { - this.dictionary.addValue(key, new JsonValue(value)); - return this; - } - - /** - * Add to this json object new key with the value of the boolean as the - * value of the key. - * - * @param key - * @param value - * @return - */ - public JsonObject addBoolean(String key, boolean value) { - this.dictionary.addValue(key, new JsonValue(new JsonBoolean(value))); - return this; - } - - /** - * Add to this json object new key with the value of the String as the value - * of the key. - * - * @param key - * @param value - * @return - */ - public JsonObject addString(String key, String value) { - this.dictionary.addValue(key, new JsonValue(new JsonString(value))); - return this; - } - - /** - * Add to this json object new key with the value of the char as the value - * of the key. - * - * @param key - * @param value - * @return - */ - public JsonObject addChar(String key, char value) { - this.dictionary.addValue(key, new JsonValue(new JsonChar(value))); - return this; - } - - /** - * Add to this json object new key with the value of the int as the value of - * the key. - * - * @param key - * @param value - * @return - */ - public JsonObject addInt(String key, int value) { - this.dictionary.addValue(key, new JsonValue(new JsonInt(value))); - return this; - } - - /** - * Add to this json object new key with the value of the long as the value - * of the key. - * - * @param key - * @param value - * @return - */ - public JsonObject addLong(String key, long value) { - this.dictionary.addValue(key, new JsonValue(new JsonLong(value))); - return this; - } - - /** - * Add to this json object new key with the value of the float as the value - * of the key. - * - * @param key - * @param value - * @return - */ - public JsonObject addFloat(String key, float value) { - this.dictionary.addValue(key, new JsonValue(new JsonFloat(value))); - return this; - } - - /** - * Add to this json object new key with the value of the double as the value - * of the key. - * - * @param key - * @param value - * @return - */ - public JsonObject addDouble(String key, double value) { - this.dictionary.addValue(key, new JsonValue(new JsonDouble(value))); - return this; - } - - /** - * - * @param key - * @return value type of the value of the given key - */ - public JsonValueType getJsonValueType(String key) { - return dictionary.getValue(key).getJsonValueType(); - } - - /** - * - * @param key - * @return object instance converted from the value of the given key - */ - public Object get(String key) { - return dictionary.getValue(key).toObject(); - } - - /** - * - * @param key - * @return json object from the value of the given key - */ - public JsonObject getObject(String key) { - return this.dictionary.getValue(key).getJsonObject(); - } - - /** - * - * @param key - * @return json array from the value of the given key - */ - public JsonArray getArray(String key) { - return this.dictionary.getValue(key).getJsonArray(); - } - - /** - * - * @param key - * @return boolean from the value of the given key - */ - public boolean getBoolean(String key) { - return this.dictionary.getValue(key).getJsonBoolean().getBoolean(); - } - - /** - * - * @param key - * @return String from the value of the given key - */ - public String getString(String key) { - return this.dictionary.getValue(key).getJsonString().getString(); - } - - /** - * - * @param key - * @return char from the value of the given key - */ - public char getChar(String key) { - return this.dictionary.getValue(key).getJsonChar().getChar(); - } - - /** - * - * @param key - * @return int from the value of the given key - */ - public int getInt(String key) { - return this.dictionary.getValue(key).getJsonInt().getInt(); - } - - /** - * - * @param key - * @return long from the value of the given key - */ - public long getLong(String key) { - return this.dictionary.getValue(key).getJsonLong().getLong(); - } - - /** - * - * @param key - * @return float from the value of the given key - */ - public float getFloat(String key) { - return this.dictionary.getValue(key).getJsonFloat().getFloat(); - } - - /** - * - * @param key - * @return double from the value of the given key - */ - public double getDouble(String key) { - return this.dictionary.getValue(key).getJsonDouble().getDouble(); - } - - /** - * Updates the value of the given key. - * - * @param key - * @param object - */ - public void update(String key, Object object) {//NOSONAR - if (object == null) { - updateNull(key); - } else { - switch (object.getClass().getName()) { - case "org.nanoboot.powerframework.json.JsonObject": - updateObject(key, (JsonObject) object); - break; - case "org.nanoboot.powerframework.json.JsonArray": - updateArray(key, (JsonArray) object); - break; - case "java.lang.Boolean": - updateBoolean(key, (boolean) object); - break; - case "java.lang.String": - updateString(key, (String) object); - break; - case "java.lang.Character": - updateChar(key, (char) object); - break; - case "java.lang.Integer": - updateInt(key, (int) object); - break; - case "java.lang.Long": - updateLong(key, (long) object); - break; - case "java.lang.Float": - updateFloat(key, (float) object); - break; - case "java.lang.Double": - updateDouble(key, (double) object); - break; - default: - throw new PowerRuntimeException("I can't add the given object as value."); - } - } - } - - /** - * Updates the value of the given key. - * - * @param key - */ - public void updateNull(String key) { - this.dictionary.updateValue(key, new JsonValue()); - } - - /** - * Updates the value of the given key. - * - * @param key - * @param value - */ - public void updateObject(String key, JsonObject value) { - this.dictionary.updateValue(key, new JsonValue(value)); - } - - /** - * Updates the value of the given key. - * - * @param key - * @param value - */ - public void updateArray(String key, JsonArray value) { - this.dictionary.updateValue(key, new JsonValue(value)); - } - - /** - * Updates the value of the given key. - * - * @param key - * @param value - */ - public void updateBoolean(String key, boolean value) { - this.dictionary.updateValue(key, new JsonValue(new JsonBoolean(value))); - } - - /** - * Updates the value of the given key. - * - * @param key - * @param value - */ - public void updateString(String key, String value) { - this.dictionary.updateValue(key, new JsonValue(new JsonString(value))); - } - - /** - * Updates the value of the given key. - * - * @param key - * @param value - */ - public void updateChar(String key, char value) { - this.dictionary.updateValue(key, new JsonValue(new JsonChar(value))); - } - - /** - * Updates the value of the given key. - * - * @param key - * @param value - */ - public void updateInt(String key, int value) { - this.dictionary.updateValue(key, new JsonValue(new JsonInt(value))); - } - - /** - * Updates the value of the given key. - * - * @param key - * @param value - */ - public void updateLong(String key, long value) { - this.dictionary.updateValue(key, new JsonValue(new JsonLong(value))); - } - - /** - * Updates the value of the given key. - * - * @param key - * @param value - */ - public void updateFloat(String key, float value) { - this.dictionary.updateValue(key, new JsonValue(new JsonFloat(value))); - } - - /** - * Updates the value of the given key. - * - * @param key - * @param value - */ - public void updateDouble(String key, double value) { - this.dictionary.updateValue(key, new JsonValue(new JsonDouble(value))); - } - - /** - * Removes the key and its value. - * - * @param key - */ - public void removeJsonValue(String key) { - this.dictionary.removeValue(key); - } - - /** - * - * @return String representation of this json object in minimal version - */ - public String toMinimalString() { - return JsonObjectPrinter.toMinimalString(this); - } - - /** - * - * @return String representation of this json object in pretty print version - */ - public String toPrettyString() { - return JsonObjectPrinter.toPrettyString(this); - } - - /** - * - * @return copy of this json object - */ - public JsonObject getCopy() { - String stringRepresentationOfThisObject = this.toMinimalString(); - return new JsonObject(stringRepresentationOfThisObject); - } - - /** - * - * @return key iterator - */ - public DictionaryKeyIterator getKeyIterator() { - return this.dictionary.getKeyIterator(); - } - - JsonValue getJsonValue(String key) { - return this.dictionary.getValue(key); - } -} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonObjectParser.java b/src/main/java/org/nanoboot/powerframework/json/JsonObjectParser.java deleted file mode 100644 index c6f6d67..0000000 --- a/src/main/java/org/nanoboot/powerframework/json/JsonObjectParser.java +++ /dev/null @@ -1,110 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.json; - -import java.util.ArrayList; -import org.nanoboot.powerframework.PowerRuntimeException; - -/** - * Is used to create json objects from strings. - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org - */ -class JsonObjectParser extends JsonParser { - - /** - * Constructor - * - * Not meant to be instantiated. - */ - private JsonObjectParser() { - //Not meant to be instantiated. - } - - /** - * Parses String to empty json object. - * - * @param jsonObject - * @param stringRepresentationOfJsonObject - * @return json object from parsed String - */ - static JsonObject parseStringToJsonObject(JsonObject jsonObject, String stringRepresentationOfJsonObject) { - if (!jsonObject.isEmpty()) { - throw new PowerRuntimeException("I can't parse. The json object is not empty."); - } - String trimmedStringRepresentationOfJsonObject = stringRepresentationOfJsonObject.trim(); - if (!isStringJsonObject(trimmedStringRepresentationOfJsonObject)) { - throw new PowerRuntimeException("I can't parse. The trimmed String does not start with { or does not end with }"); - } - String collectionsOfValuesOfTheJsonObjectString = deleteTheCharAtTheStartAndTheEnd(trimmedStringRepresentationOfJsonObject); - - fillJsonObjectWithParsedValues(jsonObject, collectionsOfValuesOfTheJsonObjectString); - return jsonObject; - } - - private static boolean isStringJsonObject(String trimmedStringRepresentationOfJsonObject) { - return (getFirstCharOfTheString(trimmedStringRepresentationOfJsonObject) == JsonSpecialCharSequences.getObjectLeft()) && (getLastCharOfTheString(trimmedStringRepresentationOfJsonObject) == JsonSpecialCharSequences.getObjectRight()); - } - - private static void fillJsonObjectWithParsedValues(JsonObject jsonObject, String collectionsOfValuesOfTheJsonObjectString) { - - ArrayList listOfCommas = getListOfIndexesOfTheStringWhereCharIsCommaAndNestingIsZero(collectionsOfValuesOfTheJsonObjectString); - int beginIndex; - int indexOfComma = 0; - for (int i = 0; i < listOfCommas.size(); i++) { - beginIndex = ++indexOfComma; - indexOfComma = listOfCommas.get(i); - if (i == 0) { - beginIndex = 0; - } - String fraction = collectionsOfValuesOfTheJsonObjectString.substring(beginIndex, indexOfComma); - - String key = getKeyFromKeyValue(fraction).trim(); - key = key.substring(1, key.length() - 1); - Object parsedObject = JsonParser.parseStringToValue(getValueFromKeyValue(fraction)); - - jsonObject.add(key, parsedObject); - } - - } - - private static String getKeyFromKeyValue(String string) { - return getKeyOrValueFromKeyValue(string, true); - } - - private static String getValueFromKeyValue(String string) { - return getKeyOrValueFromKeyValue(string, false); - } - - private static String getKeyOrValueFromKeyValue(String string, boolean trueForKeyFalseForValue) { - String stringToReturn; - int intToSaveColonIndex; - for (intToSaveColonIndex = 0; intToSaveColonIndex < string.length(); intToSaveColonIndex++) { - char currentChar = string.charAt(intToSaveColonIndex); - if (currentChar == JsonSpecialCharSequences.getColon()) { - break; - } - } - stringToReturn = trueForKeyFalseForValue ? string.substring(0, intToSaveColonIndex) : string.substring(++intToSaveColonIndex, string.length()); - - return stringToReturn; - } -} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonParser.java b/src/main/java/org/nanoboot/powerframework/json/JsonParser.java deleted file mode 100644 index e8e5463..0000000 --- a/src/main/java/org/nanoboot/powerframework/json/JsonParser.java +++ /dev/null @@ -1,176 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.json; - -import java.util.ArrayList; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Pattern; -import org.nanoboot.powerframework.PowerRuntimeException; - -/** - * Used to parse String representation of JsonObject or JsonArray to their - * object representation. - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org - */ -class JsonParser { - - /** - * Constructor - * - * Not meant to be instantiated. - */ - JsonParser() { - //Not meant to be instantiated. - } - - static char getFirstCharOfTheString(String string) { - return string.charAt(0); - } - - static char getLastCharOfTheString(String string) { - return string.charAt(string.length() - 1); - } - - protected static String deleteTheCharAtTheStartAndTheEnd(String string) { - return string.substring(1, string.length() - 1); - } - - protected static Object parseStringToValue(String stringToParse) {//NOSONAR - String trimmedStringToParse = stringToParse.trim(); - if ("null".equals(trimmedStringToParse)) { - return null; - } - if ("{".equals(trimmedStringToParse.substring(0, 1))) { - return new JsonObject(trimmedStringToParse); - } - if ("[".equals(trimmedStringToParse.substring(0, 1))) { - return new JsonArray(trimmedStringToParse); - } - if ("true".equals(trimmedStringToParse)) { - return true; - } - if ("false".equals(trimmedStringToParse)) { - return false; - } - if ("\"".equals(trimmedStringToParse.substring(0, 1))) { - return parseStringToStringOrChar(trimmedStringToParse); - } - try { - return parseStringToIntOrLongOrFloatOrDouble(trimmedStringToParse); - } catch (Exception e) { - throw new PowerRuntimeException("Something went wrong. I am not able to parse: \"" + stringToParse + "\". " + e); - } - - } - - private static Object parseStringToStringOrChar(String stringToParse) { - String stringWithoutQuotes = deleteTheCharAtTheStartAndTheEnd(stringToParse); - if (stringWithoutQuotes.length() == 1) { - return stringWithoutQuotes.charAt(0); - } else { - return stringWithoutQuotes; - } - } - - private static Object parseStringToIntOrLongOrFloatOrDouble(String stringToParse) { - String intOrLongPattern = "[0-9]*"; - String floatOrDoublePattern = "([0-9]*)\\.([0-9]*)"; - - if (Pattern.matches(floatOrDoublePattern, stringToParse)) { - return parseStringToFloatOrDouble(stringToParse); - } - if (Pattern.matches(intOrLongPattern, stringToParse)) { - return parseStringToIntOrLong(stringToParse); - } - throw new PowerRuntimeException("I am not able to parse: \"" + stringToParse + "\"."); - } - - private static Object parseStringToIntOrLong(String stringToParse) { - try { - return Integer.parseInt(stringToParse); - } catch (Exception e) { - Logger.getLogger(JsonParser.class.getName()).log(Level.SEVERE, null, e); - try { - return Long.parseLong(stringToParse); - } catch (Exception e2) { - Logger.getLogger(JsonParser.class.getName()).log(Level.SEVERE, null, e2); - throw new PowerRuntimeException("The number is too long."); - } - } - - } - - private static Object parseStringToFloatOrDouble(String stringToParse) { - int digitsPrecision = 0; - for (int i = 0; i < stringToParse.length(); i++) { - char currentChar = stringToParse.charAt(i); - if (currentChar == '.') { - digitsPrecision = stringToParse.length() - 1 - i; - break; - } - } - if (digitsPrecision > 6) { - try { - return Double.parseDouble(stringToParse); - } catch (Exception e) {//NOSONAR - throw new PowerRuntimeException("The number is too long."); - } - } else { - return Float.parseFloat(stringToParse); - } - } - - protected static ArrayList getListOfIndexesOfTheStringWhereCharIsCommaAndNestingIsZero(String collectionsOfValuesOfTheJsonArrayString) { - int nesting = 0; - ArrayList listOfCommas = new ArrayList<>(); - char currentChar; - for (int i = 0; i < collectionsOfValuesOfTheJsonArrayString.length(); i++) { - currentChar = collectionsOfValuesOfTheJsonArrayString.charAt(i); - if ((currentChar == '\"') && (nesting == 0)) { - i++;//NOSONAR - while ('\"' != collectionsOfValuesOfTheJsonArrayString.charAt(i)) { - i++;//NOSONAR - } - } - if ((currentChar == ',') && (nesting == 0)) { - listOfCommas.add(i); - } - if (nestingWillBeIncreased(currentChar)) { - nesting++; - } - if (nestingWillBeDecreased(currentChar)) { - nesting--; - } - } - listOfCommas.add(collectionsOfValuesOfTheJsonArrayString.length()); - return listOfCommas; - } - - private static boolean nestingWillBeIncreased(char charToCheck) { - return (charToCheck == '{') || (charToCheck == '['); - } - - private static boolean nestingWillBeDecreased(char charToCheck) { - return (charToCheck == '}') || (charToCheck == ']'); - } -} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonSpecialCharSequences.java b/src/main/java/org/nanoboot/powerframework/json/JsonSpecialCharSequences.java deleted file mode 100644 index d9825bc..0000000 --- a/src/main/java/org/nanoboot/powerframework/json/JsonSpecialCharSequences.java +++ /dev/null @@ -1,99 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.json; - -/** - * Used to store char and String constants used to parse or print json objects - * or arrays. - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org - */ -class JsonSpecialCharSequences { - - private static final char OBJECTLEFT = '{'; - private static final char OBJECTRIGHT = '}'; - private static final char ARRAYLEFT = '['; - private static final char ARRAYRIGHT = ']'; - private static final char COMMA = ','; - private static final char COLON = ':'; - private static final char APOSTROPHE = '"'; - private static final String LINEBREAK = "\n"; - private static final String NULL = "null"; - private static final String TRUE = "true"; - private static final String FALSE = "false"; - private static final String TAB = " "; - private static final char SPACE = ' '; - - private JsonSpecialCharSequences() { - } - - static char getObjectLeft() { - return OBJECTLEFT; - } - - static char getObjectRight() { - return OBJECTRIGHT; - } - - static char getArrayLeft() { - return ARRAYLEFT; - } - - static char getArrayRight() { - return ARRAYRIGHT; - } - - static char getComma() { - return COMMA; - } - - static char getColon() { - return COLON; - } - - static char getApostrophe() { - return APOSTROPHE; - } - - static String getLineBreak() { - return LINEBREAK; - } - - static String getNull() { - return NULL; - } - - static String getTrue() { - return TRUE; - } - - static String getFalse() { - return FALSE; - } - - static String getTab() { - return TAB; - } - - static char getSpace() { - return SPACE; - } -} diff --git a/src/main/java/org/nanoboot/powerframework/json/JsonValue.java b/src/main/java/org/nanoboot/powerframework/json/JsonValue.java deleted file mode 100644 index 4336a4c..0000000 --- a/src/main/java/org/nanoboot/powerframework/json/JsonValue.java +++ /dev/null @@ -1,290 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.json; - -import org.nanoboot.powerframework.PowerRuntimeException; - -/** - * Represents json value. - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org - */ -class JsonValue { - - private JsonValueType jsonValueType = null; - - private JsonObject jsonObject = null; - private JsonArray jsonArray = null; - private JsonBoolean jsonBoolean = null; - private JsonString jsonString = null; - private JsonChar jsonChar = null; - private JsonInt jsonInt = null; - private JsonLong jsonLong = null; - private JsonFloat jsonFloat = null; - private JsonDouble jsonDouble = null; - - JsonValue() { - this.jsonValueType = JsonValueType.NULL; - } - - JsonValue(JsonObject jsonObject) { - this.jsonValueType = JsonValueType.OBJECT; - this.jsonObject = jsonObject; - } - - JsonValue(JsonArray jsonArray) { - this.jsonValueType = JsonValueType.ARRAY; - this.jsonArray = jsonArray; - } - - JsonValue(JsonBoolean jsonBoolean) { - this.jsonValueType = JsonValueType.BOOLEAN; - this.jsonBoolean = jsonBoolean; - } - - JsonValue(JsonString jsonString) { - this.jsonValueType = JsonValueType.STRING; - this.jsonString = jsonString; - } - - JsonValue(JsonChar jsonLiteral) { - this.jsonValueType = JsonValueType.CHAR; - this.jsonChar = jsonLiteral; - } - - JsonValue(JsonInt jsonInt) { - this.jsonValueType = JsonValueType.INT; - this.jsonInt = jsonInt; - } - - JsonValue(JsonLong jsonLong) { - this.jsonValueType = JsonValueType.LONG; - this.jsonLong = jsonLong; - } - - JsonValue(JsonFloat jsonFloat) { - this.jsonValueType = JsonValueType.FLOAT; - this.jsonFloat = jsonFloat; - } - - JsonValue(JsonDouble jsonDouble) { - this.jsonValueType = JsonValueType.DOUBLE; - this.jsonDouble = jsonDouble; - } - - JsonValueType getJsonValueType() { - return this.jsonValueType; - } - - boolean isNull() { - return this.jsonValueType == JsonValueType.NULL; - } - - boolean isObject() { - return this.jsonValueType == JsonValueType.OBJECT; - } - - boolean isArray() { - return this.jsonValueType == JsonValueType.ARRAY; - } - - boolean isBoolean() { - return this.jsonValueType == JsonValueType.BOOLEAN; - } - - boolean isString() { - return this.jsonValueType == JsonValueType.STRING; - } - - boolean isChar() { - return this.jsonValueType == JsonValueType.CHAR; - } - - boolean isInt() { - return this.jsonValueType == JsonValueType.INT; - } - - boolean isLong() { - return this.jsonValueType == JsonValueType.LONG; - } - - boolean isFloat() { - return this.jsonValueType == JsonValueType.FLOAT; - } - - boolean isDouble() { - return this.jsonValueType == JsonValueType.DOUBLE; - } - - JsonObject getJsonObject() { - if (this.isObject()) { - return this.jsonObject; - } else { - throw new PowerRuntimeException("This JsonValue has no type JsonObject"); - } - } - - JsonArray getJsonArray() { - if (this.isArray()) { - return this.jsonArray; - } else { - throw new PowerRuntimeException("This JsonValue has no type JsonArray"); - } - } - - JsonBoolean getJsonBoolean() { - if (this.isBoolean()) { - return this.jsonBoolean; - } else { - throw new PowerRuntimeException("This JsonValue has no type JsonBoolean"); - } - } - - JsonString getJsonString() { - if (this.isString()) { - return this.jsonString; - } else { - throw new PowerRuntimeException("This JsonValue has no type JsonString"); - } - } - - JsonChar getJsonChar() { - if (this.isChar()) { - return this.jsonChar; - } else { - throw new PowerRuntimeException("This JsonValue has no type JsonChar"); - } - } - - JsonInt getJsonInt() { - if (this.isInt()) { - return this.jsonInt; - } else { - throw new PowerRuntimeException("This JsonValue has no type JsonInt"); - } - } - - JsonLong getJsonLong() { - if (this.isLong()) { - return this.jsonLong; - } else { - throw new PowerRuntimeException("This JsonValue has no type JsonLong"); - } - } - - JsonFloat getJsonFloat() { - if (this.isFloat()) { - return this.jsonFloat; - } else { - throw new PowerRuntimeException("This JsonValue has no type JsonFloat"); - } - } - - JsonDouble getJsonDouble() { - if (this.isDouble()) { - return this.jsonDouble; - } else { - throw new PowerRuntimeException("This JsonValue has no type JsonDouble"); - } - } - - String toPrettyString() { - return toString(true); - } - - String toMinimalString() { - return toString(false); - } - - String toString(boolean printAsPrettyVersion) {//NOSONAR - switch (this.jsonValueType) { - case NULL: - return JsonSpecialCharSequences.getNull(); - case OBJECT: - if (printAsPrettyVersion) { - return this.getJsonObject().toPrettyString(); - } else { - return this.getJsonObject().toMinimalString(); - } - case ARRAY: - if (printAsPrettyVersion) { - return this.getJsonArray().toPrettyString(); - } else { - return this.getJsonArray().toMinimalString(); - } - case BOOLEAN: - return this.getJsonBoolean().toString(); - - case STRING: - return this.getJsonString().toString(); - case CHAR: - return this.getJsonChar().toString(); - case INT: - return this.getJsonInt().toString(); - case LONG: - return this.getJsonLong().toString(); - case FLOAT: - return this.getJsonFloat().toString(); - case DOUBLE: - return this.getJsonDouble().toString(); - default: - throw new IllegalStateException("Enum error."); - } - } - - Object toObject() {//NOSONAR - switch (jsonValueType) { - case NULL: - return null; - - case OBJECT: - return this.getJsonObject(); - - case ARRAY: - return this.getJsonArray(); - - case BOOLEAN: - return this.getJsonBoolean().getBoolean(); - - case STRING: - return this.getJsonString().getString(); - - case CHAR: - return this.getJsonChar().getChar(); - - case INT: - return this.getJsonInt().getInt(); - - case LONG: - return this.getJsonLong().getLong(); - - case FLOAT: - return this.getJsonFloat().getFloat(); - - case DOUBLE: - return this.getJsonDouble().getDouble(); - - default: - throw new IllegalStateException("Enum error."); - } - - } -} diff --git a/src/main/java/org/nanoboot/powerframework/package-info.java b/src/main/java/org/nanoboot/powerframework/package-info.java deleted file mode 100644 index fccdfde..0000000 --- a/src/main/java/org/nanoboot/powerframework/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * This package represents Power library. - * Power contains many general-purpose packages and classes suitable to more than one use. - */ -package org.nanoboot.powerframework; diff --git a/src/main/java/org/nanoboot/powerframework/pseudorandom/PseudoRandomGenerator.java b/src/main/java/org/nanoboot/powerframework/pseudorandom/PseudoRandomGenerator.java deleted file mode 100644 index c56f589..0000000 --- a/src/main/java/org/nanoboot/powerframework/pseudorandom/PseudoRandomGenerator.java +++ /dev/null @@ -1,131 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.pseudorandom; - -import org.nanoboot.powerframework.PowerRuntimeException; -import org.nanoboot.powerframework.datetime.DateTime; -import org.nanoboot.powerframework.datetime.UniversalDateTime; - -/** - * Used to generate pseudo random values. - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org - */ -public class PseudoRandomGenerator { - - private final Seed magicSeed; - private final Seed[] seed = new Seed[2]; - private static final PseudoRandomGenerator pseudoRandomGenerator; - - /** - * Constructor - * - * @param magicNumber - * @param dateTime - */ - public PseudoRandomGenerator(long magicNumber, DateTime dateTime) { - this.magicSeed = new Seed(magicNumber); - long year = dateTime.getYear(); - long month = dateTime.getMonth(); - long day = dateTime.getDay(); - long hour = dateTime.getHour(); - long minute = dateTime.getMinute(); - long second = dateTime.getSecond(); - long millisecond = dateTime.getMillisecond(); - this.seed[0] = new Seed(1000 * (minute + day) + millisecond); - this.seed[1] = new Seed(hour * 100000000 + year * 10000 + second * 100 + month); - - } - - static { - UniversalDateTime currentUniversalDateTime = UniversalDateTime.getCurrentUniversalDateTime(); - int currentDay = currentUniversalDateTime.getMonth(); - int currentMillisecond = currentUniversalDateTime.getMillisecond(); - long magicNumber = (long) currentDay * 1000 + (long) currentMillisecond; - pseudoRandomGenerator = new PseudoRandomGenerator(magicNumber, currentUniversalDateTime); - } - - /** - * @return static instance - */ - public static PseudoRandomGenerator getInstance() { - return pseudoRandomGenerator; - } - - /** - * - * @param from - * @param to - * @return pseudo random long - */ - public long getLong(long from, long to) { - if (from > to) { - throw new IllegalArgumentException("from is greater than to."); - } - - long[] numberFractions = new long[2]; - - for (int i = 0; i <= 1; i++) { - this.seed[0].jump(); - this.seed[1].jump(); - - if (((magicSeed.getNextNumber()) % 2) == 0) { - this.seed[0].jump(); - } - if (((magicSeed.getNextNumber()) % 2) == 1) { - this.seed[1].jump(); - } - long number1 = seed[0].getNextNumber(); - long number2 = seed[1].getNextNumber(); - if ((magicSeed.getNextNumber() % 2) == 1) { - number2 = number2 * (-1); - } - numberFractions[i] = (Math.abs(number1 + number2)) % 1000000000; - } - long number = (numberFractions[0] * 1000000000) + numberFractions[1]; - - number = (number % (to - from + 1)) + from; - - return number; - } - - /** - * - * @param from - * @param to - * @return pseudo random int - */ - public int getInt(int from, int to) { - if (to > Integer.MAX_VALUE) { - throw new PowerRuntimeException("The parameter \"to\" is too big."); - } - return (int) getLong(from, to); - } - - /** - * - * @return pseudo random boolean - */ - public boolean getBoolean() { - int value = getInt(0, 1); - return value == 1; - } -} diff --git a/src/test/java/org/nanoboot/powerframework/collections/DictionaryKeyIteratorTest.java b/src/test/java/org/nanoboot/powerframework/collections/DictionaryKeyIteratorTest.java deleted file mode 100644 index 55cde57..0000000 --- a/src/test/java/org/nanoboot/powerframework/collections/DictionaryKeyIteratorTest.java +++ /dev/null @@ -1,205 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.collections; - -import org.junit.Test; -import static org.junit.Assert.*; - -/** - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org - */ -public class DictionaryKeyIteratorTest { - - /** - * - */ - public DictionaryKeyIteratorTest() { - } - - /** - * Test of getNextKey method, of class DictionaryKeyIterator. - */ - @Test - public void testGetNextKey() { - //arrange - Dictionary dictionary = new Dictionary<>(); - DictionaryKeyIterator dictionaryKeyIterator; - StringBuilder stringBuilder = new StringBuilder(); - String key1; - String key2; - String key3; - String value1; - String value2; - String value3; - String expectedString = "JohnJohnycalm"; - String returnedString; - //act - dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); - dictionary.removeValue("surname"); - dictionary.addValue("personality", "calm"); - dictionaryKeyIterator = dictionary.getKeyIterator(); - key1 = dictionaryKeyIterator.getNextKey(); - key2 = dictionaryKeyIterator.getNextKey(); - key3 = dictionaryKeyIterator.getNextKey(); - - value1 = dictionary.getValue(key1); - value2 = dictionary.getValue(key2); - value3 = dictionary.getValue(key3); - - stringBuilder.append(value1); - stringBuilder.append(value2); - stringBuilder.append(value3); - returnedString = stringBuilder.toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of hasNext method, of class DictionaryKeyIterator. - */ - @Test - public void testHasNext() { - //arrange - Dictionary dictionary = new Dictionary<>(); - DictionaryKeyIterator dictionaryKeyIterator; - boolean expectedValue = true; - boolean returnedValue; - //act - dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); - dictionary.removeValue("surname"); - dictionary.addValue("personality", "calm"); - dictionaryKeyIterator = dictionary.getKeyIterator(); - dictionaryKeyIterator.getNextKey(); - dictionaryKeyIterator.getNextKey(); - returnedValue = dictionaryKeyIterator.hasNext(); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of hasNext method, of class DictionaryKeyIterator. - */ - @Test - public void testHasNext2() { - //arrange - Dictionary dictionary = new Dictionary<>(); - DictionaryKeyIterator dictionaryKeyIterator; - boolean expectedValue = false; - boolean returnedValue; - //act - dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); - dictionary.removeValue("surname"); - dictionary.addValue("personality", "calm"); - dictionaryKeyIterator = dictionary.getKeyIterator(); - dictionaryKeyIterator.getNextKey(); - dictionaryKeyIterator.getNextKey(); - dictionaryKeyIterator.getNextKey(); - returnedValue = dictionaryKeyIterator.hasNext(); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of hasNext method, of class DictionaryKeyIterator. - */ - @Test - public void testHasNext3() { - //arrange - Dictionary dictionary = new Dictionary<>(); - DictionaryKeyIterator dictionaryKeyIterator; - boolean expectedValue = false; - boolean returnedValue; - //act - dictionary.addValue("name", "John"); - dictionaryKeyIterator = dictionary.getKeyIterator(); - dictionaryKeyIterator.getNextKey(); - returnedValue = dictionaryKeyIterator.hasNext(); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of hasNext method, of class DictionaryKeyIterator. - */ - @Test - public void testHasNext4() { - //arrange - Dictionary dictionary = new Dictionary<>(); - DictionaryKeyIterator dictionaryKeyIterator; - boolean expectedValue = false; - boolean returnedValue; - //act - - dictionaryKeyIterator = dictionary.getKeyIterator(); - - returnedValue = dictionaryKeyIterator.hasNext(); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of hasNext method, of class DictionaryKeyIterator. - */ - @Test - public void testHasNext5() { - //arrange - Dictionary dictionary = new Dictionary<>(); - DictionaryKeyIterator dictionaryKeyIterator; - boolean expectedValue = true; - boolean returnedValue; - //act - dictionary.addValue("name", "John"); - dictionaryKeyIterator = dictionary.getKeyIterator(); - - returnedValue = dictionaryKeyIterator.hasNext(); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of reset method, of class DictionaryKeyIterator. - */ - @Test - public void testReset() { - //arrange - Dictionary dictionary = new Dictionary<>(); - DictionaryKeyIterator dictionaryKeyIterator; - String firstKey; - - String expectedString = "John"; - String returnedString; - //act - dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); - dictionary.removeValue("surname"); - dictionary.addValue("personality", "calm"); - dictionaryKeyIterator = dictionary.getKeyIterator(); - for (int i = 0; i < 3; i++) { - dictionaryKeyIterator.getNextKey(); - } - dictionaryKeyIterator.reset(); - firstKey = dictionaryKeyIterator.getNextKey(); - returnedString = dictionary.getValue(firstKey); - //assert - assertEquals(expectedString, returnedString); - } - -} diff --git a/src/test/java/org/nanoboot/powerframework/collections/DictionaryNodeTest.java b/src/test/java/org/nanoboot/powerframework/collections/DictionaryNodeTest.java deleted file mode 100644 index 05df7d1..0000000 --- a/src/test/java/org/nanoboot/powerframework/collections/DictionaryNodeTest.java +++ /dev/null @@ -1,137 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.collections; - -import org.junit.Test; -import static org.junit.Assert.*; - -/** - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org - */ -public class DictionaryNodeTest { - - /** - * - */ - public DictionaryNodeTest() { - } - - /** - * Test of getElement method, of class DictionaryNode. - */ - @Test - public void testGetElement() { - //arrange - DictionaryNode dictionaryNode = new DictionaryNode<>("name", "John"); - String expectedString = "John"; - String returnedString; - //act - returnedString = dictionaryNode.getElement(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of setElement method, of class DictionaryNode. - */ - @Test - public void testSetElement() { - //arrange - DictionaryNode dictionaryNode = new DictionaryNode<>("name", "John"); - String expectedString = "Jack"; - String returnedString; - //act - dictionaryNode.setElement("Jack"); - returnedString = dictionaryNode.getElement(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of getNext method, of class DictionaryNode. - */ - @Test - public void testGetNext() { - //arrange - DictionaryNode dictionaryNode = new DictionaryNode<>("name", "John"); - DictionaryNode dictionaryNode2 = new DictionaryNode<>("surname", "Black"); - String expectedString = "Black"; - String returnedString; - //act - dictionaryNode.setNext(dictionaryNode2); - DictionaryNode returnedDictionaryNode = dictionaryNode.getNext(); - returnedString = returnedDictionaryNode.getElement(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of setNext method, of class DictionaryNode. - */ - @Test - public void testSetNext() { - //arrange - DictionaryNode dictionaryNode = new DictionaryNode<>("name", "John"); - DictionaryNode dictionaryNode2 = new DictionaryNode<>("surname", "White"); - String expectedString = "White"; - String returnedString; - //act - dictionaryNode.setNext(dictionaryNode2); - DictionaryNode returnedDictionaryNode = dictionaryNode.getNext(); - returnedString = returnedDictionaryNode.getElement(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of getKey method, of class DictionaryNode. - */ - @Test - public void testGetKey() { - //arrange - DictionaryNode dictionaryNode = new DictionaryNode<>("name", "John"); - String expectedString = "name"; - String returnedString; - //act - returnedString = dictionaryNode.getKey(); - //assert - assertEquals(expectedString, returnedString); - - } - - /** - * Test of setKey method, of class DictionaryNode. - */ - @Test - public void testSetKey() { - //arrange - DictionaryNode dictionaryNode = new DictionaryNode<>("name", "John"); - String expectedString = "nick"; - String returnedString; - //act - dictionaryNode.setKey("nick"); - returnedString = dictionaryNode.getKey(); - //assert - assertEquals(expectedString, returnedString); - } - -} diff --git a/src/test/java/org/nanoboot/powerframework/collections/DictionaryTest.java b/src/test/java/org/nanoboot/powerframework/collections/DictionaryTest.java deleted file mode 100644 index 9fd3de7..0000000 --- a/src/test/java/org/nanoboot/powerframework/collections/DictionaryTest.java +++ /dev/null @@ -1,381 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.collections; - -import org.nanoboot.powerframework.PowerRuntimeException; -import org.junit.Test; -import static org.junit.Assert.*; - -/** - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org - */ -public class DictionaryTest { - - /** - * - */ - public DictionaryTest() { - } - - /** - * Test of getCountOfItems method, of class Dictionary. - */ - @Test - public void testGetCountOfItems() { - //arrange - Dictionary dictionary = new Dictionary<>(); - int expectedValue = 0; - int returnedValue; - //act - returnedValue = dictionary.getCountOfItems(); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of getCountOfItems method, of class Dictionary. - */ - @Test - public void testGetCountOfItems2() { - //arrange - Dictionary dictionary = new Dictionary<>(); - int expectedValue = 0; - int returnedValue; - //act - dictionary.addValue("name", "John").addValue("surname", "Black"); - dictionary.removeValue("name").removeValue("surname"); - returnedValue = dictionary.getCountOfItems(); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of getCountOfItems method, of class Dictionary. - */ - @Test - public void testGetCountOfItems3() { - //arrange - Dictionary dictionary = new Dictionary<>(); - int expectedValue = 2; - int returnedValue; - //act - dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); - dictionary.removeValue("surname"); - returnedValue = dictionary.getCountOfItems(); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of getCountOfItems method, of class Dictionary. - */ - @Test - public void testGetCountOfItems4() { - //arrange - Dictionary dictionary = new Dictionary<>(); - int expectedValue = 1; - int returnedValue; - //act - dictionary.addValue("surname", "Black"); - returnedValue = dictionary.getCountOfItems(); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of isEmpty method, of class Dictionary. - */ - @Test - public void testIsEmpty() { - //arrange - Dictionary dictionary = new Dictionary<>(); - boolean expectedValue = true; - boolean returnedValue; - //act - returnedValue = dictionary.isEmpty(); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of isEmpty method, of class Dictionary. - */ - @Test - public void testIsEmpty2() { - //arrange - Dictionary dictionary = new Dictionary<>(); - boolean expectedValue = true; - boolean returnedValue; - //act - dictionary.addValue("name", "John").addValue("surname", "Black"); - dictionary.removeValue("name").removeValue("surname"); - returnedValue = dictionary.isEmpty(); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of isEmpty method, of class Dictionary. - */ - @Test - public void testIsEmpty3() { - //arrange - Dictionary dictionary = new Dictionary<>(); - boolean expectedValue = false; - boolean returnedValue; - //act - dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); - dictionary.removeValue("surname"); - returnedValue = dictionary.isEmpty(); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of getValue method, of class Dictionary. - */ - @Test - public void testIsEmpty4() { - //arrange - Dictionary dictionary = new Dictionary<>(); - boolean expectedValue = false; - boolean returnedValue; - //act - dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); - dictionary.removeValue("name"); - returnedValue = dictionary.isEmpty(); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of containsValueWithKey method, of class Dictionary. - */ - @Test - public void containsValueWithKey() { - //arrange - Dictionary dictionary = new Dictionary<>(); - boolean expectedValue = true; - boolean returnedValue; - //act - dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); - returnedValue = dictionary.containsValueWithKey("surname"); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of containsValueWithKey method, of class Dictionary. - */ - @Test - public void containsValueWithKey2() { - //arrange - Dictionary dictionary = new Dictionary<>(); - boolean expectedValue = false; - boolean returnedValue; - //act - dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); - returnedValue = dictionary.containsValueWithKey("job"); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of containsValueWithKey method, of class Dictionary. - */ - @Test - public void containsValueWithKey3() { - //arrange - Dictionary dictionary = new Dictionary<>(); - boolean expectedValue = true; - boolean returnedValue; - //act - dictionary.addValue("name", "John"); - returnedValue = dictionary.containsValueWithKey("name"); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of addValue method, of class Dictionary. - */ - @Test - public void testAddValue() { - //arrange - Dictionary dictionary = new Dictionary<>(); - String expectedString = "Johny"; - String returnedString; - //act - dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); - dictionary.removeValue("surname"); - returnedString = dictionary.getValue("nick"); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of addValue method, of class Dictionary. - */ - @Test - public void testAddValue2() { - //arrang - Dictionary dictionary = new Dictionary<>(); - String expectedString = "Johny"; - String returnedString; - //act - dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); - dictionary.removeValue("name"); - returnedString = dictionary.getValue("nick"); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of addValue method, of class Dictionary. - */ - @Test - public void testAddValue3() { - //arrange - Dictionary dictionary = new Dictionary<>(); - String expectedString = "Black"; - String returnedString; - //act - dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); - dictionary.removeValue("nick"); - returnedString = dictionary.getValue("surname"); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of getValue method, of class Dictionary. - */ - @Test - public void testGetValue() { - //arrange - Dictionary dictionary = new Dictionary<>(); - String expectedString = "Black"; - String returnedString; - //act - dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); - dictionary.removeValue("name"); - returnedString = dictionary.getValue("surname"); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of getValue method, of class Dictionary. - */ - @Test - public void testGetValue2() { - //arrange - Dictionary dictionary = new Dictionary<>(); - String expectedString = "Johny"; - String returnedString; - //act - dictionary.addValue("nick", "Johny"); - returnedString = dictionary.getValue("nick"); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of updateValue method, of class Dictionary. - */ - @Test - public void testUpdateValue() { - //arrange - Dictionary dictionary = new Dictionary<>(); - String expectedString = "Blue"; - String returnedString; - //act - dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); - dictionary.updateValue("surname", "Blue"); - returnedString = dictionary.getValue("surname"); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of removeValue method, of class Dictionary. - */ - @Test - public void testRemoveValue() { - //arrange - boolean isExceptionThrown = false; - Dictionary dictionary = new Dictionary<>(); - String expectedString = "Black"; - String returnedString; - dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); - dictionary.removeValue("surname"); - //act - try { - returnedString = dictionary.getValue("surname"); - } catch (PowerRuntimeException e) { - isExceptionThrown = true; - } - //assert - if (!isExceptionThrown) { - fail("There should be thrown PowerRuntimeException"); - } - } - - /** - * Test of getKeyIterator method, of class Dictionary. - */ - @Test - public void testGetKeyIterator() { - //arrange - Dictionary dictionary = new Dictionary<>(); - DictionaryKeyIterator dictionaryKeyIterator; - String expectedString = "Johny"; - String returnedString; - String secondKey; - dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); - dictionary.removeValue("surname"); - dictionaryKeyIterator = dictionary.getKeyIterator(); - //act - dictionaryKeyIterator.getNextKey(); - secondKey = dictionaryKeyIterator.getNextKey(); - returnedString = dictionary.getValue(secondKey); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of toString method, of class Dictionary. - */ - @Test - public void testToString() { - //arrange - Dictionary dictionary = new Dictionary<>(); - String expectedString = "name:John\nsurname:Black\nnick:Johny\n"; - String returnedString; - //act - dictionary.addValue("name", "John").addValue("surname", "Black").addValue("nick", "Johny"); - returnedString = dictionary.toString(); - //assert - assertEquals(expectedString, returnedString); - } - -} diff --git a/src/test/java/org/nanoboot/powerframework/datetime/DurationTest.java b/src/test/java/org/nanoboot/powerframework/datetime/DurationTest.java deleted file mode 100644 index c5e73c9..0000000 --- a/src/test/java/org/nanoboot/powerframework/datetime/DurationTest.java +++ /dev/null @@ -1,878 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.datetime; - -import org.nanoboot.powerframework.PowerRuntimeException; -import org.junit.Test; -import static org.junit.Assert.*; - -/** - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org - */ -public class DurationTest { - - /** - * - */ - public DurationTest() { - } - - /** - * Test of constructor, of class Duration. - */ - @Test - public void TestDuration_5Args_ThereShouldBeThrownNoPowerRuntimeException() { - //arrange - boolean isExceptionThrown = false; - //act - try { - Duration duration = new Duration(23, 5, 3, 43, 97); - } catch (PowerRuntimeException e) { - isExceptionThrown = true; - } - //assert - if (isExceptionThrown) { - fail("There should be thrown no PowerRuntimeException"); - } - } - - /** - * Test of constructor, of class Duration. - */ - @Test - public void TestDuration_5Args_ThereShouldBeThrownPowerRuntimeException() { - //arrange - boolean isExceptionThrown = false; - //act - try { - Duration duration = new Duration(23, 5, 3, 143, 97); - } catch (PowerRuntimeException e) { - isExceptionThrown = true; - } - //assert - if (!isExceptionThrown) { - fail("There should be thrown PowerRuntimeException"); - } - } - - /** - * Test of constructor, of class Duration. - */ - @Test - public void TestDuration_5Args_ThereShouldBeReturnedIsPositive() { - //arrange - boolean expectedValue = true; - boolean returnedValue; - Duration duration = new Duration(23, 5, 3, 43, 97); - //act - returnedValue = duration.isPositive(); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of constructor, of class Duration. - */ - @Test - public void TestDuration_6Args_ThereShouldBeReturnedIsPositive() { - //arrange - boolean expectedValue = true; - boolean returnedValue; - Duration duration = new Duration(true, 23, 5, 3, 43, 97); - //act - returnedValue = duration.isPositive(); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of constructor, of class Duration. - */ - @Test - public void TestDuration_6Args_ThereShouldBeReturnedIsNotPositive() { - //arrange - boolean expectedValue = false; - boolean returnedValue; - Duration duration = new Duration(false, 23, 5, 3, 43, 97); - //act - returnedValue = duration.isPositive(); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of constructor, of class Duration. - */ - @Test - public void TestDuration_StringArg() { - //arrange - String argString = "+00023:05:03:43:097"; - String expectedString = "+23:5:3:43:97"; - String returnedString; - - Duration duration = new Duration(argString); - //act - returnedString = duration.toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of constructor, of class Duration. - */ - @Test - public void TestDuration_StringArg_ThereShouldBeThrownPowerRuntimeException() { - //arrange - boolean isExceptionThrown = false; - //act - try { - String argString = "+23:5:60:43:97"; - Duration duration = new Duration(argString); - } catch (PowerRuntimeException e) { - isExceptionThrown = true; - } - //assert - if (!isExceptionThrown) { - fail("There should be thrown PowerRuntimeException"); - } - } - - /** - * Test of between method, of class Duration. - */ - @Test - public void testBetween1_UniversalDateTime_UniversalDateTime() { - //arrange - UniversalDateTime startUniversalDateTime = new UniversalDateTime(1949, 8, 6, 4, 23, 7, 654); - UniversalDateTime endUniversalDateTime = new UniversalDateTime(2007, 4, 21, 9, 17, 58, 954); - String expectedString = "+21077:4:54:51:300"; - String returnedString; - //act - returnedString = Duration.between(startUniversalDateTime, endUniversalDateTime).toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of between method, of class Duration. - */ - @Test - public void testBetween2_UniversalDateTime_UniversalDateTime() { - //arrange - UniversalDateTime startUniversalDateTime = new UniversalDateTime(2007, 4, 21, 9, 17, 58, 954); - UniversalDateTime endUniversalDateTime = new UniversalDateTime(1949, 8, 6, 4, 23, 7, 654); - String expectedString = "-21077:4:54:51:300"; - String returnedString; - //act - returnedString = Duration.between(startUniversalDateTime, endUniversalDateTime).toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of between method, of class Duration. - */ - @Test - public void testBetween1_ZonedDateTime_ZonedDateTime() { - //arrange - LocalDateTime localDateTime = new LocalDateTime(2016, 10, 29, 11, 19, 34, 276); - ZonedDateTime startZonedDateTime = new ZonedDateTime(localDateTime, new TimeZone("Europe/Prague")); - ZonedDateTime endZonedDateTime = new ZonedDateTime(localDateTime, new TimeZone("Australia/Sydney")); - String expectedString = "-0:9:0:0:0"; - String returnedString; - //act - returnedString = Duration.between(startZonedDateTime, endZonedDateTime).toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of between method, of class Duration. - */ - @Test - public void testBetween2_ZonedDateTime_ZonedDateTime() { - //arrange - LocalDateTime localDateTime = new LocalDateTime(2016, 10, 29, 11, 19, 34, 276); - ZonedDateTime startZonedDateTime = new ZonedDateTime(localDateTime, new TimeZone("Australia/Sydney")); - ZonedDateTime endZonedDateTime = new ZonedDateTime(localDateTime, new TimeZone("Europe/Prague")); - String expectedString = "+0:9:0:0:0"; - String returnedString; - //act - returnedString = Duration.between(startZonedDateTime, endZonedDateTime).toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of ofDays method, of class Duration. - */ - @Test - public void testOfDays() { - //arrange - int days = 13; - - Duration duration = Duration.ofDays(days); - String expectedString = "+13:0:0:0:0"; - String returnedString; - //act - returnedString = duration.toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of ofHours method, of class Duration. - */ - @Test - public void testOfHours() { - //arrange - int hours = 17; - - Duration duration = Duration.ofHours(hours); - String expectedString = "+0:17:0:0:0"; - String returnedString; - //act - returnedString = duration.toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of ofMinutes method, of class Duration. - */ - @Test - public void testOfMinutes() { - //arrange - int minutes = 42; - - Duration duration = Duration.ofMinutes(minutes); - String expectedString = "+0:0:42:0:0"; - String returnedString; - //act - returnedString = duration.toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of ofSeconds method, of class Duration. - */ - @Test - public void testOfSeconds() { - //arrange - int seconds = 9; - - Duration duration = Duration.ofSeconds(seconds); - String expectedString = "+0:0:0:9:0"; - String returnedString; - //act - returnedString = duration.toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of ofMilliseconds method, of class Duration. - */ - @Test - public void testOfMilliseconds() { - //arrange - int milliseconds = 4; - - Duration duration = Duration.ofMilliseconds(milliseconds); - String expectedString = "+0:0:0:0:4"; - String returnedString; - //act - returnedString = duration.toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of fromUniversalDateTimePlusDurationCreateNewUniversalDateTime - * method, of class Duration. - */ - @Test - public void testFromUniversalDateTimePlusDurationCreateNewUniversalDateTime() { - //arrange - UniversalDateTime universalDateTime = new UniversalDateTime(2007, 4, 21, 9, 17, 58, 954); - Duration duration = Duration.ofHours(7); - String expectedString = "2007-04-21 16:17:58:954"; - String returnedString; - //act - returnedString = Duration.fromUniversalDateTimePlusDurationCreateNewUniversalDateTime(universalDateTime, duration).toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of fromUniversalDateTimeMinusDurationCreateNewUniversalDateTime - * method, of class Duration. - */ - @Test - public void testFromUniversalDateTimeMinusDurationCreateNewUniversalDateTime() { - //arrange - UniversalDateTime universalDateTime = new UniversalDateTime(2007, 4, 21, 9, 17, 58, 954); - Duration duration = Duration.ofHours(7); - String expectedString = "2007-04-21 02:17:58:954"; - String returnedString; - //act - returnedString = Duration.fromUniversalDateTimeMinusDurationCreateNewUniversalDateTime(universalDateTime, duration).toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of fromZonedDateTimePlusDurationCreateNewZonedDateTime method, of - * class Duration. - */ - @Test - public void testFromZonedDateTimePlusDurationCreateNewZonedDateTime() { - //arrange - LocalDateTime localDateTime = new LocalDateTime(2007, 4, 21, 9, 17, 58, 954); - TimeZone timeZone = new TimeZone("Australia/Sydney"); - ZonedDateTime zonedDateTime = new ZonedDateTime(localDateTime, timeZone); - Duration duration = Duration.ofHours(7); - String expectedString = "2007-04-21 16:17:58:954"; - String returnedString; - //act - returnedString = Duration.fromZonedDateTimePlusDurationCreateNewZonedDateTime(zonedDateTime, duration).toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of fromZonedDateTimeMinusDurationCreateNewZonedDateTime method, of - * class Duration. - */ - @Test - public void testFromZonedDateTimeMinusDurationCreateNewZonedDateTime() { - //arrange - LocalDateTime localDateTime = new LocalDateTime(2007, 4, 21, 9, 17, 58, 954); - TimeZone timeZone = new TimeZone("Australia/Sydney"); - ZonedDateTime zonedDateTime = new ZonedDateTime(localDateTime, timeZone); - Duration duration = Duration.ofHours(7); - String expectedString = "2007-04-21 02:17:58:954"; - String returnedString; - //act - returnedString = Duration.fromZonedDateTimeMinusDurationCreateNewZonedDateTime(zonedDateTime, duration).toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of getDays method, of class Duration. - */ - @Test - public void testGetDays() { - //arrange - Duration duration = new Duration(23, 5, 3, 43, 97); - long expectedDays = 23; - long returnedDays; - //act - returnedDays = duration.getDays(); - //assert - assertEquals(expectedDays, returnedDays); - } - - /** - * Test of getHours method, of class Duration. - */ - @Test - public void testGetHours() { - //arrange - Duration duration = new Duration(23, 5, 3, 43, 97); - int expectedHours = 5; - int returnedHours; - //act - returnedHours = duration.getHours(); - //assert - assertEquals(expectedHours, returnedHours); - } - - /** - * Test of getMinutes method, of class Duration. - */ - @Test - public void testGetMinutes() { - //arrange - Duration duration = new Duration(23, 5, 3, 43, 97); - int expectedMinutes = 3; - int returnedMinutes; - //act - returnedMinutes = duration.getMinutes(); - //assert - assertEquals(expectedMinutes, returnedMinutes); - } - - /** - * Test of getSeconds method, of class Duration. - */ - @Test - public void testGetSeconds() { - //arrange - Duration duration = new Duration(23, 5, 3, 43, 97); - int expectedSeconds = 43; - int returnedSeconds; - //act - returnedSeconds = duration.getSeconds(); - //assert - assertEquals(expectedSeconds, returnedSeconds); - } - - /** - * Test of getMilliseconds method, of class Duration. - */ - @Test - public void testGetMilliseconds() { - //arrange - Duration duration = new Duration(23, 5, 3, 43, 97); - int expectedMilliseconds = 97; - int returnedMilliseconds; - //act - returnedMilliseconds = duration.getMilliseconds(); - //assert - assertEquals(expectedMilliseconds, returnedMilliseconds); - } - - /** - * Test of isPositive method, of class Duration. - */ - @Test - public void testIsPositive() { - //arrange - Duration duration = new Duration(false, 23, 5, 3, 43, 97); - boolean expectedValue = false; - boolean returnedValue; - //act - returnedValue = duration.isPositive(); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of negated method, of class Duration. - */ - @Test - public void testNegated() { - //arrange - Duration duration = new Duration(23, 5, 3, 43, 97); - Duration negatedDuration; - - boolean expectedValue = false; - boolean returnedValue; - //act - negatedDuration = duration.negated(); - returnedValue = negatedDuration.isPositive(); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of abs method, of class Duration. - */ - @Test - public void testAbs() { - //arrange - Duration duration = new Duration(false, 23, 5, 3, 43, 97); - Duration absDuration; - - boolean expectedValue = true; - boolean returnedValue; - //act - absDuration = duration.abs(); - returnedValue = absDuration.isPositive(); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of plusDuration method, of class Duration. - */ - @Test - public void testPlusDuration() { - //arrange - Duration duration = new Duration(12, 0, 0, 0, 0); - Duration durationToAdd = new Duration(0, 5, 4, 2, 7); - Duration returnedDuration; - String expectedString = "+12:5:4:2:7"; - String returnedString; - - //act - returnedDuration = duration.plusDuration(durationToAdd); - returnedString = returnedDuration.toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of plusDays method, of class Duration. - */ - @Test - public void testPlusDays() { - //arrange - Duration duration = new Duration(12, 0, 0, 0, 0); - long daysToAdd = 1; - Duration returnedDuration; - String expectedString = "+13:0:0:0:0"; - String returnedString; - - //act - returnedDuration = duration.plusDays(daysToAdd); - returnedString = returnedDuration.toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of plusHours method, of class Duration. - */ - @Test - public void testPlusHours() { - //arrange - Duration duration = new Duration(12, 0, 0, 0, 0); - int hoursToAdd = 1; - Duration returnedDuration; - String expectedString = "+12:1:0:0:0"; - String returnedString; - - //act - returnedDuration = duration.plusHours(hoursToAdd); - returnedString = returnedDuration.toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of plusMinutes method, of class Duration. - */ - @Test - public void testPlusMinutes() { - //arrange - Duration duration = new Duration(12, 0, 0, 0, 0); - int minutesToAdd = 1; - Duration returnedDuration; - String expectedString = "+12:0:1:0:0"; - String returnedString; - - //act - returnedDuration = duration.plusMinutes(minutesToAdd); - returnedString = returnedDuration.toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of plusSeconds method, of class Duration. - */ - @Test - public void testPlusSeconds() { - //arrange - Duration duration = new Duration(12, 0, 0, 0, 0); - int secondsToAdd = 1; - Duration returnedDuration; - String expectedString = "+12:0:0:1:0"; - String returnedString; - - //act - returnedDuration = duration.plusSeconds(secondsToAdd); - returnedString = returnedDuration.toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of plusMilliseconds method, of class Duration. - */ - @Test - public void testPlusMilliseconds() { - //arrange - Duration duration = new Duration(12, 0, 0, 0, 0); - int millisecondsToAdd = 1; - Duration returnedDuration; - String expectedString = "+12:0:0:0:1"; - String returnedString; - - //act - returnedDuration = duration.plusMilliseconds(millisecondsToAdd); - returnedString = returnedDuration.toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of minusDuration method, of class Duration. - */ - @Test - public void testMinusDuration() { - //arrange - Duration duration = new Duration(12, 5, 4, 2, 7); - Duration durationToSubtract = new Duration(0, 5, 4, 2, 7); - Duration returnedDuration; - String expectedString = "+12:0:0:0:0"; - String returnedString; - - //act - returnedDuration = duration.minusDuration(durationToSubtract); - returnedString = returnedDuration.toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of minusDays method, of class Duration. - */ - @Test - public void testMinusDays() { - //arrange - Duration duration = new Duration(12, 5, 4, 2, 7); - long daysToSubtract = 1; - Duration returnedDuration; - String expectedString = "+11:5:4:2:7"; - String returnedString; - - //act - returnedDuration = duration.minusDays(daysToSubtract); - returnedString = returnedDuration.toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of minusHours method, of class Duration. - */ - @Test - public void testMinusHours() { - //arrange - Duration duration = new Duration(12, 5, 4, 2, 7); - int hoursToSubtract = 1; - Duration returnedDuration; - String expectedString = "+12:4:4:2:7"; - String returnedString; - - //act - returnedDuration = duration.minusHours(hoursToSubtract); - returnedString = returnedDuration.toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of minusMinutes method, of class Duration. - */ - @Test - public void testMinusMinutes() { - //arrange - Duration duration = new Duration(12, 5, 4, 2, 7); - int minutesToSubtract = 1; - Duration returnedDuration; - String expectedString = "+12:5:3:2:7"; - String returnedString; - - //act - returnedDuration = duration.minusMinutes(minutesToSubtract); - returnedString = returnedDuration.toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of minusSeconds method, of class Duration. - */ - @Test - public void testMinusSeconds() { - //arrange - Duration duration = new Duration(12, 5, 4, 2, 7); - int secondsToSubtract = 1; - Duration returnedDuration; - String expectedString = "+12:5:4:1:7"; - String returnedString; - - //act - returnedDuration = duration.minusSeconds(secondsToSubtract); - returnedString = returnedDuration.toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of minusMilliseconds method, of class Duration. - */ - @Test - public void testMinusMilliseconds() { - //arrange - Duration duration = new Duration(12, 5, 4, 2, 7); - int millisecondsToSubtract = 1; - Duration returnedDuration; - String expectedString = "+12:5:4:2:6"; - String returnedString; - - //act - returnedDuration = duration.minusMilliseconds(millisecondsToSubtract); - returnedString = returnedDuration.toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of toTotalDays method, of class Duration. - */ - @Test - public void testToTotalDays() { - //arrange - Duration duration = new Duration(14, 9, 17, 53, 834); - long expectedValue = 14; - long returnedValue; - //act - returnedValue = (long) Math.floor(duration.toTotalDays()); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of toTotalHours method, of class Duration. - */ - @Test - public void testToTotalHours() { - //arrange - Duration duration = new Duration(14, 9, 17, 53, 834); - long expectedValue = 345; - long returnedValue; - //act - returnedValue = (long) Math.floor(duration.toTotalHours()); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of toTotalMinutes method, of class Duration. - */ - @Test - public void testToTotalMinutes() { - //arrange - Duration duration = new Duration(14, 9, 17, 53, 834); - long expectedValue = 20717; - long returnedValue; - //act - returnedValue = (long) Math.floor(duration.toTotalMinutes()); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of toTotalSeconds method, of class Duration. - */ - @Test - public void testToTotalSeconds() { - //arrange - Duration duration = new Duration(14, 9, 17, 53, 834); - long expectedValue = 1243073; - long returnedValue; - //act - returnedValue = (long) Math.floor(duration.toTotalSeconds()); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of toTotalMilliseconds method, of class Duration. - */ - @Test - public void testToTotalMilliseconds() { - //arrange - Duration duration = new Duration(14, 9, 17, 53, 834); - long expectedValue = 1243073834; - long returnedValue; - //act - returnedValue = (long) Math.floor(duration.toTotalMilliseconds()); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of toJavaDuration method, of class Duration. - */ - @Test - public void testToJavaDuration() { - //arrange - Duration duration = new Duration(14, 9, 17, 53, 834); - long expectedTotalSeconds = (long) Math.floor(duration.toTotalSeconds()); - long returnedSeconds; - java.time.Duration javaDuration; - //act - javaDuration = duration.toJavaDuration(); - returnedSeconds = javaDuration.getSeconds(); - //assert - assertEquals(expectedTotalSeconds, returnedSeconds); - } - - /** - * Test of toString method, of class Duration. - */ - @Test - public void testToString1_ConstructorWithLongArgUsed() { - //arrange - String expectedString = "+23:5:3:43:97"; - String returnedString; - long countOfTotalMilliseconds = 2005423097; - - Duration duration = new Duration(countOfTotalMilliseconds); - //act - returnedString = duration.toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of toString method, of class Duration. - */ - @Test - public void testToString2_ConstructorWithLongArgUsed() { - //arrange - String expectedString = "-23:5:3:43:97"; - String returnedString; - long countOfTotalMilliseconds = -2005423097; - - Duration duration = new Duration(countOfTotalMilliseconds); - //act - returnedString = duration.toString(); - //assert - assertEquals(expectedString, returnedString); - } - - /** - * Test of toString method, of class Duration. - */ - @Test - public void testToString3_ConstructorWithLongArgUsed() { - //arrange - String expectedString = "+0:0:0:0:0"; - String returnedString; - long countOfTotalMilliseconds = 0; - - Duration duration = new Duration(countOfTotalMilliseconds); - //act - returnedString = duration.toString(); - //assert - assertEquals(expectedString, returnedString); - } -} diff --git a/src/test/java/org/nanoboot/powerframework/datetime/LocalDateTimeTest.java b/src/test/java/org/nanoboot/powerframework/datetime/LocalDateTimeTest.java deleted file mode 100644 index 3f1bd80..0000000 --- a/src/test/java/org/nanoboot/powerframework/datetime/LocalDateTimeTest.java +++ /dev/null @@ -1,166 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.datetime; - -import org.junit.Test; -import static org.junit.Assert.*; - -/** - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org - */ -public class LocalDateTimeTest { - - /** - * - */ - public LocalDateTimeTest() { - } - - /** - * Test of constructor of class LocalDateTime. (String dateTimeInString) - */ - @Test - public void testLocalDateTime_1argString_day6MustBeReturned() { - //arrange - LocalDateTime localDateTime; - int expectedDay = 6; - int returnedDay; - //act - localDateTime = new LocalDateTime("1994-05-06 21:45:06:032"); - returnedDay = localDateTime.getDay(); - //assert - assertEquals(expectedDay, returnedDay); - } - - /** - * Test of constructor of class LocalDateTime. (int year, int month, int - * day, int hour24Format, int minute, int second, int millisecond) - */ - @Test - public void testLocalDateTime_7args_day6MustBeReturned() { - //arrange - LocalDateTime localDateTime; - int expectedDay = 6; - int returnedDay; - //act - localDateTime = new LocalDateTime(1994, 5, 6, 21, 45, 6, 32); - returnedDay = localDateTime.getDay(); - //assert - assertEquals(expectedDay, returnedDay); - } - - /** - * Test of constructor of class LocalDateTime. (UniversalDateTime - * universalDateTime) - */ - @Test - public void testLocalDateTime_1argUniversalDateTime_day6MustBeReturned() { - //arrange - LocalDateTime localDateTime; - UniversalDateTime universalDateTime; - int expectedDay = 6; - int returnedDay; - //act - universalDateTime = new UniversalDateTime(1994, 5, 6, 21, 45, 6, 32); - localDateTime = new LocalDateTime(universalDateTime); - returnedDay = localDateTime.getDay(); - //assert - assertEquals(expectedDay, returnedDay); - } - - /** - * Test of constructor of class LocalDateTime. (ZonedDateTime zonedDateTime) - */ - @Test - public void testLocalDateTime_1argZonedDateTime_day6MustBeReturned() { - //arrange - LocalDateTime localDateTime; - TimeZone timeZone; - ZonedDateTime zonedDateTime; - int expectedDay = 6; - int returnedDay; - //act - timeZone = new TimeZone("Australia/Sydney"); - zonedDateTime = new ZonedDateTime(new LocalDateTime(1994, 5, 6, 21, 45, 6, 32), timeZone); - localDateTime = new LocalDateTime(zonedDateTime); - returnedDay = localDateTime.getDay(); - //assert - assertEquals(expectedDay, returnedDay); - } - - /** - * Test of toUniversalDateTime method, of class LocalDateTime. - */ - @Test - public void testToUniversalDateTime() { - //arrange - LocalDateTime localDateTime; - UniversalDateTime universalDateTime; - int expectedDay = 6; - int returnedDay; - //act - localDateTime = new LocalDateTime(1994, 5, 6, 21, 45, 6, 32); - universalDateTime = localDateTime.toUniversalDateTime(); - returnedDay = universalDateTime.getDay(); - //assert - assertEquals(expectedDay, returnedDay); - } - - /** - * Test of toZonedDateTime method, of class LocalDateTime. - */ - @Test - public void testToZonedDateTime() { - //arrange - LocalDateTime localDateTime; - TimeZone timeZone; - ZonedDateTime zonedDateTime; - int expectedDay = 6; - int returnedDay; - //act - timeZone = new TimeZone("Australia/Sydney"); - localDateTime = new LocalDateTime(1994, 5, 6, 21, 45, 6, 32); - zonedDateTime = localDateTime.toZonedDateTime(timeZone); - returnedDay = zonedDateTime.getDay(); - //assert - assertEquals(expectedDay, returnedDay); - } - - /** - * Test of toJavaLocalDateTime method, of class LocalDateTime. - */ - @Test - public void testToJavaLocalDateTime() { - //arrange - LocalDateTime localDateTime; - java.time.LocalDateTime javaLocalDateTime; - int expectedDay = 6; - int returnedDay; - //act - localDateTime = new LocalDateTime(1994, 5, 6, 21, 45, 6, 32); - javaLocalDateTime = localDateTime.toJavaLocalDateTime(); - returnedDay = javaLocalDateTime.getDayOfMonth(); - //assert - assertEquals(expectedDay, returnedDay); - } - -} diff --git a/src/test/java/org/nanoboot/powerframework/datetime/TimeUnitsValidatorTest.java b/src/test/java/org/nanoboot/powerframework/datetime/TimeUnitsValidatorTest.java deleted file mode 100644 index 9a525ed..0000000 --- a/src/test/java/org/nanoboot/powerframework/datetime/TimeUnitsValidatorTest.java +++ /dev/null @@ -1,288 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.datetime; - -import org.nanoboot.powerframework.PowerRuntimeException; -import org.junit.Test; -import static org.junit.Assert.*; - -/** - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org - */ -public class TimeUnitsValidatorTest { - - /** - * - */ - public TimeUnitsValidatorTest() { - } - - /** - * Test of isHourValid method, of class TimeUnitsValidator. - */ - @Test - public void testIsHourValid_HourIs13_ThereShouldBeReturnedTrue() { - //arrange - int hour = 13; - boolean returnedValue; - //act - returnedValue = TimeUnitsValidator.isHourValid(hour); - //assert - assertTrue(returnedValue); - } - - /** - * Test of isHourValid method, of class TimeUnitsValidator. - */ - @Test - public void testIsHourValid_HourIsMinus1_ThereShouldBeReturneFalse() { - //arrange - int hour = -1; - boolean returnedValue; - //act - returnedValue = TimeUnitsValidator.isHourValid(hour); - //assert - assertFalse(returnedValue); - } - - /** - * Test of isHourValid method, of class TimeUnitsValidator. - */ - @Test - public void testIsHourValid_HourIs24_ThereShouldBeReturneFalse() { - //arrange - int hour = 24; - boolean returnedValue; - //act - returnedValue = TimeUnitsValidator.isHourValid(hour); - //assert - assertFalse(returnedValue); - } - - /** - * Test of isMinuteValid method, of class TimeUnitsValidator. - */ - @Test - public void testIsMinuteValid_MinuteIs34__ThereShouldBeReturnedTrue() { - //arrange - int minute = 34; - boolean returnedValue; - //act - returnedValue = TimeUnitsValidator.isMinuteValid(minute); - //assert - assertTrue(returnedValue); - } - - /** - * Test of isMinuteValid method, of class TimeUnitsValidator. - */ - @Test - public void testIsMinuteValid_MinuteIsMinus1_ThereShouldBeReturneFalse() { - //arrange - int minute = -1; - boolean returnedValue; - //act - returnedValue = TimeUnitsValidator.isMinuteValid(minute); - //assert - assertFalse(returnedValue); - } - - /** - * Test of isMinuteValid method, of class TimeUnitsValidator. - */ - @Test - public void testIsMinuteValid_MinuteIs60_ThereShouldBeReturneFalse() { - //arrange - int minute = 60; - boolean returnedValue; - //act - returnedValue = TimeUnitsValidator.isMinuteValid(minute); - //assert - assertFalse(returnedValue); - } - - /** - * Test of isSecondValid method, of class TimeUnitsValidator. - */ - @Test - public void testIsSecondValid_SecondIs46__ThereShouldBeReturnedTrue() { - //arrange - int second = 46; - boolean returnedValue; - //act - returnedValue = TimeUnitsValidator.isSecondValid(second); - //assert - assertTrue(returnedValue); - } - - /** - * Test of isSecondValid method, of class TimeUnitsValidator. - */ - @Test - public void testIsSecondValid_SecondIsMinus1__ThereShouldBeReturneFalse() { - //arrange - int second = -1; - boolean returnedValue; - //act - returnedValue = TimeUnitsValidator.isSecondValid(second); - //assert - assertFalse(returnedValue); - } - - /** - * Test of isSecondValid method, of class TimeUnitsValidator. - */ - @Test - public void testIsSecondValid_SecondIs60__ThereShouldBeReturneFalse() { - //arrange - int second = 60; - boolean returnedValue; - //act - returnedValue = TimeUnitsValidator.isSecondValid(second); - //assert - assertFalse(returnedValue); - } - - /** - * Test of isMillisecondValid method, of class TimeUnitsValidator. - */ - @Test - public void testIsMillisecondValid_MillisecondIs843__ThereShouldBeReturnedTrue() { - //arrange - int millisecond = 843; - boolean returnedValue; - //act - returnedValue = TimeUnitsValidator.isMillisecondValid(millisecond); - //assert - assertTrue(returnedValue); - } - - /** - * Test of isMillisecondValid method, of class TimeUnitsValidator. - */ - @Test - public void testIsMillisecondValid_MillisecondIsMinus1_ThereShouldBeReturneFalse() { - //arrange - int millisecond = -1; - boolean returnedValue; - //act - returnedValue = TimeUnitsValidator.isMillisecondValid(millisecond); - //assert - assertFalse(returnedValue); - } - - /** - * Test of isMillisecondValid method, of class TimeUnitsValidator. - */ - @Test - public void testIsMillisecondValid_MillisecondIs1000_ThereShouldBeReturneFalse() { - //arrange - int millisecond = 1000; - boolean returnedValue; - //act - returnedValue = TimeUnitsValidator.isMillisecondValid(millisecond); - //assert - assertFalse(returnedValue); - } - - /** - * Test of areAllTimeUnitsValid method, of class TimeUnitsValidator. - */ - @Test - public void testAreAllTimeUnitsValid_ThereShouldBeReturneTrue() { - //arrange - int hour = 2; - int minute = 34; - int second = 23; - int millisecond = 428; - boolean returnedValue; - //act - returnedValue = TimeUnitsValidator.areAllTimeUnitsValid(hour, minute, second, millisecond); - //assert - assertTrue(returnedValue); - } - - /** - * Test of areAllTimeUnitsValid method, of class TimeUnitsValidator. - */ - @Test - public void testAreAllTimeUnitsValid_ThereShouldBeReturneFalse() { - //arrange - int hour = 112; - int minute = 134; - int second = 123; - int millisecond = 1428; - boolean returnedValue; - //act - returnedValue = TimeUnitsValidator.areAllTimeUnitsValid(hour, minute, second, millisecond); - //assert - assertFalse(returnedValue); - } - - /** - * Test of checkInputValuesForTimeAndIfThereIsAnInvalidOneThrowException - * method, of class TimeUnitsValidator. - */ - @Test - public void testCheckInputValuesForTimeAndIfThereIsAnInvalidOneThrowException_ThereShouldBeThrownNoPowerRuntimeException() { - //arrange - int hour = 12; - int minute = 34; - int second = 23; - int millisecond = 428; - boolean isExceptionThrown = false; - //act - try { - TimeUnitsValidator.checkInputValuesForTimeAndIfThereIsAnInvalidOneThrowException(hour, minute, second, millisecond); - } catch (PowerRuntimeException e) { - isExceptionThrown = true; - } - //assert - if (isExceptionThrown) { - fail("There should be thrown no PowerRuntimeException"); - } - } - - /** - * Test of checkInputValuesForTimeAndIfThereIsAnInvalidOneThrowException - * method, of class TimeUnitsValidator. - */ - @Test - public void testCheckInputValuesForTimeAndIfThereIsAnInvalidOneThrowException_ThereShouldBeThrownPowerRuntimeException() { - //arrange - int hour = 112; - int minute = 134; - int second = 123; - int millisecond = 1428; - boolean isExceptionThrown = false; - //act - try { - TimeUnitsValidator.checkInputValuesForTimeAndIfThereIsAnInvalidOneThrowException(hour, minute, second, millisecond); - } catch (PowerRuntimeException e) { - isExceptionThrown = true; - } - //assert - if (!isExceptionThrown) { - fail("There should be thrown PowerRuntimeException"); - } - } -} diff --git a/src/test/java/org/nanoboot/powerframework/datetime/UniversalDateTimeTest.java b/src/test/java/org/nanoboot/powerframework/datetime/UniversalDateTimeTest.java deleted file mode 100644 index 9b55a3b..0000000 --- a/src/test/java/org/nanoboot/powerframework/datetime/UniversalDateTimeTest.java +++ /dev/null @@ -1,148 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.datetime; - -import org.junit.Test; -import static org.junit.Assert.*; - -/** - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org - */ -public class UniversalDateTimeTest { - - /** - * - */ - public UniversalDateTimeTest() { - } - - /** - * Test of constructor of class UniversalDateTime. (String dateTimeInString) - */ - @Test - public void testUniversalDateTime_1argString_day6MustBeReturned() { - //arrange - UniversalDateTime universalDateTime; - int expectedDay = 6; - int returnedDay; - //act - universalDateTime = new UniversalDateTime("1994-05-06 21:45:06:032"); - returnedDay = universalDateTime.getDay(); - //assert - assertEquals(expectedDay, returnedDay); - } - - /** - * Test of constructor of class UniversalDateTime. (int year, int month, int - * day, int hour24Format, int minute, int second, int millisecond) - */ - @Test - public void testUniversalDateTime_7args_day6MustBeReturned() { - //arrange - UniversalDateTime universalDateTime; - int expectedDay = 6; - int returnedDay; - //act - universalDateTime = new UniversalDateTime(1994, 5, 6, 21, 45, 6, 32); - returnedDay = universalDateTime.getDay(); - //assert - assertEquals(expectedDay, returnedDay); - } - - /** - * Test of constructor of class UniversalDateTime. (ZonedDateTime - * zonedDateTime) - */ - @Test - public void testUniversalDateTime_1argZonedDateTime_day6MustBeReturned() { - //arrange - UniversalDateTime universalDateTime; - TimeZone timeZone; - ZonedDateTime zonedDateTime; - int expectedDay = 5; - int returnedDay; - //act - timeZone = new TimeZone("Australia/Sydney"); - zonedDateTime = new ZonedDateTime(new LocalDateTime(1994, 5, 6, 21, 45, 6, 32), timeZone); - universalDateTime = new UniversalDateTime(zonedDateTime); - returnedDay = universalDateTime.getMonth(); - //assert - assertEquals(expectedDay, returnedDay); - } - - /** - * Test of constructor of class UniversalDateTime. (LocalDateTime - * localDateTime) - */ - @Test - public void testUniversalDateTime_1argLocalDateTime_day6MustBeReturned() { - //arrange - UniversalDateTime universalDateTime; - LocalDateTime localDateTime; - int expectedDay = 6; - int returnedDay; - //act - localDateTime = new LocalDateTime(1994, 5, 6, 21, 45, 6, 32); - universalDateTime = new UniversalDateTime(localDateTime); - - returnedDay = localDateTime.getDay(); - //assert - assertEquals(expectedDay, returnedDay); - } - - /** - * Test of toZonedDateTime method, of class LocalDateTime. - */ - @Test - public void testToZonedDateTime() { - //arrange - UniversalDateTime universalDateTime; - ZonedDateTime zonedDateTime; - int expectedMonth = 5; - int returnedMonth; - //act - universalDateTime = new UniversalDateTime(1994, 5, 6, 21, 45, 6, 32); - zonedDateTime = universalDateTime.toZonedDateTime(); - returnedMonth = zonedDateTime.getMonth(); - //assert - assertEquals(expectedMonth, returnedMonth); - } - - /** - * Test of testToLocalDateTime method, of class LocalDateTime. - */ - @Test - public void testToLocalDateTime() { - //arrange - UniversalDateTime universalDateTime; - LocalDateTime localDateTime; - - int expectedMonth = 5; - int returnedMonth; - //act - universalDateTime = new UniversalDateTime(1994, 5, 6, 21, 45, 6, 32); - localDateTime = universalDateTime.toLocalDateTime(); - returnedMonth = universalDateTime.getMonth(); - //assert - assertEquals(expectedMonth, returnedMonth); - } -} diff --git a/src/test/java/org/nanoboot/powerframework/datetime/ZonedDateTimeTest.java b/src/test/java/org/nanoboot/powerframework/datetime/ZonedDateTimeTest.java deleted file mode 100644 index f60789a..0000000 --- a/src/test/java/org/nanoboot/powerframework/datetime/ZonedDateTimeTest.java +++ /dev/null @@ -1,157 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.datetime; - -import org.junit.Test; -import static org.junit.Assert.*; - -/** - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org - */ -public class ZonedDateTimeTest { - - /** - * - */ - public ZonedDateTimeTest() { - } - - /** - * Test of convertDateTimeFromOneTimeZoneToAnother method, of class - * ZonedDateTime. - */ - @Test - public void testConvertDateTimeFromOneTimeZoneToAnother() { - //arrange - TimeZone oldTimeZone = new TimeZone("Australia/West"); - ZonedDateTime oldZonedDateTime = new ZonedDateTime(new LocalDateTime(1995, 11, 5, 10, 5, 4, 64), oldTimeZone); - String stringRepresentationOfOldZonedDateTime = oldZonedDateTime.toString(); - - String expectedStringValue = "1995-11-05 13:05:04:064"; - String returnedStringValue; - TimeZone newTimeZone = new TimeZone("Australia/Sydney"); - //act - returnedStringValue = ZonedDateTime.convertDateTimeFromOneTimeZoneToAnother(stringRepresentationOfOldZonedDateTime, oldTimeZone, newTimeZone); - //assert - assertEquals(expectedStringValue, returnedStringValue); - } - - /** - * Test of getTimeZone method, of class ZonedDateTime. - */ - @Test - public void testGetTimeZone() { - //arrange - String timeZoneID = "Australia/West"; - TimeZone timeZone = new TimeZone(timeZoneID); - ZonedDateTime zonedDateTime = new ZonedDateTime(new LocalDateTime(1995, 8, 5, 10, 5, 4, 64), timeZone); - TimeZone returnedTimeZone; - String returnedZoneID; - //act - returnedTimeZone = zonedDateTime.getTimeZone(); - returnedZoneID = returnedTimeZone.getTimeZoneID(); - //assert - assertEquals(timeZoneID, returnedZoneID); - - } - - /** - * Test of toUniversalDateTime method, of class ZonedDateTime. - */ - @Test - public void testToUniversalDateTime() { - //arrange - TimeZone oldTimeZone = new TimeZone("Australia/West"); - ZonedDateTime zonedDateTime = new ZonedDateTime(new LocalDateTime(1995, 8, 5, 10, 5, 4, 64), oldTimeZone); - String stringRepresentationOfZonedDateTime = zonedDateTime.toString(); - - String expectedStringValue = "1995-08-05 02:05:04:064"; - String returnedStringValue; - //act - UniversalDateTime universalDateTime = zonedDateTime.toUniversalDateTime(); - returnedStringValue = universalDateTime.toString(); - //assert - assertEquals(expectedStringValue, returnedStringValue); - } - - /** - * Test of toLocalDateTime method, of class ZonedDateTime. - */ - @Test - public void testToLocalDateTime() { - //arrange - TimeZone oldTimeZone = new TimeZone("Australia/West"); - ZonedDateTime zonedDateTime = new ZonedDateTime(new LocalDateTime(1995, 8, 5, 10, 5, 4, 64), oldTimeZone); - String stringRepresentationOfZonedDateTime = zonedDateTime.toString(); - - String expectedStringValue = "1995-08-05 10:05:04:064"; - String returnedStringValue; - //act - LocalDateTime localDateTime = zonedDateTime.toLocalDateTime(); - returnedStringValue = localDateTime.toString(); - //assert - assertEquals(expectedStringValue, returnedStringValue); - } - - /** - * Test of toZonedDateTime method, of class ZonedDateTime. - */ - @Test - public void testToZonedDateTime() { - //arrange - TimeZone oldTimeZone = new TimeZone("Australia/West"); - ZonedDateTime oldZonedDateTime = new ZonedDateTime(new LocalDateTime(1995, 11, 5, 10, 5, 4, 64), oldTimeZone); - String stringRepresentationOfOldZonedDateTime = oldZonedDateTime.toString(); - - TimeZone newTimeZone = new TimeZone("Australia/Sydney"); - ZonedDateTime newZonedDateTime = new ZonedDateTime(new LocalDateTime(1995, 11, 5, 13, 5, 4, 64), oldTimeZone); - - String expectedStringValue = "1995-11-05 13:05:04:064"; - String returnedStringValue; - //act - String stringRepresentationOfNewZonedDateTime = newZonedDateTime.toString(); - returnedStringValue = stringRepresentationOfNewZonedDateTime; - //assert - assertEquals(expectedStringValue, returnedStringValue); - } - - /** - * Test of toJavaZonedDateTime method, of class ZonedDateTime. - */ - @Test - public void testToJavaZonedDateTime() { - //arrange - TimeZone timeZone = new TimeZone("Australia/West"); - ZonedDateTime zonedDateTime; - zonedDateTime = new ZonedDateTime(new LocalDateTime(1994, 5, 6, 21, 45, 6, 32), timeZone); - java.time.ZonedDateTime javaZonedDateTime; - int expectedDay = 6; - int returnedDay; - //act - - javaZonedDateTime = zonedDateTime.toJavaZonedDateTime(); - returnedDay = javaZonedDateTime.getDayOfMonth(); - //assert - assertEquals(expectedDay, returnedDay); - } - -} diff --git a/src/test/java/org/nanoboot/powerframework/pseudorandom/PseudoRandomGeneratorTest.java b/src/test/java/org/nanoboot/powerframework/pseudorandom/PseudoRandomGeneratorTest.java deleted file mode 100644 index 51daf65..0000000 --- a/src/test/java/org/nanoboot/powerframework/pseudorandom/PseudoRandomGeneratorTest.java +++ /dev/null @@ -1,125 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.pseudorandom; - -import org.nanoboot.powerframework.datetime.DateTime; -import org.nanoboot.powerframework.datetime.LocalDateTime; -import org.nanoboot.powerframework.datetime.UniversalDateTime; -import org.nanoboot.powerframework.json.JsonArray; -import org.junit.Test; -import static org.junit.Assert.*; - -/** - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org - */ -public class PseudoRandomGeneratorTest { - - public PseudoRandomGeneratorTest() { - } - - /** - * Test of getLong method, of class PseudoRandomGenerator. - */ - @Test - public void testGetLong() { - //arrange - PseudoRandomGenerator pseudoRandomGenerator = new PseudoRandomGenerator(987, new LocalDateTime(1991, 5, 24, 6, 28, 53, 862)); - - long expectedValue = 420726198994l; - long returnedValue; - //act - for (int i = 1; i <= 4; i++) { - pseudoRandomGenerator.getLong(0, 499999999999l); - } - returnedValue = pseudoRandomGenerator.getLong(0, 499999999999l); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of getInt method, of class PseudoRandomGenerator. - */ - @Test - public void testGetInt() { - //arrange - PseudoRandomGenerator pseudoRandomGenerator = new PseudoRandomGenerator(987, new LocalDateTime(1991, 5, 24, 6, 28, 53, 862)); - - int expectedValue = 198994; - int returnedValue; - //act - for (int i = 1; i <= 4; i++) { - pseudoRandomGenerator.getInt(0, 499999); - } - returnedValue = pseudoRandomGenerator.getInt(0, 499999); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of getBoolean method, of class PseudoRandomGenerator. - */ - @Test - public void testGetBoolean() { - //arrange - PseudoRandomGenerator pseudoRandomGenerator = new PseudoRandomGenerator(987, new LocalDateTime(1991, 5, 24, 6, 28, 53, 862)); - JsonArray jsonArray = new JsonArray(); - String expectedString = "[true,false,false,true,false,false,false,false,true,true,false,true,false,false,true,true,true,true,true,false,true,true,false,true,true,false,false,true,true,false,false,false,false,false,false,true,false,true,true,true,false,false,false,true,false,true,true,false,false,false]"; - String returnedString; - //act - for (int i = 1; i <= 50; i++) { - jsonArray.addBoolean(pseudoRandomGenerator.getBoolean()); - } - returnedString = jsonArray.toMinimalString(); - //assert - assertEquals(expectedString, returnedString); - } - - @Test - public void testTheSame100thOrderHasTheSame() { - //arrange - int magicNumber = PseudoRandomGenerator.getInstance().getInt(0, 1000000); - DateTime dateTime = UniversalDateTime.getRandomUniversalDateTime(); - PseudoRandomGenerator pseudoRandomGenerator; - pseudoRandomGenerator = new PseudoRandomGenerator(magicNumber, dateTime); - for (int i = 1; i < 100; i++) { - pseudoRandomGenerator.getInt(0, 1000000); - } - int expectedValue = pseudoRandomGenerator.getInt(0, 1000000); - int returnedValue; - - pseudoRandomGenerator = new PseudoRandomGenerator(magicNumber, dateTime); - for (int i = 1; i < 100; i++) { - if (PseudoRandomGenerator.getInstance().getBoolean()) { - pseudoRandomGenerator.getBoolean(); - } else if (PseudoRandomGenerator.getInstance().getBoolean()) { - pseudoRandomGenerator.getInt(0, PseudoRandomGenerator.getInstance().getInt(0, 1000000)); - } else { - pseudoRandomGenerator.getLong(0, PseudoRandomGenerator.getInstance().getInt(0, 1000000)); - } - } - //act - returnedValue = pseudoRandomGenerator.getInt(0, 1000000); - //assert - assertEquals(expectedValue, returnedValue); - } - -} diff --git a/src/test/java/org/nanoboot/powerframework/pseudorandom/SeedTest.java b/src/test/java/org/nanoboot/powerframework/pseudorandom/SeedTest.java deleted file mode 100644 index 7c2eb5c..0000000 --- a/src/test/java/org/nanoboot/powerframework/pseudorandom/SeedTest.java +++ /dev/null @@ -1,71 +0,0 @@ - -/////////////////////////////////////////////////////////////////////////////////////////////// -// power-framework: Java library with many purposes of usage. -// Copyright (C) 2016-2022 the original author or authors. -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the GNU Lesser General Public -// License as published by the Free Software Foundation; -// version 2.1 of the License only. -// -// This library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -// Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public -// License along with this library; if not, write to the Free Software -// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -/////////////////////////////////////////////////////////////////////////////////////////////// - -package org.nanoboot.powerframework.pseudorandom; - -import org.junit.Test; -import static org.junit.Assert.*; - -/** - * - * @author Robert Vokac e-mail: robertvokac@nanoboot.org - */ -public class SeedTest { - - public SeedTest() { - } - - /** - * Test of getNextNumber method, of class Seed. - */ - @Test - public void testGetNextNumber() { - //arrange - Seed seed = new Seed(5); - long expectedValue = 1679444804; - long returnedValue; - //act - for (int i = 1; i <= 37; i++) { - seed.getNextNumber(); - } - returnedValue = seed.getNextNumber(); - //assert - assertEquals(expectedValue, returnedValue); - } - - /** - * Test of jump method, of class Seed. - */ - @Test - public void testJump() { - //arrange - Seed seed = new Seed(5); - long expectedValue = 1679444804; - long returnedValue; - //act - for (int i = 1; i <= 37; i++) { - seed.jump(); - } - returnedValue = seed.getNextNumber(); - //assert - assertEquals(expectedValue, returnedValue); - } - -}