9
0
mirror of https://github.com/VolmitSoftware/Iris.git synced 2025-12-28 11:39:07 +00:00
This commit is contained in:
Daniel Mills
2020-07-27 20:49:26 -04:00
parent 1ae1cebab6
commit 108499706a
181 changed files with 11266 additions and 498 deletions

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
/**
* Provides an incredibly fast averaging object. It swaps values from a sum

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import org.bukkit.util.Vector;

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import java.util.Random;

View File

@@ -1,7 +1,6 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import ninja.bytecode.iris.object.IrisBiome;
import ninja.bytecode.shuriken.collections.KMap;
import com.volmit.iris.object.IrisBiome;
public class BiomeDominance extends KMap<IrisBiome, Double>
{

View File

@@ -1,6 +1,6 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import ninja.bytecode.iris.object.IrisBiome;
import com.volmit.iris.object.IrisBiome;
public class BiomeMap
{

View File

@@ -1,7 +1,8 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import com.volmit.iris.object.IrisBiome;
import lombok.Data;
import ninja.bytecode.iris.object.IrisBiome;
@Data
public class BiomeResult

View File

@@ -1,12 +1,10 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.block.data.BlockData;
import ninja.bytecode.iris.Iris;
import ninja.bytecode.shuriken.collections.KList;
import ninja.bytecode.shuriken.collections.KMap;
import com.volmit.iris.Iris;
public class BlockDataTools
{

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import lombok.Data;

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import java.util.Collections;
import java.util.List;

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import lombok.Getter;
import org.apache.commons.lang.StringUtils;

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.Objective;

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import lombok.Builder;
import lombok.Getter;

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import lombok.RequiredArgsConstructor;

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
@FunctionalInterface
public interface BorderCheck<T>

View File

@@ -1,6 +1,4 @@
package ninja.bytecode.iris.util;
import ninja.bytecode.shuriken.math.M;
package com.volmit.iris.util;
public class Borders
{

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
/*
* JNBT License

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
/*
* JNBT License

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
public class CDou
{

View File

@@ -1,6 +1,4 @@
package ninja.bytecode.iris.util;
import ninja.bytecode.shuriken.collections.KList;
package com.volmit.iris.util;
public class CNG
{

View File

@@ -0,0 +1,6 @@
package com.volmit.iris.util;
public interface Callback<T>
{
public void run(T t);
}

View File

@@ -1,6 +1,6 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
public interface Callback<T>
public interface CallbackCV<T>
{
public void run(T t);
}

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import lombok.Data;

View File

@@ -1,10 +1,11 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import com.volmit.iris.util.FastNoise.CellularDistanceFunction;
import com.volmit.iris.util.FastNoise.CellularReturnType;
import com.volmit.iris.util.FastNoise.NoiseType;
import lombok.Getter;
import lombok.Setter;
import ninja.bytecode.iris.util.FastNoise.CellularDistanceFunction;
import ninja.bytecode.iris.util.FastNoise.CellularReturnType;
import ninja.bytecode.iris.util.FastNoise.NoiseType;
public class CellGenerator
{

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
public class ChronoLatch
{

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import lombok.Data;

View File

@@ -0,0 +1,57 @@
package com.volmit.iris.util;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
public class Chunker<T>
{
private ExecutorService executor;
private int threads;
private int workload;
private KList<T> q;
public Chunker(KList<T> q)
{
this.q = q;
}
public Chunker<T> threads(int threads)
{
this.threads = threads;
return this;
}
public Chunker<T> workload(int workload)
{
this.workload = workload;
return this;
}
public void execute(Consumer<T> consumer, Callback<Double> progress, int progressInterval)
{
ChronoLatch cl = new ChronoLatch(progressInterval);
Contained<Integer> consumed = new Contained<Integer>(0);
executor = Executors.newFixedThreadPool(threads);
int length = q.size();
int remaining = length;
while(remaining > 0)
{
int at = remaining;
remaining -= (remaining > workload ? workload : remaining);
int to = remaining;
executor.submit(() ->
{
J.dofor(at, (i) -> i >= to, -1, (i) -> J.attempt(() -> consumer.accept(q.get(i))));
consumed.mod((c) -> c += workload);
J.doif(() -> progress != null && cl.flip(), () -> progress.run((double) consumed.get() / (double) length));
});
}
executor.shutdown();
J.attempt(() -> executor.awaitTermination(100, TimeUnit.HOURS));
}
}

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
/*
* JNBT License

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
@FunctionalInterface
public interface Consumer2<A, B>

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
@FunctionalInterface
public interface Consumer3<A, B, C>

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import java.util.function.Function;

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import java.util.ArrayList;
import java.util.HashMap;
@@ -15,8 +15,6 @@ import org.bukkit.block.Block;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.entity.Entity;
import ninja.bytecode.shuriken.collections.KList;
/**
* Cuboids
*

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
/**
* Represents a cuboid exception

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import org.bukkit.util.Vector;

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
/**
* Dimensions

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
/**
* Represents a dimension (coordinates not worlds)

View File

@@ -1,13 +1,11 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import org.bukkit.Axis;
import org.bukkit.block.BlockFace;
import org.bukkit.util.Vector;
import ninja.bytecode.iris.util.Cuboid.CuboidDirection;
import ninja.bytecode.shuriken.collections.KList;
import ninja.bytecode.shuriken.collections.KMap;
import com.volmit.iris.util.Cuboid.CuboidDirection;
/**
* Directions

View File

@@ -0,0 +1,14 @@
package com.volmit.iris.util;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target({FIELD, TYPE})
public @interface DontObfuscate
{
}

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
public class DoubleArrayUtils

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
/*
* JNBT License

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
/*
* JNBT License

View File

@@ -25,7 +25,7 @@
// The developer's email is jorzixdan.me2@gzixmail.com (for great email, take
// off every 'zix'.)
//
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import javax.vecmath.Vector2f;
import javax.vecmath.Vector3f;

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import org.bukkit.Location;
import org.bukkit.World;

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import org.bukkit.Bukkit;

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import java.io.File;

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
/*
* JNBT License

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,7 @@
package com.volmit.iris.util;
@FunctionalInterface
public interface Function2<A, B, R>
{
public R apply(A a, B b);
}

View File

@@ -0,0 +1,7 @@
package com.volmit.iris.util;
@FunctionalInterface
public interface Function3<A, B, C, R>
{
public R apply(A a, B b, C c);
}

View File

@@ -0,0 +1,7 @@
package com.volmit.iris.util;
@FunctionalInterface
public interface Function4<A, B, C, D, R>
{
public R apply(A a, B b, C c, D d);
}

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import java.io.Serializable;

View File

@@ -1,10 +1,8 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import java.util.List;
import ninja.bytecode.shuriken.collections.KList;
/**
* Adapts a list of objects into a list of other objects
*

View File

@@ -1,6 +1,6 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import ninja.bytecode.iris.generator.DimensionChunkGenerator;
import com.volmit.iris.generator.DimensionChunkGenerator;
public abstract class GenLayer
{

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -7,10 +7,6 @@ import java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory;
import java.util.concurrent.ForkJoinWorkerThread;
import java.util.concurrent.locks.ReentrantLock;
import ninja.bytecode.shuriken.collections.KMap;
import ninja.bytecode.shuriken.execution.J;
import ninja.bytecode.shuriken.execution.NastyRunnable;
public class GroupedExecutor
{
private int xc;

View File

@@ -0,0 +1,201 @@
package com.volmit.iris.util;
/*
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import java.util.Iterator;
/**
* Convert an HTTP header to a JSONObject and back.
*
* @author JSON.org
* @version 2014-05-03
*/
public class HTTP
{
/** Carriage return/line feed. */
public static final String CRLF = "\r\n";
/**
* Convert an HTTP header string into a JSONObject. It can be a request
* header or a response header. A request header will contain
*
* <pre>
* {
* Method: "POST" (for example),
* "Request-URI": "/" (for example),
* "HTTP-Version": "HTTP/1.1" (for example)
* }
* </pre>
*
* A response header will contain
*
* <pre>
* {
* "HTTP-Version": "HTTP/1.1" (for example),
* "Status-Code": "200" (for example),
* "Reason-Phrase": "OK" (for example)
* }
* </pre>
*
* In addition, the other parameters in the header will be captured, using
* the HTTP field names as JSON names, so that
*
* <pre>
* Date: Sun, 26 May 2002 18:06:04 GMT
* Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s
* Cache-Control: no-cache
* </pre>
*
* become
*
* <pre>
* {...
* Date: "Sun, 26 May 2002 18:06:04 GMT",
* Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s",
* "Cache-Control": "no-cache",
* ...}
* </pre>
*
* It does no further checking or conversion. It does not parse dates. It
* does not do '%' transforms on URLs.
*
* @param string
* An HTTP header string.
* @return A JSONObject containing the elements and attributes of the XML
* string.
* @throws JSONException
*/
public static JSONObject toJSONObject(String string) throws JSONException
{
JSONObject jo = new JSONObject();
HTTPTokener x = new HTTPTokener(string);
String token;
token = x.nextToken();
if(token.toUpperCase().startsWith("HTTP"))
{
// Response
jo.put("HTTP-Version", token);
jo.put("Status-Code", x.nextToken());
jo.put("Reason-Phrase", x.nextTo('\0'));
x.next();
} else
{
// Request
jo.put("Method", token);
jo.put("Request-URI", x.nextToken());
jo.put("HTTP-Version", x.nextToken());
}
// Fields
while(x.more())
{
String name = x.nextTo(':');
x.next(':');
jo.put(name, x.nextTo('\0'));
x.next();
}
return jo;
}
/**
* Convert a JSONObject into an HTTP header. A request header must contain
*
* <pre>
* {
* Method: "POST" (for example),
* "Request-URI": "/" (for example),
* "HTTP-Version": "HTTP/1.1" (for example)
* }
* </pre>
*
* A response header must contain
*
* <pre>
* {
* "HTTP-Version": "HTTP/1.1" (for example),
* "Status-Code": "200" (for example),
* "Reason-Phrase": "OK" (for example)
* }
* </pre>
*
* Any other members of the JSONObject will be output as HTTP fields. The
* result will end with two CRLF pairs.
*
* @param jo
* A JSONObject
* @return An HTTP header string.
* @throws JSONException
* if the object does not contain enough information.
*/
public static String toString(JSONObject jo) throws JSONException
{
Iterator<String> keys = jo.keys();
String string;
StringBuilder sb = new StringBuilder();
if(jo.has("Status-Code") && jo.has("Reason-Phrase"))
{
sb.append(jo.getString("HTTP-Version"));
sb.append(' ');
sb.append(jo.getString("Status-Code"));
sb.append(' ');
sb.append(jo.getString("Reason-Phrase"));
} else if(jo.has("Method") && jo.has("Request-URI"))
{
sb.append(jo.getString("Method"));
sb.append(' ');
sb.append('"');
sb.append(jo.getString("Request-URI"));
sb.append('"');
sb.append(' ');
sb.append(jo.getString("HTTP-Version"));
} else
{
throw new JSONException("Not enough material for an HTTP header.");
}
sb.append(CRLF);
while(keys.hasNext())
{
string = keys.next();
if(!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && !"Reason-Phrase".equals(string) && !"Method".equals(string) && !"Request-URI".equals(string) && !jo.isNull(string))
{
sb.append(string);
sb.append(": ");
sb.append(jo.getString(string));
sb.append(CRLF);
}
}
sb.append(CRLF);
return sb.toString();
}
}

View File

@@ -0,0 +1,91 @@
package com.volmit.iris.util;
/*
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* The HTTPTokener extends the JSONTokener to provide additional methods for the
* parsing of HTTP headers.
*
* @author JSON.org
* @version 2014-05-03
*/
public class HTTPTokener extends JSONTokener
{
/**
* Construct an HTTPTokener from a string.
*
* @param string
* A source string.
*/
public HTTPTokener(String string)
{
super(string);
}
/**
* Get the next token or string. This is used in parsing HTTP headers.
*
* @throws JSONException
* @return A String.
*/
public String nextToken() throws JSONException
{
char c;
char q;
StringBuilder sb = new StringBuilder();
do
{
c = next();
} while(Character.isWhitespace(c));
if(c == '"' || c == '\'')
{
q = c;
for(;;)
{
c = next();
if(c < ' ')
{
throw syntaxError("Unterminated string.");
}
if(c == q)
{
return sb.toString();
}
sb.append(c);
}
}
for(;;)
{
if(c == 0 || Character.isWhitespace(c))
{
return sb.toString();
}
sb.append(c);
c = next();
}
}
}

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import java.util.Arrays;

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
public class ING
{

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import java.io.BufferedInputStream;
import java.io.BufferedReader;

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import org.bukkit.block.data.BlockData;

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import org.bukkit.block.data.BlockData;

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import java.util.Arrays;

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
/*
* JNBT License

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
public enum InterpolationType
{
LINEAR,

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import org.bukkit.block.Biome;
import org.bukkit.generator.ChunkGenerator.BiomeGrid;

View File

@@ -1,6 +1,6 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import ninja.bytecode.iris.object.InterpolationMethod;
import com.volmit.iris.object.InterpolationMethod;
public class IrisInterpolation
{

View File

@@ -1,8 +1,8 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import org.bukkit.block.data.BlockData;
import ninja.bytecode.iris.generator.PostBlockChunkGenerator;
import com.volmit.iris.generator.PostBlockChunkGenerator;
public abstract class IrisPostBlockFilter implements IPostBlockAccess
{

View File

@@ -0,0 +1,137 @@
package com.volmit.iris.util;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import com.volmit.iris.Iris;
public class J
{
private static int tid = 0;
private static final ExecutorService e = Executors.newCachedThreadPool(new ThreadFactory()
{
@Override
public Thread newThread(Runnable r)
{
tid++;
Thread t = new Thread(r);
t.setName("Actuator " + tid);
t.setPriority(Thread.MIN_PRIORITY);
t.setUncaughtExceptionHandler((et, e) ->
{
Iris.info("Exception encountered in " + et.getName());
e.printStackTrace();
});
return t;
}
});
public static void dofor(int a, Function<Integer, Boolean> c, int ch, Consumer<Integer> d)
{
for(int i = a; c.apply(i); i += ch)
{
c.apply(i);
}
}
public static boolean doif(Supplier<Boolean> c, Runnable g)
{
if(c.get())
{
g.run();
return true;
}
return false;
}
public static void a(Runnable a)
{
e.submit(a);
}
public static <T> Future<T> a(Callable<T> a)
{
return e.submit(a);
}
public static void attemptAsync(NastyRunnable r)
{
J.a(() -> J.attempt(r));
}
public static <R> R attemptResult(NastyFuture<R> r, R onError)
{
try
{
return r.run();
}
catch(Throwable e)
{
}
return onError;
}
public static <T, R> R attemptFunction(NastyFunction<T, R> r, T param, R onError)
{
try
{
return r.run(param);
}
catch(Throwable e)
{
}
return onError;
}
public static boolean sleep(long ms)
{
return J.attempt(() -> Thread.sleep(ms));
}
public static boolean attempt(NastyRunnable r)
{
return attemptCatch(r) == null;
}
public static Throwable attemptCatch(NastyRunnable r)
{
try
{
r.run();
}
catch(Throwable e)
{
return e;
}
return null;
}
public static <T> T attempt(Supplier<T> t, T i)
{
try
{
return t.get();
}
catch(Throwable e)
{
return i;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,50 @@
package com.volmit.iris.util;
/**
* The JSONException is thrown by the JSON.org classes when things are amiss.
*
* @author JSON.org
* @version 2014-05-03
*/
public class JSONException extends RuntimeException
{
private static final long serialVersionUID = 0;
private Throwable cause;
/**
* Constructs a JSONException with an explanatory message.
*
* @param message
* Detail about the reason for the exception.
*/
public JSONException(String message)
{
super(message);
}
/**
* Constructs a new JSONException with the specified cause.
*
* @param cause
* The cause.
*/
public JSONException(Throwable cause)
{
super(cause.getMessage());
this.cause = cause;
}
/**
* Returns the cause of this exception or null if the cause is nonexistent
* or unknown.
*
* @return the cause of this exception or null if the cause is nonexistent
* or unknown.
*/
@Override
public Throwable getCause()
{
return this.cause;
}
}

View File

@@ -0,0 +1,555 @@
package com.volmit.iris.util;
/*
Copyright (c) 2008 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import java.util.Iterator;
/**
* This provides static methods to convert an XML text into a JSONArray or
* JSONObject, and to covert a JSONArray or JSONObject into an XML text using
* the JsonML transform.
*
* @author JSON.org
* @version 2014-05-03
*/
public class JSONML
{
/**
* Parse XML values and store them in a JSONArray.
*
* @param x
* The XMLTokener containing the source string.
* @param arrayForm
* true if array form, false if object form.
* @param ja
* The JSONArray that is containing the current tag or null if we
* are at the outermost level.
* @return A JSONArray if the value is the outermost tag, otherwise null.
* @throws JSONException
*/
private static Object parse(XMLTokener x, boolean arrayForm, JSONArray ja) throws JSONException
{
String attribute;
char c;
String closeTag = null;
int i;
JSONArray newja = null;
JSONObject newjo = null;
Object token;
String tagName = null;
// Test for and skip past these forms:
// <!-- ... -->
// <![ ... ]]>
// <! ... >
// <? ... ?>
while(true)
{
if(!x.more())
{
throw x.syntaxError("Bad XML");
}
token = x.nextContent();
if(token == XML.LT)
{
token = x.nextToken();
if(token instanceof Character)
{
if(token == XML.SLASH)
{
// Close tag </
token = x.nextToken();
if(!(token instanceof String))
{
throw new JSONException("Expected a closing name instead of '" + token + "'.");
}
if(x.nextToken() != XML.GT)
{
throw x.syntaxError("Misshaped close tag");
}
return token;
} else if(token == XML.BANG)
{
// <!
c = x.next();
if(c == '-')
{
if(x.next() == '-')
{
x.skipPast("-->");
} else
{
x.back();
}
} else if(c == '[')
{
token = x.nextToken();
if(token.equals("CDATA") && x.next() == '[')
{
if(ja != null)
{
ja.put(x.nextCDATA());
}
} else
{
throw x.syntaxError("Expected 'CDATA['");
}
} else
{
i = 1;
do
{
token = x.nextMeta();
if(token == null)
{
throw x.syntaxError("Missing '>' after '<!'.");
} else if(token == XML.LT)
{
i += 1;
} else if(token == XML.GT)
{
i -= 1;
}
} while(i > 0);
}
} else if(token == XML.QUEST)
{
// <?
x.skipPast("?>");
} else
{
throw x.syntaxError("Misshaped tag");
}
// Open tag <
} else
{
if(!(token instanceof String))
{
throw x.syntaxError("Bad tagName '" + token + "'.");
}
tagName = (String) token;
newja = new JSONArray();
newjo = new JSONObject();
if(arrayForm)
{
newja.put(tagName);
if(ja != null)
{
ja.put(newja);
}
} else
{
newjo.put("tagName", tagName);
if(ja != null)
{
ja.put(newjo);
}
}
token = null;
for(;;)
{
if(token == null)
{
token = x.nextToken();
}
if(token == null)
{
throw x.syntaxError("Misshaped tag");
}
if(!(token instanceof String))
{
break;
}
// attribute = value
attribute = (String) token;
if(!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute)))
{
throw x.syntaxError("Reserved attribute.");
}
token = x.nextToken();
if(token == XML.EQ)
{
token = x.nextToken();
if(!(token instanceof String))
{
throw x.syntaxError("Missing value");
}
newjo.accumulate(attribute, XML.stringToValue((String) token));
token = null;
} else
{
newjo.accumulate(attribute, "");
}
}
if(arrayForm && newjo.length() > 0)
{
newja.put(newjo);
}
// Empty tag <.../>
if(token == XML.SLASH)
{
if(x.nextToken() != XML.GT)
{
throw x.syntaxError("Misshaped tag");
}
if(ja == null)
{
if(arrayForm)
{
return newja;
} else
{
return newjo;
}
}
// Content, between <...> and </...>
} else
{
if(token != XML.GT)
{
throw x.syntaxError("Misshaped tag");
}
closeTag = (String) parse(x, arrayForm, newja);
if(closeTag != null)
{
if(!closeTag.equals(tagName))
{
throw x.syntaxError("Mismatched '" + tagName + "' and '" + closeTag + "'");
}
tagName = null;
if(!arrayForm && newja.length() > 0)
{
newjo.put("childNodes", newja);
}
if(ja == null)
{
if(arrayForm)
{
return newja;
} else
{
return newjo;
}
}
}
}
}
} else
{
if(ja != null)
{
ja.put(token instanceof String ? XML.stringToValue((String) token) : token);
}
}
}
}
/**
* Convert a well-formed (but not necessarily valid) XML string into a
* JSONArray using the JsonML transform. Each XML tag is represented as a
* JSONArray in which the first element is the tag name. If the tag has
* attributes, then the second element will be JSONObject containing the
* name/value pairs. If the tag contains children, then strings and
* JSONArrays will represent the child tags. Comments, prologs, DTDs, and
* <code>&lt;[ [ ]]></code> are ignored.
*
* @param string
* The source string.
* @return A JSONArray containing the structured data from the XML string.
* @throws JSONException
*/
public static JSONArray toJSONArray(String string) throws JSONException
{
return toJSONArray(new XMLTokener(string));
}
/**
* Convert a well-formed (but not necessarily valid) XML string into a
* JSONArray using the JsonML transform. Each XML tag is represented as a
* JSONArray in which the first element is the tag name. If the tag has
* attributes, then the second element will be JSONObject containing the
* name/value pairs. If the tag contains children, then strings and
* JSONArrays will represent the child content and tags. Comments, prologs,
* DTDs, and <code>&lt;[ [ ]]></code> are ignored.
*
* @param x
* An XMLTokener.
* @return A JSONArray containing the structured data from the XML string.
* @throws JSONException
*/
public static JSONArray toJSONArray(XMLTokener x) throws JSONException
{
return (JSONArray) parse(x, true, null);
}
/**
* Convert a well-formed (but not necessarily valid) XML string into a
* JSONObject using the JsonML transform. Each XML tag is represented as a
* JSONObject with a "tagName" property. If the tag has attributes, then the
* attributes will be in the JSONObject as properties. If the tag contains
* children, the object will have a "childNodes" property which will be an
* array of strings and JsonML JSONObjects.
*
* Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
*
* @param x
* An XMLTokener of the XML source text.
* @return A JSONObject containing the structured data from the XML string.
* @throws JSONException
*/
public static JSONObject toJSONObject(XMLTokener x) throws JSONException
{
return (JSONObject) parse(x, false, null);
}
/**
* Convert a well-formed (but not necessarily valid) XML string into a
* JSONObject using the JsonML transform. Each XML tag is represented as a
* JSONObject with a "tagName" property. If the tag has attributes, then the
* attributes will be in the JSONObject as properties. If the tag contains
* children, the object will have a "childNodes" property which will be an
* array of strings and JsonML JSONObjects.
*
* Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
*
* @param string
* The XML source text.
* @return A JSONObject containing the structured data from the XML string.
* @throws JSONException
*/
public static JSONObject toJSONObject(String string) throws JSONException
{
return toJSONObject(new XMLTokener(string));
}
/**
* Reverse the JSONML transformation, making an XML text from a JSONArray.
*
* @param ja
* A JSONArray.
* @return An XML string.
* @throws JSONException
*/
public static String toString(JSONArray ja) throws JSONException
{
int i;
JSONObject jo;
String key;
Iterator<String> keys;
int length;
Object object;
StringBuilder sb = new StringBuilder();
String tagName;
String value;
// Emit <tagName
tagName = ja.getString(0);
XML.noSpace(tagName);
tagName = XML.escape(tagName);
sb.append('<');
sb.append(tagName);
object = ja.opt(1);
if(object instanceof JSONObject)
{
i = 2;
jo = (JSONObject) object;
// Emit the attributes
keys = jo.keys();
while(keys.hasNext())
{
key = keys.next();
XML.noSpace(key);
value = jo.optString(key);
if(value != null)
{
sb.append(' ');
sb.append(XML.escape(key));
sb.append('=');
sb.append('"');
sb.append(XML.escape(value));
sb.append('"');
}
}
} else
{
i = 1;
}
// Emit content in body
length = ja.length();
if(i >= length)
{
sb.append('/');
sb.append('>');
} else
{
sb.append('>');
do
{
object = ja.get(i);
i += 1;
if(object != null)
{
if(object instanceof String)
{
sb.append(XML.escape(object.toString()));
} else if(object instanceof JSONObject)
{
sb.append(toString((JSONObject) object));
} else if(object instanceof JSONArray)
{
sb.append(toString((JSONArray) object));
} else
{
sb.append(object.toString());
}
}
} while(i < length);
sb.append('<');
sb.append('/');
sb.append(tagName);
sb.append('>');
}
return sb.toString();
}
/**
* Reverse the JSONML transformation, making an XML text from a JSONObject.
* The JSONObject must contain a "tagName" property. If it has children,
* then it must have a "childNodes" property containing an array of objects.
* The other properties are attributes with string values.
*
* @param jo
* A JSONObject.
* @return An XML string.
* @throws JSONException
*/
public static String toString(JSONObject jo) throws JSONException
{
StringBuilder sb = new StringBuilder();
int i;
JSONArray ja;
String key;
Iterator<String> keys;
int length;
Object object;
String tagName;
String value;
// Emit <tagName
tagName = jo.optString("tagName");
if(tagName == null)
{
return XML.escape(jo.toString());
}
XML.noSpace(tagName);
tagName = XML.escape(tagName);
sb.append('<');
sb.append(tagName);
// Emit the attributes
keys = jo.keys();
while(keys.hasNext())
{
key = keys.next();
if(!"tagName".equals(key) && !"childNodes".equals(key))
{
XML.noSpace(key);
value = jo.optString(key);
if(value != null)
{
sb.append(' ');
sb.append(XML.escape(key));
sb.append('=');
sb.append('"');
sb.append(XML.escape(value));
sb.append('"');
}
}
}
// Emit content in body
ja = jo.optJSONArray("childNodes");
if(ja == null)
{
sb.append('/');
sb.append('>');
} else
{
sb.append('>');
length = ja.length();
for(i = 0; i < length; i += 1)
{
object = ja.get(i);
if(object != null)
{
if(object instanceof String)
{
sb.append(XML.escape(object.toString()));
} else if(object instanceof JSONObject)
{
sb.append(toString((JSONObject) object));
} else if(object instanceof JSONArray)
{
sb.append(toString((JSONArray) object));
} else
{
sb.append(object.toString());
}
}
}
sb.append('<');
sb.append('/');
sb.append(tagName);
sb.append('>');
}
return sb.toString();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,21 @@
package com.volmit.iris.util;
/**
* The <code>JSONString</code> interface allows a <code>toJSONString()</code>
* method so that a class can change the behavior of
* <code>JSONObject.toString()</code>, <code>JSONArray.toString()</code>, and
* <code>JSONWriter.value(</code>Object<code>)</code>. The
* <code>toJSONString</code> method will be used instead of the default behavior
* of using the Object's <code>toString()</code> method and quoting the result.
*/
public interface JSONString
{
/**
* The <code>toJSONString</code> method allows a class to produce its own
* JSON serialization.
*
* @return A strictly syntactically correct JSON text.
*/
public String toJSONString();
}

View File

@@ -0,0 +1,86 @@
package com.volmit.iris.util;
/*
Copyright (c) 2006 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import java.io.StringWriter;
/**
* JSONStringer provides a quick and convenient way of producing JSON text. The
* texts produced strictly conform to JSON syntax rules. No whitespace is added,
* so the results are ready for transmission or storage. Each instance of
* JSONStringer can produce one JSON text.
* <p>
* A JSONStringer instance provides a <code>value</code> method for appending
* values to the text, and a <code>key</code> method for adding keys before
* values in objects. There are <code>array</code> and <code>endArray</code>
* methods that make and bound array values, and <code>object</code> and
* <code>endObject</code> methods which make and bound object values. All of
* these methods return the JSONWriter instance, permitting cascade style. For
* example,
*
* <pre>
* myString = new JSONStringer().object().key("JSON").value("Hello, World!").endObject().toString();
* </pre>
*
* which produces the string
*
* <pre>
* {"JSON":"Hello, World!"}
* </pre>
* <p>
* The first method called must be <code>array</code> or <code>object</code>.
* There are no methods for adding commas or colons. JSONStringer adds them for
* you. Objects and arrays can be nested up to 20 levels deep.
* <p>
* This can sometimes be easier than using a JSONObject to build a string.
*
* @author JSON.org
* @version 2008-09-18
*/
public class JSONStringer extends JSONWriter
{
/**
* Make a fresh JSONStringer. It can be used to build one JSON text.
*/
public JSONStringer()
{
super(new StringWriter());
}
/**
* Return the JSON text. This method is used to obtain the product of the
* JSONStringer instance. It will return <code>null</code> if there was a
* problem in the construction of the JSON text (such as the calls to
* <code>array</code> were not properly balanced with calls to
* <code>endArray</code>).
*
* @return The JSON text.
*/
public String toString()
{
return this.mode == 'd' ? this.writer.toString() : null;
}
}

View File

@@ -0,0 +1,504 @@
package com.volmit.iris.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
/*
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* A JSONTokener takes a source string and extracts characters and tokens from
* it. It is used by the JSONObject and JSONArray constructors to parse JSON
* source strings.
*
* @author JSON.org
* @version 2014-05-03
*/
public class JSONTokener
{
private long character;
private boolean eof;
private long index;
private long line;
private char previous;
private Reader reader;
private boolean usePrevious;
/**
* Construct a JSONTokener from a Reader.
*
* @param reader
* A reader.
*/
public JSONTokener(Reader reader)
{
this.reader = reader.markSupported() ? reader : new BufferedReader(reader);
this.eof = false;
this.usePrevious = false;
this.previous = 0;
this.index = 0;
this.character = 1;
this.line = 1;
}
/**
* Construct a JSONTokener from an InputStream.
*
* @param inputStream
* The source.
*/
public JSONTokener(InputStream inputStream) throws JSONException
{
this(new InputStreamReader(inputStream));
}
/**
* Construct a JSONTokener from a string.
*
* @param s
* A source string.
*/
public JSONTokener(String s)
{
this(new StringReader(s));
}
/**
* Back up one character. This provides a sort of lookahead capability, so
* that you can test for a digit or letter before attempting to parse the
* next number or identifier.
*/
public void back() throws JSONException
{
if(this.usePrevious || this.index <= 0)
{
throw new JSONException("Stepping back two steps is not supported");
}
this.index -= 1;
this.character -= 1;
this.usePrevious = true;
this.eof = false;
}
/**
* Get the hex value of a character (base16).
*
* @param c
* A character between '0' and '9' or between 'A' and 'F' or
* between 'a' and 'f'.
* @return An int between 0 and 15, or -1 if c was not a hex digit.
*/
public static int dehexchar(char c)
{
if(c >= '0' && c <= '9')
{
return c - '0';
}
if(c >= 'A' && c <= 'F')
{
return c - ('A' - 10);
}
if(c >= 'a' && c <= 'f')
{
return c - ('a' - 10);
}
return -1;
}
public boolean end()
{
return this.eof && !this.usePrevious;
}
/**
* Determine if the source string still contains characters that next() can
* consume.
*
* @return true if not yet at the end of the source.
*/
public boolean more() throws JSONException
{
this.next();
if(this.end())
{
return false;
}
this.back();
return true;
}
/**
* Get the next character in the source string.
*
* @return The next character, or 0 if past the end of the source string.
*/
public char next() throws JSONException
{
int c;
if(this.usePrevious)
{
this.usePrevious = false;
c = this.previous;
} else
{
try
{
c = this.reader.read();
} catch(IOException exception)
{
throw new JSONException(exception);
}
if(c <= 0)
{ // End of stream
this.eof = true;
c = 0;
}
}
this.index += 1;
if(this.previous == '\r')
{
this.line += 1;
this.character = c == '\n' ? 0 : 1;
} else if(c == '\n')
{
this.line += 1;
this.character = 0;
} else
{
this.character += 1;
}
this.previous = (char) c;
return this.previous;
}
/**
* Consume the next character, and check that it matches a specified
* character.
*
* @param c
* The character to match.
* @return The character.
* @throws JSONException
* if the character does not match.
*/
public char next(char c) throws JSONException
{
char n = this.next();
if(n != c)
{
throw this.syntaxError("Expected '" + c + "' and instead saw '" + n + "'");
}
return n;
}
/**
* Get the next n characters.
*
* @param n
* The number of characters to take.
* @return A string of n characters.
* @throws JSONException
* Substring bounds error if there are not n characters
* remaining in the source string.
*/
public String next(int n) throws JSONException
{
if(n == 0)
{
return "";
}
char[] chars = new char[n];
int pos = 0;
while(pos < n)
{
chars[pos] = this.next();
if(this.end())
{
throw this.syntaxError("Substring bounds error");
}
pos += 1;
}
return new String(chars);
}
/**
* Get the next char in the string, skipping whitespace.
*
* @throws JSONException
* @return A character, or 0 if there are no more characters.
*/
public char nextClean() throws JSONException
{
for(;;)
{
char c = this.next();
if(c == 0 || c > ' ')
{
return c;
}
}
}
/**
* Return the characters up to the next close quote character. Backslash
* processing is done. The formal JSON format does not allow strings in
* single quotes, but an implementation is allowed to accept them.
*
* @param quote
* The quoting character, either <code>"</code>&nbsp;
* <small>(double quote)</small> or <code>'</code>&nbsp;
* <small>(single quote)</small>.
* @return A String.
* @throws JSONException
* Unterminated string.
*/
public String nextString(char quote) throws JSONException
{
char c;
StringBuilder sb = new StringBuilder();
for(;;)
{
c = this.next();
switch(c)
{
case 0:
case '\n':
case '\r':
throw this.syntaxError("Unterminated string");
case '\\':
c = this.next();
switch(c)
{
case 'b':
sb.append('\b');
break;
case 't':
sb.append('\t');
break;
case 'n':
sb.append('\n');
break;
case 'f':
sb.append('\f');
break;
case 'r':
sb.append('\r');
break;
case 'u':
sb.append((char) Integer.parseInt(this.next(4), 16));
break;
case '"':
case '\'':
case '\\':
case '/':
sb.append(c);
break;
default:
throw this.syntaxError("Illegal escape.");
}
break;
default:
if(c == quote)
{
return sb.toString();
}
sb.append(c);
}
}
}
/**
* Get the text up but not including the specified character or the end of
* line, whichever comes first.
*
* @param delimiter
* A delimiter character.
* @return A string.
*/
public String nextTo(char delimiter) throws JSONException
{
StringBuilder sb = new StringBuilder();
for(;;)
{
char c = this.next();
if(c == delimiter || c == 0 || c == '\n' || c == '\r')
{
if(c != 0)
{
this.back();
}
return sb.toString().trim();
}
sb.append(c);
}
}
/**
* Get the text up but not including one of the specified delimiter
* characters or the end of line, whichever comes first.
*
* @param delimiters
* A set of delimiter characters.
* @return A string, trimmed.
*/
public String nextTo(String delimiters) throws JSONException
{
char c;
StringBuilder sb = new StringBuilder();
for(;;)
{
c = this.next();
if(delimiters.indexOf(c) >= 0 || c == 0 || c == '\n' || c == '\r')
{
if(c != 0)
{
this.back();
}
return sb.toString().trim();
}
sb.append(c);
}
}
/**
* Get the next value. The value can be a Boolean, Double, Integer,
* JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object.
*
* @throws JSONException
* If syntax error.
*
* @return An object.
*/
public Object nextValue() throws JSONException
{
char c = this.nextClean();
String string;
switch(c)
{
case '"':
case '\'':
return this.nextString(c);
case '{':
this.back();
return new JSONObject(this);
case '[':
this.back();
return new JSONArray(this);
}
/*
* Handle unquoted text. This could be the values true, false, or null,
* or it can be a number. An implementation (such as this one) is
* allowed to also accept non-standard forms.
*
* Accumulate characters until we reach the end of the text or a
* formatting character.
*/
StringBuilder sb = new StringBuilder();
while(c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0)
{
sb.append(c);
c = this.next();
}
this.back();
string = sb.toString().trim();
if("".equals(string))
{
throw this.syntaxError("Missing value");
}
return JSONObject.stringToValue(string);
}
/**
* Skip characters until the next character is the requested character. If
* the requested character is not found, no characters are skipped.
*
* @param to
* A character to skip to.
* @return The requested character, or zero if the requested character is
* not found.
*/
public char skipTo(char to) throws JSONException
{
char c;
try
{
long startIndex = this.index;
long startCharacter = this.character;
long startLine = this.line;
this.reader.mark(1000000);
do
{
c = this.next();
if(c == 0)
{
this.reader.reset();
this.index = startIndex;
this.character = startCharacter;
this.line = startLine;
return c;
}
} while(c != to);
} catch(IOException exception)
{
throw new JSONException(exception);
}
this.back();
return c;
}
/**
* Make a JSONException to signal a syntax error.
*
* @param message
* The error message.
* @return A JSONException object, suitable for throwing
*/
public JSONException syntaxError(String message)
{
return new JSONException(message + this.toString());
}
/**
* Make a printable string of this JSONTokener.
*
* @return " at {index} [character {character} line {line}]"
*/
public String toString()
{
return " at " + this.index + " [character " + this.character + " line " + this.line + "]";
}
}

View File

@@ -0,0 +1,388 @@
package com.volmit.iris.util;
import java.io.IOException;
import java.io.Writer;
/*
Copyright (c) 2006 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* JSONWriter provides a quick and convenient way of producing JSON text. The
* texts produced strictly conform to JSON syntax rules. No whitespace is added,
* so the results are ready for transmission or storage. Each instance of
* JSONWriter can produce one JSON text.
* <p>
* A JSONWriter instance provides a <code>value</code> method for appending
* values to the text, and a <code>key</code> method for adding keys before
* values in objects. There are <code>array</code> and <code>endArray</code>
* methods that make and bound array values, and <code>object</code> and
* <code>endObject</code> methods which make and bound object values. All of
* these methods return the JSONWriter instance, permitting a cascade style. For
* example,
*
* <pre>
* new JSONWriter(myWriter).object().key("JSON").value("Hello, World!").endObject();
* </pre>
*
* which writes
*
* <pre>
* {"JSON":"Hello, World!"}
* </pre>
* <p>
* The first method called must be <code>array</code> or <code>object</code>.
* There are no methods for adding commas or colons. JSONWriter adds them for
* you. Objects and arrays can be nested up to 20 levels deep.
* <p>
* This can sometimes be easier than using a JSONObject to build a string.
*
* @author JSON.org
* @version 2011-11-24
*/
public class JSONWriter
{
private static final int maxdepth = 200;
/**
* The comma flag determines if a comma should be output before the next
* value.
*/
private boolean comma;
/**
* The current mode. Values: 'a' (array), 'd' (done), 'i' (initial), 'k'
* (key), 'o' (object).
*/
protected char mode;
/**
* The object/array stack.
*/
private final JSONObject stack[];
/**
* The stack top index. A value of 0 indicates that the stack is empty.
*/
private int top;
/**
* The writer that will receive the output.
*/
protected Writer writer;
/**
* Make a fresh JSONWriter. It can be used to build one JSON text.
*/
public JSONWriter(Writer w)
{
this.comma = false;
this.mode = 'i';
this.stack = new JSONObject[maxdepth];
this.top = 0;
this.writer = w;
}
/**
* Append a value.
*
* @param string
* A string value.
* @return this
* @throws JSONException
* If the value is out of sequence.
*/
private JSONWriter append(String string) throws JSONException
{
if(string == null)
{
throw new JSONException("Null pointer");
}
if(this.mode == 'o' || this.mode == 'a')
{
try
{
if(this.comma && this.mode == 'a')
{
this.writer.write(',');
}
this.writer.write(string);
} catch(IOException e)
{
throw new JSONException(e);
}
if(this.mode == 'o')
{
this.mode = 'k';
}
this.comma = true;
return this;
}
throw new JSONException("Value out of sequence.");
}
/**
* Begin appending a new array. All values until the balancing
* <code>endArray</code> will be appended to this array. The
* <code>endArray</code> method must be called to mark the array's end.
*
* @return this
* @throws JSONException
* If the nesting is too deep, or if the object is started in
* the wrong place (for example as a key or after the end of the
* outermost array or object).
*/
public JSONWriter array() throws JSONException
{
if(this.mode == 'i' || this.mode == 'o' || this.mode == 'a')
{
this.push(null);
this.append("[");
this.comma = false;
return this;
}
throw new JSONException("Misplaced array.");
}
/**
* End something.
*
* @param mode
* Mode
* @param c
* Closing character
* @return this
* @throws JSONException
* If unbalanced.
*/
private JSONWriter end(char mode, char c) throws JSONException
{
if(this.mode != mode)
{
throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject.");
}
this.pop(mode);
try
{
this.writer.write(c);
} catch(IOException e)
{
throw new JSONException(e);
}
this.comma = true;
return this;
}
/**
* End an array. This method most be called to balance calls to
* <code>array</code>.
*
* @return this
* @throws JSONException
* If incorrectly nested.
*/
public JSONWriter endArray() throws JSONException
{
return this.end('a', ']');
}
/**
* End an object. This method most be called to balance calls to
* <code>object</code>.
*
* @return this
* @throws JSONException
* If incorrectly nested.
*/
public JSONWriter endObject() throws JSONException
{
return this.end('k', '}');
}
/**
* Append a key. The key will be associated with the next value. In an
* object, every value must be preceded by a key.
*
* @param string
* A key string.
* @return this
* @throws JSONException
* If the key is out of place. For example, keys do not belong
* in arrays or if the key is null.
*/
public JSONWriter key(String string) throws JSONException
{
if(string == null)
{
throw new JSONException("Null key.");
}
if(this.mode == 'k')
{
try
{
this.stack[this.top - 1].putOnce(string, Boolean.TRUE);
if(this.comma)
{
this.writer.write(',');
}
this.writer.write(JSONObject.quote(string));
this.writer.write(':');
this.comma = false;
this.mode = 'o';
return this;
} catch(IOException e)
{
throw new JSONException(e);
}
}
throw new JSONException("Misplaced key.");
}
/**
* Begin appending a new object. All keys and values until the balancing
* <code>endObject</code> will be appended to this object. The
* <code>endObject</code> method must be called to mark the object's end.
*
* @return this
* @throws JSONException
* If the nesting is too deep, or if the object is started in
* the wrong place (for example as a key or after the end of the
* outermost array or object).
*/
public JSONWriter object() throws JSONException
{
if(this.mode == 'i')
{
this.mode = 'o';
}
if(this.mode == 'o' || this.mode == 'a')
{
this.append("{");
this.push(new JSONObject());
this.comma = false;
return this;
}
throw new JSONException("Misplaced object.");
}
/**
* Pop an array or object scope.
*
* @param c
* The scope to close.
* @throws JSONException
* If nesting is wrong.
*/
private void pop(char c) throws JSONException
{
if(this.top <= 0)
{
throw new JSONException("Nesting error.");
}
char m = this.stack[this.top - 1] == null ? 'a' : 'k';
if(m != c)
{
throw new JSONException("Nesting error.");
}
this.top -= 1;
this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k';
}
/**
* Push an array or object scope.
*
* @param jo
* The scope to open.
* @throws JSONException
* If nesting is too deep.
*/
private void push(JSONObject jo) throws JSONException
{
if(this.top >= maxdepth)
{
throw new JSONException("Nesting too deep.");
}
this.stack[this.top] = jo;
this.mode = jo == null ? 'a' : 'k';
this.top += 1;
}
/**
* Append either the value <code>true</code> or the value <code>false</code>
* .
*
* @param b
* A boolean.
* @return this
* @throws JSONException
*/
public JSONWriter value(boolean b) throws JSONException
{
return this.append(b ? "true" : "false");
}
/**
* Append a double value.
*
* @param d
* A double.
* @return this
* @throws JSONException
* If the number is not finite.
*/
public JSONWriter value(double d) throws JSONException
{
return this.value(new Double(d));
}
/**
* Append a long value.
*
* @param l
* A long.
* @return this
* @throws JSONException
*/
public JSONWriter value(long l) throws JSONException
{
return this.append(Long.toString(l));
}
/**
* Append an object value.
*
* @param object
* The object to append. It can be null, or a Boolean, Number,
* String, JSONObject, or JSONArray, or an object that implements
* JSONString.
* @return this
* @throws JSONException
* If the value is out of sequence.
*/
public JSONWriter value(Object object) throws JSONException
{
return this.append(JSONObject.valueToString(object));
}
}

View File

@@ -0,0 +1,89 @@
package com.volmit.iris.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class JarScanner
{
private final KSet<Class<?>> classes;
private final File jar;
private final String superPackage;
/**
* Create a scanner
*
* @param jar
* the path to the jar
*/
public JarScanner(File jar, String superPackage)
{
this.jar = jar;
this.classes = new KSet<Class<?>>();
this.superPackage = superPackage;
}
/**
* Scan the jar
*
* @throws IOException
* bad things happen
*/
public void scan() throws IOException
{
classes.clear();
FileInputStream fin = new FileInputStream(jar);
ZipInputStream zip = new ZipInputStream(fin);
for(ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry())
{
if(!entry.isDirectory() && entry.getName().endsWith(".class"))
{
if(entry.getName().contains("$"))
{
continue;
}
String c = entry.getName().replaceAll("/", ".").replace(".class", "");
if(c.startsWith(superPackage))
{
try
{
Class<?> clazz = Class.forName(c);
classes.add(clazz);
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
}
zip.close();
}
/**
* Get the scanned clases
*
* @return a gset of classes
*/
public KSet<Class<?>> getClasses()
{
return classes;
}
/**
* Get the file object for the jar
*
* @return a file object representing the jar
*/
public File getJar()
{
return jar;
}
}

View File

@@ -0,0 +1,666 @@
package com.volmit.iris.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.function.Function;
public class KList<T> extends ArrayList<T> implements List<T>
{
private static final long serialVersionUID = -2892550695744823337L;
@SafeVarargs
public KList(T... ts)
{
super();
add(ts);
}
public KList()
{
super();
}
public KList(Collection<T> values)
{
super();
add(values);
}
public KList(Enumeration<T> e)
{
super();
add(e);
}
/**
* Remove the last element
*/
public KList<T> removeLast()
{
remove(last());
return this;
}
private KList<T> add(Enumeration<T> e)
{
while(e.hasMoreElements())
{
add(e.nextElement());
}
return this;
}
public KList<T> add(Collection<T> values)
{
addAll(values);
return this;
}
/**
* Create a Map out of this list where this list becomes the values of the
* returned map. You must specify each key for each value in this list. In the
* function, returning null will not add the keyval pair.
*
* @param <K>
* the inferred key type
* @param f
* the function
* @return the new map
*/
public <K> KMap<K, T> asValues(Function<T, K> f)
{
KMap<K, T> m = new KMap<K, T>();
forEach((i) -> m.putNonNull(f.apply(i), i));
return m;
}
/**
* Create a Map out of this list where this list becomes the keys of the
* returned map. You must specify each value for each key in this list. In the
* function, returning null will not add the keyval pair.
*
* @param <V>
* the inferred value type
* @param f
* the function
* @return the new map
*/
public <V> KMap<T, V> asKeys(Function<T, V> f)
{
KMap<T, V> m = new KMap<T, V>();
forEach((i) -> m.putNonNull(i, f.apply(i)));
return m;
}
/**
* Cut this list into targetCount sublists
*
* @param targetCount
* the target count of sublists
* @return the list of sublists
*/
public KList<KList<T>> divide(int targetCount)
{
return split(size() / targetCount);
}
/**
* Split this list into a list of sublists with roughly targetSize elements of T
* per sublist
*
* @param targetSize
* the target size
* @return the list of sublists
*/
public KList<KList<T>> split(int targetSize)
{
targetSize = targetSize < 1 ? 1 : targetSize;
KList<KList<T>> gg = new KList<>();
KList<T> b = new KList<>();
for(T i : this)
{
if(b.size() >= targetSize)
{
gg.add(b.copy());
b.clear();
}
b.add(i);
}
if(!b.isEmpty())
{
gg.add(b);
}
return gg;
}
/**
* Rewrite this list by checking each value and changing the value (or not).
* Return null to remove the element in the function
*
* @param t
* the function
* @return the same list (not a copy)
*/
public KList<T> rewrite(Function<T, T> t)
{
KList<T> m = copy();
clear();
for(T i : m)
{
addNonNull(t.apply(i));
}
return this;
}
/**
* To array
*
* @return the array
*/
@SuppressWarnings("unchecked")
public T[] array()
{
return (T[]) toArray();
}
/**
* Return a copy of this list
*
* @return the copy
*/
public KList<T> copy()
{
return new KList<T>().add(this);
}
/**
* Shuffle the list
*
* @return the same list
*/
public KList<T> shuffle()
{
Collections.shuffle(this);
return this;
}
/**
* Sort the list (based on toString comparison)
*
* @return the same list
*/
public KList<T> sort()
{
Collections.sort(this, (a, b) -> a.toString().compareTo(b.toString()));
return this;
}
/**
* Reverse this list
*
* @return the same list
*/
public KList<T> reverse()
{
Collections.reverse(this);
return this;
}
@Override
public String toString()
{
return "[" + toString(", ") + "]";
}
/**
* Tostring with a seperator for each item in the list
*
* @param split
* the seperator
* @return the string representing this object
*/
public String toString(String split)
{
if(isEmpty())
{
return "";
}
if(size() == 1)
{
return get(0).toString();
}
StringBuilder b = new StringBuilder();
for(String i : toStringList())
{
b.append(split + i);
}
return b.toString().substring(split.length());
}
/**
* Invoke tostring on each value in the list into a string list
*
* @return the string list
*/
public KList<String> toStringList()
{
return convert((t) -> t.toString());
}
/**
* Add the contents of the given list (v) into this list using a converter
*
* @param <V>
* the type of the forign list
* @param v
* the forign (given) list
* @param converter
* the converter that converts the forign type into this list type
* @return this list (builder)
*/
public <V> KList<T> addFrom(List<V> v, Function<V, T> converter)
{
v.forEach((g) -> add(converter.apply(g)));
return this;
}
/**
* Convert this list into another list type. Such as GList<Integer> to
* GList<String>. list.convert((i) -> "" + i);
*
* @param <V>
* @param converter
* @return
*/
public <V> KList<V> convert(Function<T, V> converter)
{
KList<V> v = new KList<V>();
forEach((t) -> v.addNonNull(converter.apply(t)));
return v;
}
/**
* Adds T to the list, ignores if null
*
* @param t
* the value to add
* @return the same list
*/
public KList<T> addNonNull(T t)
{
if(t != null)
{
super.add(t);
}
return this;
}
/**
* Swaps the values of index a and b. For example "hello", "world", "!" swap(1,
* 2) would change the list to "hello", "!", "world"
*
* @param a
* the first index
* @param b
* the second index
* @return the same list (builder), not a copy
*/
public KList<T> swapIndexes(int a, int b)
{
T aa = remove(a);
T bb = get(b);
add(a, bb);
remove(b);
add(b, aa);
return this;
}
/**
* Remove a number of elements from the list
*
* @param t
* the elements
* @return this list
*/
@SuppressWarnings("unchecked")
public KList<T> remove(T... t)
{
for(T i : t)
{
super.remove(i);
}
return this;
}
/**
* Add another glist's contents to this one (addall builder)
*
* @param t
* the list
* @return the same list
*/
public KList<T> add(KList<T> t)
{
super.addAll(t);
return this;
}
/**
* Add a number of values to this list
*
* @param t
* the list
* @return this list
*/
@SuppressWarnings("unchecked")
public KList<T> add(T... t)
{
for(T i : t)
{
super.add(i);
}
return this;
}
/**
* Check if this list has an index at the given index
*
* @param index
* the given index
* @return true if size > index
*/
public boolean hasIndex(int index)
{
return size() > index && index >= 0;
}
/**
* Get the last index of this list (size - 1)
*
* @return the last index of this list
*/
public int last()
{
return size() - 1;
}
/**
* Deduplicate this list by converting to linked hash set and back
*
* @return the deduplicated list
*/
public KList<T> dedupe()
{
LinkedHashSet<T> lhs = new LinkedHashSet<T>(this);
return qclear().add(lhs);
}
/**
* Clear this list (and return it)
*
* @return the same list
*/
public KList<T> qclear()
{
super.clear();
return this;
}
/**
* Simply !isEmpty()
*
* @return true if this list has 1 or more element(s)
*/
public boolean hasElements()
{
return !isEmpty();
}
/**
* Simply !isEmpty()
*
* @return true if this list has 1 or more element(s)
*/
public boolean isNotEmpty()
{
return !isEmpty();
}
/**
* Pop the first item off this list and return it
*
* @return the popped off item or null if the list is empty
*/
public T pop()
{
if(isEmpty())
{
return null;
}
return remove(0);
}
/**
* Pop the last item off this list and return it
*
* @return the popped off item or null if the list is empty
*/
public T popLast()
{
if(isEmpty())
{
return null;
}
return remove(last());
}
public T popRandom()
{
if(isEmpty())
{
return null;
}
if(size() == 1)
{
return pop();
}
return remove(M.irand(0, last()));
}
public static KList<String> fromJSONAny(JSONArray oo)
{
KList<String> s = new KList<String>();
for(int i = 0; i < oo.length(); i++)
{
s.add(oo.get(i).toString());
}
return s;
}
public KList<T> sub(int f, int t)
{
KList<T> g = new KList<>();
for(int i = f; i < M.min(size(), t); i++)
{
g.add(get(i));
}
return g;
}
public JSONArray toJSONStringArray()
{
JSONArray j = new JSONArray();
for(Object i : this)
{
j.put(i.toString());
}
return j;
}
public static KList<String> asStringList(List<?> oo)
{
KList<String> s = new KList<String>();
for(Object i : oo)
{
s.add(i.toString());
}
return s;
}
@SuppressWarnings("unchecked")
public KList<T> forceAdd(Object[] values)
{
for(Object i : values)
{
add((T) i);
}
return this;
}
@SuppressWarnings("unchecked")
public KList<T> forceAdd(int[] values)
{
for(Object i : values)
{
add((T) i);
}
return this;
}
@SuppressWarnings("unchecked")
public KList<T> forceAdd(double[] values)
{
for(Object i : values)
{
add((T) i);
}
return this;
}
@SuppressWarnings("unchecked")
public KList<T> forceAdd(float[] values)
{
for(Object i : values)
{
add((T) i);
}
return this;
}
@SuppressWarnings("unchecked")
public KList<T> forceAdd(byte[] values)
{
for(Object i : values)
{
add((T) i);
}
return this;
}
@SuppressWarnings("unchecked")
public KList<T> forceAdd(short[] values)
{
for(Object i : values)
{
add((T) i);
}
return this;
}
@SuppressWarnings("unchecked")
public KList<T> forceAdd(long[] values)
{
for(Object i : values)
{
add((T) i);
}
return this;
}
@SuppressWarnings("unchecked")
public KList<T> forceAdd(boolean[] values)
{
for(Object i : values)
{
add((T) i);
}
return this;
}
public T middleValue()
{
return get(middleIndex());
}
private int middleIndex()
{
return size() % 2 == 0 ? (size() / 2) : ((size() / 2) + 1);
}
public T getRandom()
{
if(isEmpty())
{
return null;
}
if(size() == 1)
{
return get(0);
}
return get(M.irand(0, last()));
}
public KList<T> qdel(T t)
{
remove(t);
return this;
}
public KList<T> qadd(T t)
{
add(t);
return this;
}
}

View File

@@ -0,0 +1,424 @@
package com.volmit.iris.util;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class KMap<K, V> extends ConcurrentHashMap<K, V>
{
private static final long serialVersionUID = 7288942695300448163L;
public KMap()
{
super();
}
public KMap(KMap<K, V> gMap)
{
this();
put(gMap);
}
/**
* Puts a value into a map-value-list based on the key such that if GMap<K,
* GList<S>> where V is GList<S>
*
* @param <S>
* the list type in the value type
* @param k
* the key to look for
* @param vs
* the values to put into the list of the given key
* @return the same list (builder)
*/
@SuppressWarnings("unchecked")
public <S> KMap<K, V> putValueList(K k, S... vs)
{
try
{
KMap<K, KList<S>> s = (KMap<K, KList<S>>) this;
if(!s.containsKey(k))
{
s.put(k, new KList<S>());
}
s.get(k).add(vs);
}
catch(Throwable e)
{
}
return this;
}
/**
* Returns a sorted list of keys from this map, based on the sorting order of
* the values.
*
* @return the value-sorted key list
*/
public KList<K> sortK()
{
KList<K> k = new KList<K>();
KList<V> v = v();
Collections.sort(v, new Comparator<V>()
{
@Override
public int compare(V v, V t1)
{
return v.toString().compareTo(t1.toString());
}
});
for(V i : v)
{
for(K j : k())
{
if(get(j).equals(i))
{
k.add(j);
}
}
}
k.dedupe();
return k;
}
/**
* Returns a sorted list of keys from this map, based on the sorting order of
* the values. Sorting is based on numerical values
*
* @return the value-sorted key list
*/
public KList<K> sortKNumber()
{
KList<K> k = new KList<K>();
KList<V> v = v();
Collections.sort(v, new Comparator<V>()
{
@Override
public int compare(V v, V t1)
{
Number n1 = (Number) v;
Number n2 = (Number) t1;
return (int) ((n1.doubleValue() - n2.doubleValue()) * 1000);
}
});
for(V i : v)
{
for(K j : k())
{
if(get(j).equals(i))
{
k.add(j);
}
}
}
k.dedupe();
return k;
}
/**
* Put another map's values into this map
*
* @param m
* the map to insert
* @return this map (builder)
*/
public KMap<K, V> put(Map<K, V> m)
{
putAll(m);
return this;
}
/**
* Return a copy of this map
*
* @return the copied map
*/
public KMap<K, V> copy()
{
return new KMap<K, V>(this);
}
/**
* Loop through each keyvalue set (copy of it) with the map parameter
*
* @param f
* the function
* @return the same gmap
*/
public KMap<K, V> rewrite(Consumer3<K, V, KMap<K, V>> f)
{
KMap<K, V> m = copy();
for(K i : m.k())
{
f.accept(i, get(i), this);
}
return this;
}
/**
* Loop through each keyvalue set (copy of it)
*
* @param f
* the function
* @return the same gmap
*/
public KMap<K, V> each(Consumer2<K, V> f)
{
for(K i : k())
{
f.accept(i, get(i));
}
return this;
}
/**
* Flip the hashmap and flatten the value list even if there are multiple keys
*
* @return the flipped and flattened hashmap
*/
public KMap<V, K> flipFlatten()
{
KMap<V, KList<K>> f = flip();
KMap<V, K> m = new KMap<>();
for(V i : f.k())
{
m.putNonNull(i, m.isEmpty() ? null : m.get(0));
}
return m;
}
/**
* Flip the hashmap so keys are now list-keys in the value position
*
* @return the flipped hashmap
*/
public KMap<V, KList<K>> flip()
{
KMap<V, KList<K>> flipped = new KMap<V, KList<K>>();
for(K i : keySet())
{
if(i == null)
{
continue;
}
if(!flipped.containsKey(get(i)))
{
flipped.put(get(i), new KList<K>());
}
flipped.get(get(i)).add(i);
}
return flipped;
}
/**
* Sort values based on the keys sorting order
*
* @return the values (sorted)
*/
public KList<V> sortV()
{
KList<V> v = new KList<V>();
KList<K> k = k();
Collections.sort(k, new Comparator<K>()
{
@Override
public int compare(K v, K t1)
{
return v.toString().compareTo(t1.toString());
}
});
for(K i : k)
{
for(V j : v())
{
if(get(i).equals(j))
{
v.add(j);
}
}
}
v.dedupe();
return v;
}
public KList<V> sortVNoDedupe()
{
KList<V> v = new KList<V>();
KList<K> k = k();
Collections.sort(k, new Comparator<K>()
{
@Override
public int compare(K v, K t1)
{
return v.toString().compareTo(t1.toString());
}
});
for(K i : k)
{
for(V j : v())
{
if(get(i).equals(j))
{
v.add(j);
}
}
}
return v;
}
/**
* Get a copy of this maps keys
*
* @return the keys
*/
public KList<K> k()
{
KList<K> k = new KList<K>();
Enumeration<K> kk = keys();
while(kk.hasMoreElements())
{
K kkk = kk.nextElement();
k.add(kkk);
}
return k;
}
/**
* Get a copy of this maps values
*
* @return the values
*/
public KList<V> v()
{
return new KList<V>(values());
}
/**
* Still works as it normally should except it returns itself (builder)
*
* @param key
* the key
* @param value
* the value (single only supported)
* @return
*/
public KMap<K, V> qput(K key, V value)
{
super.put(key, value);
return this;
}
/**
* Works just like put, except it wont put anything unless the key and value are
* nonnull
*
* @param key
* the nonnull key
* @param value
* the nonnull value
* @return the same map
*/
public KMap<K, V> putNonNull(K key, V value)
{
if(key != null || value != null)
{
put(key, value);
}
return this;
}
public V putThen(K key, V valueIfKeyNotPresent)
{
if(!containsKey(key))
{
put(key, valueIfKeyNotPresent);
}
return get(key);
}
/**
* Clear this map and return it
*
* @return the cleared map
*/
public KMap<K, V> qclear()
{
super.clear();
return this;
}
/**
* Convert this map to keypairs
*
* @return the keypair list
*/
public KList<KeyPair<K, V>> keypair()
{
KList<KeyPair<K, V>> g = new KList<>();
each((k, v) -> g.add(new KeyPair<K, V>(k, v)));
return g;
}
/**
* Create a keypair queue
*
* @return the queue
*/
public Queue<KeyPair<K, V>> enqueue()
{
return Queue.create(keypair());
}
/**
* Create a key queue
*
* @return the queue
*/
public Queue<K> enqueueKeys()
{
return Queue.create(k());
}
/**
* Create a value queue
*
* @return the queue
*/
public Queue<V> enqueueValues()
{
return Queue.create(v());
}
}

View File

@@ -0,0 +1,29 @@
package com.volmit.iris.util;
import java.util.Collection;
import java.util.HashSet;
public class KSet<T> extends HashSet<T>
{
private static final long serialVersionUID = 1L;
public KSet()
{
super();
}
public KSet(Collection<? extends T> c)
{
super(c);
}
public KSet(int initialCapacity, float loadFactor)
{
super(initialCapacity, loadFactor);
}
public KSet(int initialCapacity)
{
super(initialCapacity);
}
}

View File

@@ -0,0 +1,45 @@
package com.volmit.iris.util;
/**
* Represents a keypair
* @author cyberpwn
*
* @param <K> the key type
* @param <V> the value type
*/
public class KeyPair<K, V>
{
private K k;
private V v;
/**
* Create a keypair
* @param k the key
* @param v the value
*/
public KeyPair(K k, V v)
{
this.k = k;
this.v = v;
}
public K getK()
{
return k;
}
public void setK(K k)
{
this.k = k;
}
public V getV()
{
return v;
}
public void setV(V v)
{
this.v = v;
}
}

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
/*
* JNBT License

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
/*
* JNBT License

View File

@@ -0,0 +1,38 @@
package com.volmit.iris.util;
import com.volmit.iris.Iris;
public abstract class Looper extends Thread
{
public void run()
{
while(!interrupted())
{
try
{
long m = loop();
if(m < 0)
{
break;
}
Thread.sleep(m);
}
catch(InterruptedException e)
{
break;
}
catch(Throwable e)
{
e.printStackTrace();
}
}
Iris.info("Thread " + getName() + " Shutdown.");
}
protected abstract long loop();
}

View File

@@ -0,0 +1,443 @@
package com.volmit.iris.util;
import java.util.regex.Matcher;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
/**
* Math
*
* @author cyberpwn
*/
public class M
{
private static final int precision = 128;
private static final int modulus = 360 * precision;
private static final float[] sin = new float[modulus];
/**
* Scales B by an external range change so that <br/>
* <br/>
* BMIN < B < BMAX <br/>
* AMIN < RESULT < AMAX <br/>
* <br/>
* So Given rangeScale(0, 20, 0, 10, 5) -> 10 <br/>
* 0 < 5 < 10 <br/>
* 0 < ? < 20 <br/>
* <br/>
* would return 10
*
* @param amin
* the resulting minimum
* @param amax
* the resulting maximum
* @param bmin
* the initial minimum
* @param bmax
* the initial maximum
* @param b
* the initial value
* @return the resulting value
*/
public static double rangeScale(double amin, double amax, double bmin, double bmax, double b)
{
return amin + ((amax - amin) * ((b - bmin) / (bmax - bmin)));
}
/**
* Get the percent (inverse lerp) from "from" to "to" where "at".
*
* If from = 0 and to = 100 and at = 25 then it would return 0.25
*
* @param from
* the from
* @param to
* the to
* @param at
* the at
* @return the percent
*/
public static double lerpInverse(double from, double to, double at)
{
return M.rangeScale(0, 1, from, to, at);
}
/**
* Linear interpolation from a to b where f is the percent across
*
* @param a
* the first pos (0)
* @param b
* the second pos (1)
* @param f
* the percent
* @return the value
*/
public static double lerp(double a, double b, double f)
{
return a + (f * (b - a));
}
/**
* Bilinear interpolation
*
* @param a
* the first point (0, 0)
* @param b
* the second point (1, 0)
* @param c
* the third point (0, 1)
* @param d
* the fourth point (1, 1)
* @param tx
* the x
* @param ty
* the y
* @return the bilerped value
*/
public static double bilerp(double a, double b, double c, double d, double x, double y)
{
return lerp(lerp(a, b, x), lerp(c, d, x), y);
}
/**
* Trilinear interpolation
*
* @param a
* the first point (0, 0, 0)
* @param b
* the second point (1, 0, 0)
* @param c
* the third point (0, 0, 1)
* @param d
* the fourth point (1, 0, 1)
* @param e
* the fifth point (0, 1, 0)
* @param f
* the sixth point (1, 1, 0)
* @param g
* the seventh point (0, 1, 1)
* @param h
* the eighth point (1, 1, 1)
* @param x
* the x
* @param y
* the y
* @param z
* the z
* @return the trilerped value
*/
public static double trilerp(double a, double b, double c, double d, double e, double f, double g, double h, double x, double y, double z)
{
return lerp(bilerp(a, b, c, d, x, y), bilerp(e, f, g, h, x, y), z);
}
/**
* Clip a value
*
* @param value
* the value
* @param min
* the min
* @param max
* the max
* @return the clipped value
*/
@SuppressWarnings("unchecked")
public static <T extends Number> T clip(T value, T min, T max)
{
return (T) Double.valueOf(Math.min(max.doubleValue(), Math.max(min.doubleValue(), value.doubleValue())));
}
/**
* Get true or false based on random percent
*
* @param d
* between 0 and 1
* @return true if true
*/
public static boolean r(Double d)
{
if(d == null)
{
return Math.random() < 0.5;
}
return Math.random() < d;
}
/**
* Get the ticks per second from a time in nanoseconds, the rad can be used for
* multiple ticks
*
* @param ns
* the time in nanoseconds
* @param rad
* the radius of the time
* @return the ticks per second in double form
*/
public static double tps(long ns, int rad)
{
return (20.0 * (ns / 50000000.0)) / rad;
}
/**
* Get the number of ticks from a time in nanoseconds
*
* @param ns
* the nanoseconds
* @return the amount of ticks
*/
public static double ticksFromNS(long ns)
{
return (ns / 50000000.0);
}
/**
* Get a random int from to (inclusive)
*
* @param f
* the from
* @param t
* the to
* @return the value
*/
public static int irand(int f, int t)
{
return f + (int) (Math.random() * ((t - f) + 1));
}
/**
* Get a random float from to (inclusive)
*
* @param f
* the from
* @param t
* the to
* @return the value
*/
public static float frand(float f, float t)
{
return f + (float) (Math.random() * ((t - f) + 1));
}
/**
* Get a random double from to (inclusive)
*
* @param f
* the from
* @param t
* the to
* @return the value
*/
public static double drand(double f, double t)
{
return f + (Math.random() * ((t - f) + 1));
}
/**
* Get system Nanoseconds
*
* @return nanoseconds (current)
*/
public static long ns()
{
return System.nanoTime();
}
/**
* Get the current millisecond time
*
* @return milliseconds
*/
public static long ms()
{
return System.currentTimeMillis();
}
/**
* Fast sin function
*
* @param a
* the number
* @return the sin
*/
public static float sin(float a)
{
return sinLookup((int) (a * precision + 0.5f));
}
/**
* Fast cos function
*
* @param a
* the number
* @return the cos
*/
public static float cos(float a)
{
return sinLookup((int) ((a + 90f) * precision + 0.5f));
}
/**
* Fast tan function
*
* @param a
* the number
* @return the tan
*/
public static float tan(float a)
{
float c = cos(a);
return sin(a) / (c == 0 ? 0.0000001f : c);
}
/**
* Biggest number
*
* @param numbers
* the numbers
* @return the biggest one
*/
@SuppressWarnings("unchecked")
public static <T extends Number> T max(T... doubles)
{
double max = Double.MIN_VALUE;
for(T i : doubles)
{
if(i.doubleValue() > max)
{
max = i.doubleValue();
}
}
return (T) Double.valueOf(max);
}
/**
* Smallest number
*
* @param doubles
* the numbers
* @return the smallest one
*/
@SuppressWarnings("unchecked")
public static <T extends Number> T min(T... doubles)
{
double min = Double.MAX_VALUE;
for(T i : doubles)
{
if(i.doubleValue() < min)
{
min = i.doubleValue();
}
}
return (T) Double.valueOf(min);
}
/**
* Evaluates an expression using javascript engine and returns the double
* result. This can take variable parameters, so you need to define them.
* Parameters are defined as $[0-9]. For example evaluate("4$0/$1", 1, 2); This
* makes the expression (4x1)/2 == 2. Keep note that you must use 0-9, you
* cannot skip, or start at a number other than 0.
*
* @param expression
* the expression with variables
* @param args
* the arguments/variables
* @return the resulting double value
* @throws ScriptException
* ... gg
* @throws IndexOutOfBoundsException
* learn to count
*/
public static double evaluate(String expression, Double... args) throws ScriptException, IndexOutOfBoundsException
{
for(int i = 0; i < args.length; i++)
{
String current = "$" + i;
if(expression.contains(current))
{
expression = expression.replaceAll(Matcher.quoteReplacement(current), args[i] + "");
}
}
return evaluate(expression);
}
/**
* Evaluates an expression using javascript engine and returns the double
*
* @param expression
* the mathimatical expression
* @return the double result
* @throws ScriptException
* ... gg
*/
public static double evaluate(String expression) throws ScriptException
{
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine scriptEngine = mgr.getEngineByName("JavaScript");
return Double.valueOf(scriptEngine.eval(expression).toString());
}
/**
* is the number "is" within from-to
*
* @param from
* the lower end
* @param to
* the upper end
* @param is
* the check
* @return true if its within
*/
public static boolean within(int from, int to, int is)
{
return is >= from && is <= to;
}
/**
* Get the amount of days past since the epoch time (1970 jan 1 utc)
*
* @return the epoch days
*/
public static long epochDays()
{
return epochDays(M.ms());
}
/**
* Get the amount of days past since the epoch time (1970 jan 1 utc)
*
* @param ms
* the time in milliseconds
* @return the epoch days
*/
private static long epochDays(long ms)
{
return ms / 1000 / 60 / 60 / 24;
}
static
{
for(int i = 0; i < sin.length; i++)
{
sin[i] = (float) Math.sin((i * Math.PI) / (precision * 180));
}
}
private static float sinLookup(int a)
{
return a >= 0 ? sin[a % (modulus)] : -sin[-a % (modulus)];
}
}

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
/*
* JNBT License

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
/*
* JNBT License

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
/*
* JNBT License

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
/*
* JNBT License

View File

@@ -0,0 +1,6 @@
package com.volmit.iris.util;
public interface NastyFunction<T, R>
{
public R run(T t) throws Throwable;
}

View File

@@ -0,0 +1,6 @@
package com.volmit.iris.util;
public interface NastyFuture<R>
{
public R run() throws Throwable;
}

View File

@@ -0,0 +1,6 @@
package com.volmit.iris.util;
public interface NastyRunnable
{
public void run() throws Throwable;
}

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
/**
* Base class for all noise generators

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
@FunctionalInterface
public interface NoiseInjector

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
@FunctionalInterface
public interface NoiseProvider
{

View File

@@ -0,0 +1,53 @@
package com.volmit.iris.util;
public class O<T> implements Observable<T>
{
private T t = null;
private KList<Observer<T>> observers;
@Override
public T get()
{
return t;
}
@Override
public O<T> set(T t)
{
T x = t;
this.t = t;
if(observers != null && observers.hasElements())
{
observers.forEach((o) -> o.onChanged(x, t));
}
return this;
}
@Override
public boolean has()
{
return t != null;
}
@Override
public O<T> clearObservers()
{
observers.clear();
return this;
}
@Override
public O<T> observe(Observer<T> t)
{
if(observers == null)
{
observers = new KList<>();
}
observers.add(t);
return this;
}
}

View File

@@ -1,4 +1,4 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
public class ObjectConverter
{

View File

@@ -1,13 +1,11 @@
package ninja.bytecode.iris.util;
package com.volmit.iris.util;
import java.io.File;
import org.bukkit.util.BlockVector;
import ninja.bytecode.iris.Iris;
import ninja.bytecode.iris.object.IrisObject;
import ninja.bytecode.shuriken.collections.KMap;
import ninja.bytecode.shuriken.math.M;
import com.volmit.iris.Iris;
import com.volmit.iris.object.IrisObject;
public class ObjectResourceLoader extends ResourceLoader<IrisObject>
{

View File

@@ -0,0 +1,14 @@
package com.volmit.iris.util;
public interface Observable<T>
{
public T get();
public Observable<T> set(T t);
public boolean has();
public Observable<T> clearObservers();
public Observable<T> observe(Observer<T> t);
}

Some files were not shown because too many files have changed in this diff Show More