diff --git a/examples/Bar.java b/examples/Bar.java new file mode 100644 index 0000000..2b05406 --- /dev/null +++ b/examples/Bar.java @@ -0,0 +1,85 @@ +package examples; + +import java.util.List; + +public final class Bar extends Foo //Sample object that inheres +{ + byte by0 = (byte) 142; + short s0 = 555; + double d2 = 5; + Object sampleParent; + + @Override + public String toString() + { + return "Bar[" + a + " " + b + " " + c + " " + d + " " + f + " " + ch + " " + s + " " + nah + " " + l + " " + by0 + " " + s0 + " " + sampleParent+"]"; + } + + public static class BarProtocol extends FooProtocol //Protocol to serialize Bar + { + @Override + public Object[] serialize(Foo object) + { + return new Object[] {object.a, object.b, object.c, object.d, object.f, object.ch, object.s, object.nah, object.l, ((Bar) object).by0, ((Bar) object).s0, "${$parent}" /*If serialized with JussSerializer this will try to get value of parent property from certain scope!*/}; + } + + @SuppressWarnings("unchecked") + @Override + public Foo unserialize(Class objectClass, Object... args) + { + Bar f = new Bar(); + f.a = (int) args[0]; + f.b = (int) args[1]; + f.c = (int) args[2]; + f.d = (double) args[3]; + f.f = (float) args[4]; + f.ch = (char) args[5]; + f.s = (String) args[6]; + f.nah = (boolean) args[7]; + f.l = (List) args[8]; + f.by0 = (byte) args[9]; + f.s0 = (short) args[10]; + f.sampleParent = args[11]; + + return f; + } + + @Override + public Class applicableFor() + { + return Bar.class; + } + } + + public byte getBy0() { + return by0; + } + + public void setBy0(byte by0) { + this.by0 = by0; + } + + public short getS0() { + return s0; + } + + public void setS0(short s0) { + this.s0 = s0; + } + + public double getD2() { + return d2; + } + + public void setD2(double d2) { + this.d2 = d2; + } + + public Object getSampleParent() { + return sampleParent; + } + + public void setSampleParent(Object sampleParent) { + this.sampleParent = sampleParent; + } +} diff --git a/examples/Foo.java b/examples/Foo.java new file mode 100644 index 0000000..51f1451 --- /dev/null +++ b/examples/Foo.java @@ -0,0 +1,142 @@ +package examples; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Random; +import java.util.concurrent.CopyOnWriteArrayList; + +import org.ugp.serialx.protocols.SerializationProtocol; + +public class Foo //Sample object to be serialized using its protocol! +{ + int a = 8, b = 1, c = 456; + double d = 5; + float f = 1453.364564564132454654511324f; + char ch = 'l'; + String s = "a"; + boolean nah = false; + List l = new CopyOnWriteArrayList(Arrays.asList(6, 45, 464654, 9.9, 56f)); + + public Foo() + { + l.add(6); + l.add(9); + l.add(13); + l.add(new Random()); + l.add(new ArrayList<>(Arrays.asList(4, 5, 6d, new ArrayList<>(), "hi"))); + } + + @Override + public String toString() + { + return "Foo[" + a + " " + b + " " + c + " " + d + " " + f + " " + ch + " " + s + " " + nah + " " + l + "]"; + } + + public static class FooProtocol extends SerializationProtocol //Protocol to serialize Foo + { + @Override + public Object[] serialize(Foo object) + { + return new Object[] {object.a, object.b, object.c, object.d, object.f, object.ch, object.s, object.nah, object.l}; + } + + @SuppressWarnings("unchecked") + @Override + public Foo unserialize(Class objectClass, Object... args) + { + Foo f = new Foo(); + f.a = (int) args[0]; + f.b = (int) args[1]; + f.c = (int) args[2]; + f.d = (double) args[3]; + f.f = (float) args[4]; + f.ch = (char) args[5]; + f.s = (String) args[6]; + f.nah = (boolean) args[7]; + f.l = (List) args[8]; + + return f; + } + + @Override + public Class applicableFor() + { + return Foo.class; + } + } + + public int getA() { + return a; + } + + public void setA(int a) { + this.a = a; + } + + public int getB() { + return b; + } + + public void setB(int b) { + this.b = b; + } + + public int getC() { + return c; + } + + public void setC(int c) { + this.c = c; + } + + public double getD() { + return d; + } + + public void setD(double d) { + this.d = d; + } + + public float getF() { + return f; + } + + public void setF(float f) { + this.f = f; + } + + public char getCh() { + return ch; + } + + public void setCh(char ch) { + this.ch = ch; + } + + public String getS() { + return s; + } + + public void setS(String s) { + this.s = s; + } + + public boolean isNah() { + return nah; + } + + public void setNah(boolean nah) { + this.nah = nah; + } + + public List getL() { + return l; + } + + public void setL(List l) { + this.l = l; + }; + + public static void a() {}; +} diff --git a/examples/MemberInvokeOperator.java b/examples/MemberInvokeOperator.java new file mode 100644 index 0000000..be64f82 --- /dev/null +++ b/examples/MemberInvokeOperator.java @@ -0,0 +1,48 @@ +package examples; + +import static org.ugp.serialx.Serializer.InvokeFunc; +import static org.ugp.serialx.Serializer.indexOfNotInObj; +import static org.ugp.serialx.Serializer.splitValues; + +import java.lang.reflect.InvocationTargetException; + +import org.ugp.serialx.JussSerializer; +import org.ugp.serialx.converters.DataParser; +import org.ugp.serialx.converters.ObjectConverter; + +/** + * This is example of more advanced parser! It can be used for calling non-static methods from objects via "->" operator!
+ * For example with this parser registered with {@link JussSerializer#JUSS_PARSERS} you can print out hello world in JUSS like System::out->println "Hello world"
+ * Note: This is only for demonstration purposes and not a real feature so its not fully compatible with JUSS syntax so you will have to use () quiet often depending on where you put this parser! + * + * @author PETO + * + * @serial 1.3.5 + */ +public class MemberInvokeOperator implements DataParser +{ + @Override + public Object parse(ParserRegistry myHomeRegistry, String str, Object... args) + { + int index; + if ((index = indexOfNotInObj(str, "->", false)) > 0) + { + Object obj = myHomeRegistry.parse(str.substring(0, index).trim(), args); + String[] funcArgs = splitValues(str.substring(index+2).trim(), ' '); + + try + { + return InvokeFunc(obj, funcArgs[0], ObjectConverter.parseAll(myHomeRegistry, funcArgs, 1, true, args)); + } + catch (InvocationTargetException e) + { + throw new RuntimeException(e); + } + catch (Exception e2) + { + return null; + } + } + return CONTINUE; + } +} diff --git a/examples/Message.java b/examples/Message.java new file mode 100644 index 0000000..3f5e6d7 --- /dev/null +++ b/examples/Message.java @@ -0,0 +1,37 @@ +package examples; + +import org.ugp.serialx.SerializationDebugger; +import org.ugp.serialx.protocols.SelfSerializable; + +/** + * Example of self-serializable object! + * SelfSerializable objects can be serialized directly without necessity of having any {@link SerializationDebugger}, all you need to do is implement {@link SelfSerializable} interface and override {@link SelfSerializable#serialize()} method accordingly! + * + * @author PETO + * + * @see SelfSerializable + * + * @since 1.3.2 + */ +public class Message implements SelfSerializable +{ + public String str; + public int date; + + public Message(String str, int date) + { + this.str = str; + this.date = date; + } + + @Override + public String toString() { + return "Message["+str+", "+date+"]"; + } + + @Override + public Object[] serialize() + { + return new Object[] {str, date}; + } +} diff --git a/examples/TryParser.java b/examples/TryParser.java new file mode 100644 index 0000000..bdf5fa7 --- /dev/null +++ b/examples/TryParser.java @@ -0,0 +1,35 @@ +package examples; + +import static org.ugp.serialx.Serializer.indexOfNotInObj; + +import org.ugp.serialx.converters.DataParser; + +/** + * This is another example of more "advanced" parser. This one allow you to use "try" keyword and catching exceptions! + * Note: This is only for demonstration purposes and not a real feature so its not fully compatible with JUSS syntax so you will have to use () quiet often depending on where you put this parser! + * + * @author PETO + * + * @since 1.3.5 + * + * @see MemberInvokeOperator + */ +public class TryParser implements DataParser +{ + @Override + public Object parse(ParserRegistry myHomeRegistry, String str, Object... args) + { + if (indexOfNotInObj(str = str.trim(), "try") == 0) + { + try + { + return myHomeRegistry.parse(str.substring(3).trim(), false, new Class[] {getClass()}, args); + } + catch (Exception e) + { + return e; + } + } + return CONTINUE; + } +} diff --git a/examples/implementations/AdvancedParsersExample.java b/examples/implementations/AdvancedParsersExample.java new file mode 100644 index 0000000..2c63d68 --- /dev/null +++ b/examples/implementations/AdvancedParsersExample.java @@ -0,0 +1,39 @@ +package examples.implementations; + +import java.io.File; + +import org.ugp.serialx.JussSerializer; +import org.ugp.serialx.LogProvider; +import org.ugp.serialx.converters.VariableConverter; + +import examples.MemberInvokeOperator; +import examples.TryParser; + +/** + * In this example we will create our very own simple scripting language by using {@link MemberInvokeOperator} and {@link TryParser} + * together with {@link JussSerializer#JUSS_PARSERS_AND_OPERATORS}! + * As you can see with SerialX capable of far more than parsing some JSON... + * Note: This is primarily for demonstrational purposes and might not be suitable for production... + * + * @author PETO + * + * @since 1.3.5 + */ +public class AdvancedParsersExample +{ + public static void main(String[] args) throws Exception + { + //In this case JussSerializer acts as an interpreter for our custom scripting language. + JussSerializer interpreter = new JussSerializer(); + + interpreter.setParsers(JussSerializer.JUSS_PARSERS_AND_OPERATORS); //Allowing usage of operators in our script! + interpreter.getParsers().addAllAfter(VariableConverter.class, new TryParser(), new MemberInvokeOperator()); //Allowing method calls and try expressions in our script! + + LogProvider.instance.setReThrowException(true); //This allows us to implement custom exception handling! + + interpreter.LoadFrom(new File("src/examples/implementations/simpleScript.juss")); //Running our script from simpleScript.juss file! + + //Printing the results of our script... + //System.out.println(interpreter); //This is not necessary in this case! + } +} diff --git a/examples/implementations/GeneralExample.java b/examples/implementations/GeneralExample.java new file mode 100644 index 0000000..bdbea5d --- /dev/null +++ b/examples/implementations/GeneralExample.java @@ -0,0 +1,126 @@ +package examples.implementations; + +import java.io.File; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Random; +import java.util.concurrent.atomic.AtomicLong; + +import org.ugp.serialx.JussSerializer; +import org.ugp.serialx.Scope; +import org.ugp.serialx.SerializationDebugger; +import org.ugp.serialx.protocols.SerializationProtocol; + +import examples.Bar; +import examples.Foo; + +/** + * This example is overview of general SerialX API functionalities! + * We will look at how to serialize and deserialize objects using file. We will also create protocols for our objects as well as for already existing ones! + * This example is also for benchmarking! + * + * @author PETO + * + * @since 1.0.0 + */ +public class GeneralExample +{ + public static void main(String[] args) throws Exception + { + //------------------------------------------- Custom protocol registration ------------------------------------------- + + SerializationProtocol.REGISTRY.addAll(new Bar.BarProtocol(), new Foo.FooProtocol(), new SerializationProtocol() //Sample custom protocol to serialized Random. + { //Random will be serialized also without protocol via classic Java Base64 because it implements java.io.Serializable! + @Override + public Object[] serialize(Random object) + { + try + { + Field f = Random.class.getDeclaredField("seed"); + f.setAccessible(true); + return new Object[] {((AtomicLong) f.get(object)).get()}; + } + catch (Exception e) + { + e.printStackTrace(); + return new Object[] {-1}; + } + } + + @Override + public Random unserialize(Class objectClass, Object... args) + { + return new Random(((Number) args[0]).longValue()); + } + + @Override + public Class applicableFor() + { + return Random.class; + } + }); + + File f = new File("src/examples/implementations/test.juss"); //File to write and read from! + + //------------------------------------------- Generating mock data ------------------------------------------- + + Random r = new Random(); + List list = new ArrayList<>(); + for (int i = 0; i < 8; i++) + list.add(r.nextBoolean() ? r.nextInt(i+1) : r.nextBoolean()); + + HashMap vars = new HashMap<>(); //Variables to serialize + vars.put("yourMom", "is heavier than sun... //lol"); + vars.put("num", 6); + + int[][] ints = {{1, 2, 3}, {4, 5, 4}, {3, 2, 1}}; + + //------------------------------------------- Serializing ------------------------------------------- + + JussSerializer serializer = new JussSerializer(vars); //Creating an instance of Serializer that will serialize objects using Juss! Serializer is instance of scope so it behaves like so! + //Adding independent values Invokation of static members of this class (calling method "println" and obtaining "hello" field as argument! + serializer.addAll("some string", r, list, serializer.Comment("Size of array"), serializer.Var("arrSize", list.size()), new Bar(), 1, 2.2, 3, 'A', true, false, null, ints, serializer.Code("$num"), new Scope(), serializer.StaticMember(GeneralExample.class, "println", serializer.StaticMember(GeneralExample.class, "hello"))); + //This will insert an comment Another way to add variable except Map $ is used to obtain value from variable + serializer.setGenerateComments(true); //Enabling comment generation + + serializer.getParsers().resetCache(); //Enabling cache, this can improve performance when serializing a lot of data (not case of this example)! + + double t0 = System.nanoTime(); + serializer.SerializeTo(f); //Saving content of serializer to file (serializing) + double t = System.nanoTime(); + System.out.println("Write: " + (t-t0)/1000000 + " ms"); //Write benchmark + + //------------------------------------------- Deserializing ------------------------------------------- + + SerializationProtocol.REGISTRY.setActivityForAll(true); //Enabling all protocols, just in case... + + JussSerializer deserializer = new JussSerializer(); //Creating instance of Serializer that will deserialize objects serialized in Juss (same class is responsible for serializing and deserializing)! + deserializer.setParsers(JussSerializer.JUSS_PARSERS_AND_OPERATORS); //Doing this will allow us to use operators from org.ugp.serialx.converters.operators while deserializing! + deserializer.put("parent", "father"); //Setting global variables + + deserializer.getParsers().resetCache(); //Enabling cache, this can improve performance when serializing a lot of data (not case of this example)! + + deserializer = SerializationDebugger.debug(deserializer); //Enabling debugging for deserialization! + + t0 = System.nanoTime(); + deserializer.LoadFrom(f); //Loading content of file in to deserializer! + t = System.nanoTime(); + System.out.println("Read: " + (t-t0)/1000000 + " ms"); //Read benchmark + + //deserializer = (JussSerializer) deserializer.filter(obj -> obj != null); //This will filter away every null value and variable! + + //Printing values and variables of scope! + System.out.println(deserializer.variables()); + System.out.println(deserializer.values()); + } + + //We can invoke static members in JUSS! + public static String hello = "Hello world!"; + + public static void println(String str) + { + System.out.println(str); + } +} \ No newline at end of file diff --git a/examples/implementations/ReadingJsonFromInternet.java b/examples/implementations/ReadingJsonFromInternet.java new file mode 100644 index 0000000..d992095 --- /dev/null +++ b/examples/implementations/ReadingJsonFromInternet.java @@ -0,0 +1,34 @@ +package examples.implementations; + +import java.io.IOException; + +import org.ugp.serialx.JsonSerializer; + +/** + * In this example we can see how to perform json reading from remote web url! + * Note: Internet connection is required for this example to work! + * + * @author PETO + * + * @since 1.3.2 + */ +public class ReadingJsonFromInternet +{ + public static void main(String[] args) throws IOException, Exception + { + /* + //---------------------- Before SerialX 1.3.5 ---------------------- + //Creating JsonSerializer that can parse json! + JsonSerializer reader = new JsonSerializer(); + + InputStream urlInput = new URL("https://jsonplaceholder.typicode.com/users").openStream(); //Establishing connection with https://jsonplaceholder.typicode.com/users and getting stream of received data! + reader.LoadFrom(urlInput); //Parsing url stream content into json! + */ + + JsonSerializer reader = JsonSerializer.from("https://jsonplaceholder.typicode.com/users"); //Getting and deserializing data from remote web address! + + String user = "Glenna Reichert"; //User we want to get (Glenna Reichert)! + String glennasCompany = reader.getScopesWith("name", user).getScope(0).getString("name"); //Obtaining first scope that contains variable with users name and getting name of his company as string from it! + System.out.println(user + " is working for " + glennasCompany); //Printing results! + } +} diff --git a/examples/implementations/SimpleCalculator.java b/examples/implementations/SimpleCalculator.java new file mode 100644 index 0000000..b2af4b1 --- /dev/null +++ b/examples/implementations/SimpleCalculator.java @@ -0,0 +1,66 @@ +package examples.implementations; + +import java.util.Scanner; + +import org.ugp.serialx.converters.DataParser; +import org.ugp.serialx.converters.DataParser.ParserRegistry; +import org.ugp.serialx.converters.NumberConverter; +import org.ugp.serialx.converters.OperationGroups; +import org.ugp.serialx.converters.operators.ArithmeticOperators; + +/** + * This example will show you simple implementation of SerialX latest feature the recursive data parser! + * In this example we will be creating simple evaluator of mathematical expressions! + * + * @author PETO + * + * @since 1.3.0 + */ +public class SimpleCalculator +{ + static Scanner scIn = new Scanner(System.in); + + public static void main(String[] args) + { + /* + * We could easily just use DataParser.REGISTRY but there is tone of stuff we do not need and it will just slow it down! + */ + ParserRegistry parsersRequiredToEvaluateMath = new ParserRegistry(new OperationGroups(), new ArithmeticOperators(), new NumberConverter()); + + /* + * This is an example of simple custom parser this one will allow us to reuse answers of out previous evaluations! + * We will access this old answer using 'ans' word! + * Old ans must be provided as first one of args! + */ + DataParser ansParser = new DataParser() + { + @Override + public Object parse(ParserRegistry myHomeRegistry, String str, Object... args) + { + if (str.equalsIgnoreCase("ans")) + { + if (args.length > 0) + return args[0]; //First arg is old answer! + return null; + } + return CONTINUE; + } + }; + parsersRequiredToEvaluateMath.add(ansParser); + + Object oldAns = null; + while (true) + { + System.out.print("Please insert your math problem: "); //Ask for input! + String input = scIn.nextLine() ;//Read console input + if (!(input = input.trim()).isEmpty()) //Avoiding empty input! + { + double t0 = System.nanoTime(); //Performing simple benchmark + oldAns = parsersRequiredToEvaluateMath.parse(input, oldAns); //Notice that we are inserting oldAns as compiler arguments for parseObj which are then picked up by our ansParser as well as every other registered DataParser. + double t = System.nanoTime(); + + System.out.println(input + " = " + oldAns +"\n" + (t-t0)/1000000 + "ms \n"); //Parsing input! + } + } + } +} diff --git a/examples/implementations/SimpleQuerying.java b/examples/implementations/SimpleQuerying.java new file mode 100644 index 0000000..8487702 --- /dev/null +++ b/examples/implementations/SimpleQuerying.java @@ -0,0 +1,148 @@ +package examples.implementations; + +import java.util.List; + +import org.ugp.serialx.JussSerializer; +import org.ugp.serialx.Scope; +import org.ugp.serialx.converters.DataParser; + +/** + * This example contains brief example of querying and obtaining real data from deserialized content! + * + * @author PETO + * + * @since 1.3.5 + */ +public class SimpleQuerying +{ + public static void main(String[] args) throws Exception + { + //Loading complex juss file "commentedExample.juss"! + JussSerializer content = JussSerializer.from("src/examples/implementations/commentedExample.juss"); //Since 1.3.5 we can use "from/into API" to load content of scope by just typing its path into "from" method! + + //Printing loaded data! + System.out.println("Used content:\n" + content + "\n"); + + /* + * Scope#getScope method is capable of getting scopes that are direct sub-scopes of scope but also it will automatically search for required scope + * through every sub-scope in content! Thats why we can get sub-scope stored by "serialx" variable even though it is neasted in 3 parent scopes, Scope#getScope method will + * search for it automatically without necessity of chaining multiple of them. In case of there being more than one "serialx" we can specify the specific path like + * content.getScope("dependencies", "something", "serialx")! But in case of there being only one, like we have, this is not really necessary. + */ + String serialx = content.getScope("serialx").getString(0); //Getting first independent value of scope stored by variable "serialx"! + System.out.println("SerialX " + serialx.toLowerCase()); //Printing result! + + /** + * We often times have scopes where there are data with repetitive structure. In this case in scope stored by "ppl" there are always sub-scopes that have name, age and residence! + * We can use Scope#getAllStoredBy to get values of all variables from this sub-scopes. + * In this example we will take all age of all people, sum it up and than print average age of them! + */ + List ages = content.getScope("ppl").getAllStoredBy("age"); //Getting all age variables of sub-scopes from "ppl" scope! \ + //Suming them and printing avg age! + double sum = 0; + for (Number number : ages) + sum += number.doubleValue(); + System.out.println("Avarage age of people is: " + (sum / ages.size())); + + /** + * Sometimes we do not need to get only values of variables inside of a scope, sometimes we need actual scopes with variables meeting certain criterias, + * this is case where method Scope#getScopesWith comes in handy! This method will return sub-scope containing all sub-scopes found that contains variable that meats + * a certain condition! + * With this we can for example get all people that live in a certain country! + */ + String residence = "germany"; //Country of residence! + Scope residents = content.getScope("ppl").getScopesWith("residence", residanceValue -> ((String) residanceValue).equalsIgnoreCase(residence)); //Getting all people sub-scopes that whose have "residence" variable equal to required residence! + System.out.println("People liveing in " + residence + " are: " + residents.getAllStoredBy("name")); //Printing names of those who live in Germany! + + /** + * Perhaps the most powerful querying method is GenericScope#filter that allow you to filter away both independent values as well as variables with values that + * does not meet your condition! + * In this particular example we are writing pretty simple condition that will filter away everything that is not a scope and has no independent values inside! + */ + Scope filtered = (Scope) content.getScope("dataStorage").filter(obj -> ((Scope) obj).valuesCount() > 0); //Filtering + System.out.println(filtered.variables()); //Printing variables of filtered sub-scope! + + /** + * One also very powerful method is GenericScope#map that will remap independent values of the scope based on rule you write! + * In this case we are taking all values of sub-scope stored by "arr" variable and multiplying them by 2 if they are bigger than 3! + * Notice that by returning DataParser#VOID we can filter away the certain values! + * + * Honorable mention is also GenericScope#transform that will transform entire scope including values of variables not only independent values like map! + */ + List remappedValues = content.getScope("arr").map(obj -> ((Number) obj).doubleValue() > 3 ? ((Number) obj).doubleValue() * 2 : DataParser.VOID); //Remapping independent values of scope stored by "arr" by multiplying them by 2 if they are bigger than 3! + System.out.println("Mapped number values: " + remappedValues); //Printing remapped independent values of "arr"! + + /** + * We can use GenericScope#map in combination with Scope#toObject and Scope#into methods to remap scopes into real java objects! + * For instance we can remap all all scopes representing residents of Germany into real Java sample Person objects! + */ + List realResidents = residents.map(obj -> { + try + { + return ((Scope) obj).into(Person.class); //Turning scopes into real Java objects! + } + catch (Exception e) + { + return DataParser.VOID; //We already know that this will filter away the object! + } + }); + System.out.println("Real \"Java\" residents of " + residence + " are: " + realResidents); //Printing results + } + + /** + * Dummy class, part of SerialX {@link SimpleQuerying} example!
+ * Note: In order for {@link Scope#toObject} and {@link Scope#into} and methods to work, object must have valid getters and setters! + * + * @author PETO + * + * @since 1.3.5 + */ + public static class Person + { + protected String name, residance; + protected double age; + + public Person(String name, String residance, double age) + { + this.name = name; + this.residance = residance; + this.age = age; + } + + public String getName() + { + return name; + } + + public void setName(String name) + { + this.name = name; + } + + public String getResidance() + { + return residance; + } + + public void setResidance(String residance) + { + this.residance = residance; + } + + public double getAge() + { + return age; + } + + public void setAge(double age) + { + this.age = age; + } + + @Override + public String toString() + { + return "Person[name=" + name + ", residance=" + residance + ", age=" + age + "]"; + } + } +} diff --git a/examples/implementations/commentedExample.juss b/examples/implementations/commentedExample.juss new file mode 100644 index 0000000..4060ca5 --- /dev/null +++ b/examples/implementations/commentedExample.juss @@ -0,0 +1,146 @@ +/* THIS IS HOW RESULT OF SERIALX (Juss) REAL LIFE IMPLEMENTATION MIGHT LOOK LIKE */ +import org.ugp.serialx.JsonSerializer => Json; //Importing JsonSerializer and aliasing it as Json! + +name = "app"; + +dependencies = +{ + //This is scope, the Juss representation of ugp.org.SerialX.Scope! + //Each scope can have its own variables with values and independant values! + + //Every scope can read and write parent scopes variables however by changing them, it will only affect local one and not parents one! + $name; //"app" ($ obtains value from variable, in this case "app") + $name = "no longer app lol!"; + + composition-api = "1.0.0 (beta)", //This is one of the variables of this scope... + bootstrap = "4.5.3", + version = "2.3.4", + something = + { + dataStorage = + { + //This is "dataStorage" (stored by variable "dataStorage") sub-scope aka nested skope of its parent scope "something" which is subscope of "dependencies", + xml = + { + version = "2.8.0" + }, + yaml = + { + version = "1.10.5" + }, + josn = + { + version = "4.0.0" + }, + serialx = + { + version = "The best version!"; + "Is the best!" + } + totalVersion = "9.9.9" + }, + ppl = + { + //This is "ppl" (stored by variable "ppl") sub-scope aka nested skope of its parent scope "something" which is subscope of "dependencies". + //All of these scopes are sub-scopes of "ppl", there can be infinite number of variables and independent values together in one Scope! + { + name: "Vladimir"; + age = 37; + residence = "russia"; + }, + { + name: "Ivan"; + age = 19; + residence = "russia"; + }, + { + name: "Firippu"; + age = 103; + residence = "japan"; + }, + { + name: "Peter"; + age = 17; + residence = "slovak"; + }, + { + name: "Lukas"; + age = 23; + residence = "usa"; + }, + { + name: "Hans"; + age = 51; + residence = "germany"; + }, + { + name: "Yeager"; + age = 17; + residence = "germany"; + }, + { + name: "Pierre"; + age = 44; + residence = "france"; + } + } + }, + "lololoolollool"; //This is independent value of this scope. +}, +$dependencies.something.dataStorage.serialx.version; //Obtaining value of "serialx" variable in "dependencies" sub-scopes! + +devDependencies = +{ + //Variables in this scope have nothing to do with variables from "dependencies" because they are in diffrent scope! + $name = "absolutely not app!"; + + composition-api = "1.0.0 (alpha)", + bootstrap = "2.2.3", + version = "1.2.3", + something = + { + dataStorage = {}, + ppl = {} + } +}; +//Setting variable of scope from outer world (possible since 1.3.2) +devDependencies.something.ppl.ludvig = +{ + age = 60; + residence = "russia"; +}; + +//Since 1.2.5 Serializer fully supports Json and JavaScript object! +jsonCrossover = Json { + "hello" : "Hello world I am Javascript object notation!", + "jsObject": { + name: "John", + age: 31, + city: "New York" + }, + "jsonArray": [ + 1, + 2, + 3, + 4 + ] +}, + +//Since SerialX 1.3.5 we can use "from/into API" to load files from external locations! +alienFruit = Json::from "src/examples/implementations/test.json"; //Loading content of external file by using JsonSerializer! +alienPost = Json::from "https://jsonplaceholder.typicode.com/posts/1"; //We can even load files from remote urls (internet connection is required for this)! + +//$bullshit <-- No this is not possible, variable "bullshit" cannot be accessed here because it was not initialized yet! +bullshit = +{ + //This scope cant access variable that is stored by (bullshit), because variable is always created after its value (Scope in this case) is constructed! + server = "service server", + build = "service build", + sql = "service sql"; +}, +$bullshit; //Now we can access variable "bullshit" + +$name; //"name" is still "app" in this scope! + +arr = {1, 2, 3, 4, 5}; //This is scope with only values! So lets call it... array I guess! +superArr = {$arr, $arr, $arr, $arr::new /*creates clone of arr*/, {1, 2, 3, 4, 5}}; //Yes... this is completely normal and possible in Juss but keep in mind that first, second and third element will refere to same instance in this case! diff --git a/examples/implementations/simpleScript.juss b/examples/implementations/simpleScript.juss new file mode 100644 index 0000000..3bada57 --- /dev/null +++ b/examples/implementations/simpleScript.juss @@ -0,0 +1,21 @@ +/* THIS EXAMPLE IS DEMONSTRATING CAPABILITIES OF SERIALX AS A DOMAIN SPECIFIC LANGUAGE TOOLKIT BY CREATING AN SIMPLE SCRIPT */ +/* In this case, we are writing a simple script that will print "Hello world!" and then analyze your age category from the age given! */ + +System::out->println "Hello world!"; //Saying the famous "Hello world" in our custom script by calling java methods! + +//Handling possible errors! +result = try { //Convenient usage of JUSS scope as a code block... + System::out->print "Enter your age: "; //Asking for input! + + input = java.util.Scanner System::in; //Declaring input scanner object! + age = double ($input->nextLine); //Reading input from console as number! + + //Printing age message + System::out->println ($age >= 18 ? "You are an adult!" : $age <= 0 ? "Well, you are not yet..." : "You are sill a child!"); +} + +//Printing adequate error message... +$result instanceof java.lang.RuntimeException ? (System::err->println "Age must be a number you dummy..."); + +//Voidification of used variables that are not needed! This is not really a necessity but it nice to know about it... +result = void; //Voidification will remove the variable from this scope releasing some memory! \ No newline at end of file diff --git a/examples/implementations/test.json b/examples/implementations/test.json new file mode 100644 index 0000000..4a4419c --- /dev/null +++ b/examples/implementations/test.json @@ -0,0 +1,10 @@ +{ + "fruit": "Apple", + "size": "Large", + "color": "Red", + "variants": [ + 1, + 2, + 3 + ] +} \ No newline at end of file diff --git a/examples/implementations/test.juss b/examples/implementations/test.juss new file mode 100644 index 0000000..2887100 --- /dev/null +++ b/examples/implementations/test.juss @@ -0,0 +1,25 @@ +//Date created: 08-30-2022 at 22:09:37 CEST + +//Scope serialization summary: +//2 variables! +//17 values! + +num = 6; //Primitive data type: "6" the integer value! Stored by "num" variable! +yourMom = "is heavier than sun... //lol"; //Object of java.lang.String: "is heavier than sun... //lol"! Stored by "yourMom" variable! +"some string"; //Object of java.lang.String: "some string"! +java.util.Random 201741863018485L; //Object of java.util.Random: "java.util.Random@28d93b30" serialized using examples.implementations.GeneralExample$1[java.util.Random]! +ArrayList 0 0 0 1 1 F T T; //Object of java.util.ArrayList: "[0, 0, 0, 1, 1, false, true, true]" serialized using org.ugp.serialx.protocols.ListProtocol[java.util.Collection]! +//Size of array +arrSize = 8; //Manually inserted code! +examples.Bar 8 1 456 5D 1453.365F '108' "a" F {java.util.concurrent.CopyOnWriteArrayList 6 45 464654 9.9 56F 6 9 13 {java.util.Random 247146578635213L} {ArrayList 4 5 6D ArrayList "hi"}} -114Y 555S $parent; //Object of examples.Bar: "Bar[8 1 456 5.0 1453.3646 l a false [6, 45, 464654, 9.9, 56.0, 6, 9, 13, java.util.Random@1b6d3586, [4, 5, 6.0, [], hi]] -114 555 null]" serialized using examples.Bar$BarProtocol[examples.Bar]! +1; //Primitive data type: "1" the integer value! +2.2; //Primitive data type: "2.2" the double value! +3; //Primitive data type: "3" the integer value! +'65'; //Primitive data type: "A" the character value! +T; //Primitive data type: "true" the boolean value! +F; //Primitive data type: "false" the boolean value! +null; //Null, the nothing! +(1 2 3) (4 5 4) (3 2 1); //Primitive array [[I@4554617c converted by org.ugp.serialx.converters.ArrayConverter +$num; //Manually inserted code! +{}; //Empty scope! +{examples.implementations.GeneralExample::println examples.implementations.GeneralExample::hello}; //Manually inserted code! \ No newline at end of file