diff --git a/.gitignore b/.gitignore index 5c1cf006..8eb22fd9 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,11 @@ target/ *.project *.classpath *.prefs + +# IDE setting files +.vscode/ + +.settings/ +.factorypath + +dependency-reduced-pom.xml \ No newline at end of file diff --git a/build.xml b/build.xml deleted file mode 100644 index 66dc9d49..00000000 --- a/build.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/libs/Essentials.jar b/libs/Essentials.jar deleted file mode 100644 index 3b5813f3..00000000 Binary files a/libs/Essentials.jar and /dev/null differ diff --git a/libs/EssentialsGroupManager.jar b/libs/EssentialsGroupManager.jar deleted file mode 100644 index 181ebccb..00000000 Binary files a/libs/EssentialsGroupManager.jar and /dev/null differ diff --git a/libs/Factions.jar b/libs/Factions.jar deleted file mode 100644 index 6c5b798f..00000000 Binary files a/libs/Factions.jar and /dev/null differ diff --git a/libs/GriefPrevention.jar b/libs/GriefPrevention.jar deleted file mode 100644 index 5e0afb84..00000000 Binary files a/libs/GriefPrevention.jar and /dev/null differ diff --git a/libs/LWC.jar b/libs/LWC.jar deleted file mode 100644 index ba3b7f5c..00000000 Binary files a/libs/LWC.jar and /dev/null differ diff --git a/libs/MassiveCore.jar b/libs/MassiveCore.jar deleted file mode 100644 index e23d12b6..00000000 Binary files a/libs/MassiveCore.jar and /dev/null differ diff --git a/libs/MyWarp.jar b/libs/MyWarp.jar deleted file mode 100644 index 3126381b..00000000 Binary files a/libs/MyWarp.jar and /dev/null differ diff --git a/libs/PreciousStones.jar b/libs/PreciousStones.jar deleted file mode 100644 index b3cdd7e1..00000000 Binary files a/libs/PreciousStones.jar and /dev/null differ diff --git a/libs/Residence.jar b/libs/Residence.jar deleted file mode 100644 index a79c2675..00000000 Binary files a/libs/Residence.jar and /dev/null differ diff --git a/libs/Towny.jar b/libs/Towny.jar deleted file mode 100644 index c7b248f7..00000000 Binary files a/libs/Towny.jar and /dev/null differ diff --git a/libs/Vault.jar b/libs/Vault.jar deleted file mode 100644 index d4d4ecc7..00000000 Binary files a/libs/Vault.jar and /dev/null differ diff --git a/libs/WorldEdit.jar b/libs/WorldEdit.jar deleted file mode 100644 index 1bc1cd6b..00000000 Binary files a/libs/WorldEdit.jar and /dev/null differ diff --git a/libs/WorldGuard.jar b/libs/WorldGuard.jar deleted file mode 100644 index 1114fe6e..00000000 Binary files a/libs/WorldGuard.jar and /dev/null differ diff --git a/libs/downloads.txt b/libs/downloads.txt new file mode 100644 index 00000000..caed9448 --- /dev/null +++ b/libs/downloads.txt @@ -0,0 +1,16 @@ +Download jars from these links and put in libs directory. + +paperspigot +https://papermc.io/downloads +download paperclip and run server. +then, copy ./cache/patched_.jar into libs. +finally, rename patched_.jar to paperspigot.jar + +Factions & MassiveCore +https://www.spigotmc.org/resources/factions3-for-1-13.63602/ + +Residence +https://zrips.net/Residence/ + +MyWarp +https://dev.bukkit.org/projects/mywarp \ No newline at end of file diff --git a/libs/paperspigot.jar b/libs/paperspigot.jar deleted file mode 100644 index fdc3ac98..00000000 Binary files a/libs/paperspigot.jar and /dev/null differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..61da86c3 --- /dev/null +++ b/pom.xml @@ -0,0 +1,234 @@ + + 4.0.0 + autosaveworld + AutoSaveWorld + 4.15 + Multifunctional plugin to manage server easier + + + + jitpack.io + https://jitpack.io + + + enginehub-maven + https://maven.enginehub.org/repo/ + + + essentialsx-repo + https://ci.ender.zone/plugin/repository/everything/ + + + + elMakers-repo + http://maven.elmakers.com/repository/ + + + + + + + com.dropbox.core + dropbox-core-sdk + 3.1.5 + + + com.google.api-client + google-api-client + 1.30.11 + + + com.google.apis + google-api-services-drive + v3-rev197-1.25.0 + + + com.google.auth + google-auth-library-oauth2-http + 0.22.0 + + + com.jcraft + jsch + 0.1.55 + + + commons-net + commons-net + 3.7.2 + + + + + com.sk89q.worldedit + worldedit-bukkit + 7.2.0 + provided + + + com.sk89q.worldguard + worldguard-bukkit + 7.0.4 + provided + + + com.github.MilkBowl + VaultAPI + 1.7 + provided + + + net.ess3 + EssentialsX + 2.18.1 + provided + + + com.griefcraft.lwc + LWCX + 2.2.6 + provided + + + com.github.TechFortress + GriefPrevention + 16.7.1 + provided + + + com.github.GroupManager + GroupManager + v0.2.0 + provided + + + net.sacredlabyrinth.Phaed + PreciousStones + 1.16.1.12 + provided + + + com.github.TownyAdvanced + Towny + 0.96.3.0 + provided + + + + + com.destroystokyo.paper + paper + 1.16.4-R0.1-SNAPSHOT + system + ${basedir}/libs/paperspigot.jar + + + com.massivecraft.massivecore + MassiveCore + 3.2.3 + system + ${basedir}/libs/MassiveCore.jar + + + com.massivecraft.factions + Factions + 3.2.3 + system + ${basedir}/libs/Factions.jar + + + com.bekvon.bukkit.residence + Residence + 4.9.2.0 + system + ${basedir}/libs/Residence.jar + + + io.github.mywarp.mywarp + MyWarp + 3.1 + system + ${basedir}/libs/MyWarp.jar + + + + + + + . + true + src/main/resources/ + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.2.0 + + ${project.name} + + + true + true + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + ${java.version} + ${java.version} + UTF-8 + false + + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.3 + + + package + + shade + + + true + + + com.dropbox + autosaveworld.zlibs.com.dropbox + + + com.fasterxml + autosaveworld.zlibs.com.fasterxml + + + com.google + autosaveworld.zlibs.com.google + + + com.jcraft + autosaveworld.zlibs.com.jcraft + + + org.apache.commons.net + autosaveworld.zlibs.org.apache.commons.net + + + + + + + + + + UTF-8 + UTF-8 + 10 + + \ No newline at end of file diff --git a/src/autosaveworld/zlibs/com/dropbox/core/ApiErrorResponse.java b/src/autosaveworld/zlibs/com/dropbox/core/ApiErrorResponse.java deleted file mode 100644 index b39fd8f4..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/ApiErrorResponse.java +++ /dev/null @@ -1,75 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core; - -import java.io.IOException; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -final class ApiErrorResponse { - private final T error; - private LocalizedText userMessage; - - public ApiErrorResponse(T error, LocalizedText userMessage) { - if (error == null) { - throw new NullPointerException("error"); - } - this.error = error; - this.userMessage = userMessage; - } - - public T getError() { - return error; - } - - public LocalizedText getUserMessage() { - return userMessage; - } - - /** - * For internal use only. - */ - static final class Serializer extends StoneSerializer> { - private StoneSerializer errSerializer; - - public Serializer(StoneSerializer errSerializer) { - this.errSerializer = errSerializer; - } - - @Override - public void serialize(ApiErrorResponse value, JsonGenerator g) throws IOException, JsonGenerationException { - throw new UnsupportedOperationException("Error wrapper serialization not supported."); - } - - @Override - public ApiErrorResponse deserialize(JsonParser p) throws IOException, JsonParseException { - T error = null; - LocalizedText userMessage = null; - - expectStartObject(p); - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("error".equals(field)) { - error = errSerializer.deserialize(p); - } else if ("user_message".equals(field)) { - userMessage = LocalizedText.STONE_SERIALIZER.deserialize(p); - } else { - skipValue(p); - } - } - if (error == null) { - throw new JsonParseException(p, "Required field \"error\" missing."); - } - - ApiErrorResponse value = new ApiErrorResponse(error, userMessage); - expectEndObject(p); - - return value; - } - } -} - diff --git a/src/autosaveworld/zlibs/com/dropbox/core/BadRequestException.java b/src/autosaveworld/zlibs/com/dropbox/core/BadRequestException.java deleted file mode 100644 index dbdb9cc1..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/BadRequestException.java +++ /dev/null @@ -1,13 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core; - -/** - * This is what is thrown when the Dropbox server tells us that it didn't like something about our - * request. This corresponds to the HTTP 400 status code. - */ -public class BadRequestException extends ProtocolException { - private static final long serialVersionUID = 0; - - public BadRequestException(String requestId, String message) { - super(requestId, message); - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/BadResponseCodeException.java b/src/autosaveworld/zlibs/com/dropbox/core/BadResponseCodeException.java deleted file mode 100644 index 9cc7e0a5..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/BadResponseCodeException.java +++ /dev/null @@ -1,30 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core; - -/** - * Thrown when the Dropbox server responds with an HTTP status code we didn't expect. - */ -public class BadResponseCodeException extends BadResponseException { - private static final long serialVersionUID = 0L; - - private final int statusCode; - - public BadResponseCodeException(String requestId, String message, int statusCode) { - super(requestId, message); - this.statusCode = statusCode; - } - - public BadResponseCodeException(String requestId, String message, int statusCode, Throwable cause) { - super(requestId, message, cause); - this.statusCode = statusCode; - } - - /** - * Returns HTTP status code received from the Dropbox server. - * - * @return HTTP status code returned by Dropbox server - */ - public int getStatusCode() { - return statusCode; - } -} - diff --git a/src/autosaveworld/zlibs/com/dropbox/core/BadResponseException.java b/src/autosaveworld/zlibs/com/dropbox/core/BadResponseException.java deleted file mode 100644 index 855f8274..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/BadResponseException.java +++ /dev/null @@ -1,18 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core; - -/** - * Thrown when we the response from the Dropbox server isn't something we expect. - * For example, if the JSON returned by the server is malformed or missing fields. - */ -public class BadResponseException extends ProtocolException { - private static final long serialVersionUID = 0; - - public BadResponseException(String requestId, String message) { - super(requestId, message); - } - - public BadResponseException(String requestId, String message, Throwable cause) { - super(requestId, message, cause); - } -} - diff --git a/src/autosaveworld/zlibs/com/dropbox/core/DbxApiException.java b/src/autosaveworld/zlibs/com/dropbox/core/DbxApiException.java deleted file mode 100644 index c0504114..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/DbxApiException.java +++ /dev/null @@ -1,47 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core; - -/** - * Base class for API-specific exceptions raised by API v2 routes. - */ -public class DbxApiException extends DbxException { - private static final long serialVersionUID = 0L; - - private final LocalizedText userMessage; - - public DbxApiException(String requestId, LocalizedText userMessage, String message) { - super(requestId, message); - this.userMessage = userMessage; - } - - public DbxApiException(String requestId, LocalizedText userMessage, String message, Throwable cause) { - super(requestId, message, cause); - this.userMessage = userMessage; - } - - /** - * Returns a human-readable message that can be displayed to the end user. - * - *

If no such message is available, then this method returns {@code null}. - * - * @return human-readable message to display to end user, or {@code null} if unavailable - */ - public LocalizedText getUserMessage() { - return userMessage; - } - - protected static String buildMessage(String routeName, LocalizedText userMessage) { - return buildMessage(routeName, userMessage, null); - } - - protected static String buildMessage(String routeName, LocalizedText userMessage, Object errorValue) { - StringBuilder sb = new StringBuilder(); - sb.append("Exception in ").append(routeName); - if (errorValue != null) { - sb.append(": ").append(errorValue); - } - if (userMessage != null) { - sb.append(" (user message: ").append(userMessage).append(")"); - } - return sb.toString(); - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/DbxAppInfo.java b/src/autosaveworld/zlibs/com/dropbox/core/DbxAppInfo.java deleted file mode 100644 index 2fe8f53d..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/DbxAppInfo.java +++ /dev/null @@ -1,242 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core; - -import static autosaveworld.zlibs.com.dropbox.core.util.StringUtil.jq; - -import java.io.IOException; - -import autosaveworld.zlibs.com.dropbox.core.json.JsonReadException; -import autosaveworld.zlibs.com.dropbox.core.json.JsonReader; -import autosaveworld.zlibs.com.dropbox.core.util.DumpWriter; -import autosaveworld.zlibs.com.dropbox.core.util.Dumpable; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonLocation; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/*>>> import checkers.nullness.quals.Nullable; */ - -/** - * Identifying information about your application. - */ -public class DbxAppInfo extends Dumpable { - private final String key; - private final String secret; - private final DbxHost host; - - /** - * @param key Dropbox app key (see {@link #getKey}) - * @param secret Dropbox app secret (see {@link #getSecret}) - */ - public DbxAppInfo(String key, String secret) { - checkKeyArg(key); - checkSecretArg(secret); - - this.key = key; - this.secret = secret; - this.host = DbxHost.DEFAULT; - } - - /** - * @param key Dropbox app key (see {@link #getKey}) - * @param secret Dropbox app secret (see {@link #getSecret}) - * @param host Dropbox host configuration (see {@link #getHost}) - */ - public DbxAppInfo(String key, String secret, DbxHost host) { - checkKeyArg(key); - checkSecretArg(secret); - - this.key = key; - this.secret = secret; - this.host = host; - } - - /** - * Returns the Dropbox app key (OAuth calls this the consumer key). You can - * create an app key and secret on the Dropbox - * developer website. - * - * @return Dropbox app key - */ - public String getKey() { - return key; - } - - /** - * Returns the Dropbox app secret (OAuth calls this the consumer secret). You - * can create an app key and secret on the Dropbox - * developer website. - * - *

Make sure that this is kept a secret. Someone with your app secret can impesonate your - * application. People sometimes ask for help on the Dropbox API forums and copy/paste their - * code, which sometimes includes their app secret. Do not do that.

- * - * @return Dropbox app secret - */ - public String getSecret() { - return secret; - } - - /** - * Returns the Dropbox host configuration. - * - *

This is almost always {@link DbxHost#DEFAULT}. Typically this value will only be - * different for testing purposes. - * - * @return Dropbox host configuration - */ - public DbxHost getHost() { - return host; - } - - @Override - protected void dumpFields(DumpWriter out) { - out.f("key").v(key); - out.f("secret").v(secret); - } - - /** - * If they key's format looks correct, return {@code null}. Otherwise return - * a string that describes what the problem is. - * - *

- * NOTE: This function only performs some cursory checks on the format of the key. - * Even if it returns {@code null} (which means "no problem"), it doesn't mean - * that what you passed in is an actual valid Dropbox API app key. - *

- */ - public static /*@Nullable*/String getKeyFormatError(String key) { - return getTokenPartError(key); - } - - /** - * If they secret's format looks correct, return {@code null}. Otherwise return - * a string that describes what the problem is. - * - *

- * NOTE: This function only performs some cursory checks on the format. Even if it - * returns {@code null} (which means "no problem"), it doesn't mean that what - * you passed in is an actual valid Dropbox API app key. - *

- */ - public static /*@Nullable*/String getSecretFormatError(String key) { - return getTokenPartError(key); - } - - // ------------------------------------------------------ - // JSON parsing - - public static final JsonReader Reader = new JsonReader() - { - @Override - public final DbxAppInfo read(JsonParser parser) - throws IOException, JsonReadException - { - JsonLocation top = JsonReader.expectObjectStart(parser); - - String key = null; - String secret = null; - DbxHost host = null; - - while (parser.getCurrentToken() == JsonToken.FIELD_NAME) { - String fieldName = parser.getCurrentName(); - parser.nextToken(); - - try { - if (fieldName.equals("key")) { - key = KeyReader.readField(parser, fieldName, key); - } - else if (fieldName.equals("secret")) { - secret = SecretReader.readField(parser, fieldName, secret); - } - else if (fieldName.equals("host")) { - host = DbxHost.Reader.readField(parser, fieldName, host); - } - else { - // Unknown field. Skip over it. - JsonReader.skipValue(parser); - } - } - catch (JsonReadException ex) { - throw ex.addFieldContext(fieldName); - } - } - - JsonReader.expectObjectEnd(parser); - - if (key == null) throw new JsonReadException("missing field \"key\"", top); - if (secret == null) throw new JsonReadException("missing field \"secret\"", top); - if (host == null) host = DbxHost.DEFAULT; - - return new DbxAppInfo(key, secret, host); - } - }; - - public static final JsonReader KeyReader = new JsonReader() - { - @Override - public String read(JsonParser parser) throws IOException, JsonReadException - { - try { - String v = parser.getText(); - String error = getKeyFormatError(v); - if (error != null) { - throw new JsonReadException("bad format for app key: " + error, parser.getTokenLocation()); - } - parser.nextToken(); - return v; - } - catch (JsonParseException ex) { - throw JsonReadException.fromJackson(ex); - } - } - }; - - public static final JsonReader SecretReader = new JsonReader() - { - @Override - public String read(JsonParser parser) throws IOException, JsonReadException - { - try { - String v = parser.getText(); - String error = getKeyFormatError(v); - if (error != null) { - throw new JsonReadException("bad format for app secret: " + error, parser.getTokenLocation()); - } - parser.nextToken(); - return v; - } - catch (JsonParseException ex) { - throw JsonReadException.fromJackson(ex); - } - } - - }; - - public static /*@Nullable*/String getTokenPartError(String s) - { - if (s == null) return "can't be null"; - if (s.length() == 0) return "can't be empty"; - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - if (c < 0x21 || c > 0x7e) { - // Only allow normal visible ASCII characters. - return "invalid character at index " + i + ": " + jq("" + c); - } - } - return null; - } - - public static void checkKeyArg(String key) - { - String error = getTokenPartError(key); - if (error == null) return; - throw new IllegalArgumentException("Bad 'key': " + error); - } - - public static void checkSecretArg(String secret) - { - String error = getTokenPartError(secret); - if (error == null) return; - throw new IllegalArgumentException("Bad 'secret': " + error); - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/DbxException.java b/src/autosaveworld/zlibs/com/dropbox/core/DbxException.java deleted file mode 100644 index 3e736953..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/DbxException.java +++ /dev/null @@ -1,45 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core; - -/** - * The base exception thrown by Dropbox API calls. Normally, you'll need to do something specific - * for {@link InvalidAccessTokenException} and possibly for {@link RetryException}. The rest you - * should probably just log and investigate manually. - */ -public class DbxException extends Exception { - private static final long serialVersionUID = 0L; - - private final String requestId; - - public DbxException(String message) { - this(null, message); - } - - public DbxException(String requestId, String message) { - super(message); - this.requestId = requestId; - } - - public DbxException(String message, Throwable cause) { - this(null, message, cause); - } - - public DbxException(String requestId, String message, Throwable cause) { - super(message, cause); - this.requestId = requestId; - } - - /** - * Return the unique ID associated with the request that triggered this exception. - * - *

The ID may be {@code null} if we could not receive a response from the Dropbox servers - * (e.g. from a {@link NetworkIOException}). - * - *

Please use this ID when filing bug reports. - * - * @return unique ID associated with the request that caused this exception, or {@code null} if - * one is not available. - */ - public String getRequestId() { - return requestId; - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/DbxHost.java b/src/autosaveworld/zlibs/com/dropbox/core/DbxHost.java deleted file mode 100644 index 600a75de..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/DbxHost.java +++ /dev/null @@ -1,200 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.json.JsonReadException; -import autosaveworld.zlibs.com.dropbox.core.json.JsonReader; -import autosaveworld.zlibs.com.dropbox.core.json.JsonWriter; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonLocation; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/*>>> import checkers.nullness.quals.Nullable; */ - -/** - * This is for mocking things out during testing. Most of the time you won't have to deal with - * this class; just use the default value: {@link DbxHost#DEFAULT}. - */ -public final class DbxHost { - /** - * The standard Dropbox hosts: "api.dropbox.com", "api-content.dropbox.com", - * and "www.dropbox.com" - */ - public static final DbxHost DEFAULT = new DbxHost( - "api.dropboxapi.com", - "content.dropboxapi.com", - "www.dropbox.com", - "notify.dropboxapi.com" - ); - - private final String api; - private final String content; - private final String web; - private final String notify; - - /** - * @param api main Dropbox API server host name - * @param content Dropbox API content server host name - * @param web Dropbox web server host name - * @param notify Dropbox notification server host name - */ - public DbxHost(String api, String content, String web, String notify) { - this.api = api; - this.content = content; - this.web = web; - this.notify = notify; - } - - /** - * Returns the host name of the main Dropbox API server. - * The default is {@code "api.dropbox.com"}. - * - * @return host name of main Dropbox API server - */ - public String getApi() { - return api; - } - - /** - * Returns the host name of the Dropbox API content server. - * The default is {@code "api-content.dropbox.com"}. - * - * @return host name of Dropbox API content server - */ - public String getContent() { - return content; - } - - /** - * Returns the host name of the Dropbox web server. Used during user authorization. - * The default is {@code "www.dropbox.com"}. - * - * @return host name of Dropbox API web server used during user authorization - */ - public String getWeb() { - return web; - } - - /** - * Returns the host name of the Dropbox notification server. Used by longpoll endpoints. - * The default is {@code "api-notify.dropbox.com"}. - * - * @return host name of Dropbox notification server used for longpolling - */ - public String getNotify() { - return notify; - } - - @Override - public int hashCode() { - return Arrays.hashCode(new String [] {api, content, web, notify}); - } - - @Override - public boolean equals(/*@Nullable*/Object obj) { - if (obj == this) { - return true; - } else if(obj instanceof DbxHost) { - DbxHost other = (DbxHost) obj; - return other.api.equals(this.api) - && other.content.equals(this.content) - && other.web.equals(this.web) - && other.notify.equals(this.notify); - } else { - return false; - } - } - - private static DbxHost fromBaseHost(String s) { - return new DbxHost("api-" + s, "api-content-" + s, "meta-" + s, "api-notify-" + s); - } - - public static final JsonReader Reader = new JsonReader() { - @Override - public DbxHost read(JsonParser parser) throws IOException, JsonReadException { - JsonToken t = parser.getCurrentToken(); - if (t == JsonToken.VALUE_STRING) { - String s = parser.getText(); - JsonReader.nextToken(parser); - return DbxHost.fromBaseHost(s); - } else if (t == JsonToken.START_OBJECT) { - JsonLocation top = parser.getTokenLocation(); - nextToken(parser); - - String api = null; - String content = null; - String web = null; - String notify = null; - - while (parser.getCurrentToken() == JsonToken.FIELD_NAME) { - String fieldName = parser.getCurrentName(); - parser.nextToken(); - - try { - if (fieldName.equals("api")) { - api = JsonReader.StringReader.readField(parser, fieldName, api); - } - else if (fieldName.equals("content")) { - content = JsonReader.StringReader.readField(parser, fieldName, content); - } - else if (fieldName.equals("web")) { - web = JsonReader.StringReader.readField(parser, fieldName, web); - } - else if (fieldName.equals("notify")) { - notify = JsonReader.StringReader.readField(parser, fieldName, notify); - } - else { - throw new JsonReadException("unknown field", parser.getCurrentLocation()); - } - } - catch (JsonReadException ex) { - throw ex.addFieldContext(fieldName); - } - } - - JsonReader.expectObjectEnd(parser); - - if (api == null) throw new JsonReadException("missing field \"api\"", top); - if (content == null) throw new JsonReadException("missing field \"content\"", top); - if (web == null) throw new JsonReadException("missing field \"web\"", top); - if (notify == null) throw new JsonReadException("missing field \"notify\"", top); - - return new DbxHost(api, content, web, notify); - } else { - throw new JsonReadException("expecting a string or an object", parser.getTokenLocation()); - } - } - }; - - private /*@Nullable*/String inferBaseHost() { - if (web.startsWith("meta-") && api.startsWith("api-") && content.startsWith("api-content-") && notify.startsWith("api-notify-")) { - String webBase = web.substring("meta-".length()); - String apiBase = api.substring("api-".length()); - String contentBase = content.substring("api-content-".length()); - String notifyBase = notify.substring("api-notify-".length()); - if (webBase.equals(apiBase) && webBase.equals(contentBase) && webBase.equals(notifyBase)) { - return webBase; - } - } - return null; - } - - public static final JsonWriter Writer = new JsonWriter() { - @Override - public void write(DbxHost host, JsonGenerator g) throws IOException { - String base = host.inferBaseHost(); - if (base != null) { - g.writeString(base); - } else { - g.writeStartObject(); - g.writeStringField("api", host.api); - g.writeStringField("content", host.content); - g.writeStringField("web", host.web); - g.writeStringField("notify", host.notify); - g.writeEndObject(); - } - } - }; -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/DbxRequestConfig.java b/src/autosaveworld/zlibs/com/dropbox/core/DbxRequestConfig.java deleted file mode 100644 index b51f3f91..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/DbxRequestConfig.java +++ /dev/null @@ -1,396 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core; - -import java.util.Locale; - -import autosaveworld.zlibs.com.dropbox.core.http.HttpRequestor; -import autosaveworld.zlibs.com.dropbox.core.http.StandardHttpRequestor; - -/*>>> import checkers.nullness.quals.Nullable; */ - -/** - * A grouping of a few configuration parameters for how we should make requests to the - * Dropbox servers. - */ -public class DbxRequestConfig { - private final String clientIdentifier; - private final /*@Nullable*/String userLocale; - private final HttpRequestor httpRequestor; - private final int maxRetries; - - private DbxRequestConfig(String clientIdentifier, /*@Nullable*/ String userLocale, HttpRequestor httpRequestor, int maxRetries) { - if (clientIdentifier == null) throw new NullPointerException("clientIdentifier"); - if (httpRequestor == null) throw new NullPointerException("httpRequestor"); - if (maxRetries < 0) throw new IllegalArgumentException("maxRetries"); - - this.clientIdentifier = clientIdentifier; - this.userLocale = toLanguageTag(userLocale); - this.httpRequestor = httpRequestor; - this.maxRetries = maxRetries; - } - - /** - * Creates a new configuration. - * - * @param clientIdentifier client identifier typically in the form "Name/Version" to be used in - * the User-Agent header (see {@link #getClientIdentifier}). - */ - public DbxRequestConfig(String clientIdentifier) { - this(clientIdentifier, null); - } - - /** - * Creates a new configuration. - * - * @param clientIdentifier client identifier typically in the form "Name/Version" to be used in - * the User-Agent header (see {@link #getClientIdentifier}). - * @param userLocale IETF BCP 47 language tag of locale to use for user-visible text in responses, or - * {@code null} to use the user's Dropbox locale preference. - * - * @deprecated Use {@link #newBuilder} to customize configuration - */ - @Deprecated - public DbxRequestConfig(String clientIdentifier, /*@Nullable*/ String userLocale) { - this(clientIdentifier, userLocale, StandardHttpRequestor.INSTANCE); - } - - /** - * Creates a new configuration. - * - * @param clientIdentifier client identifier typically in the form "Name/Version" to be used in - * the User-Agent header (see {@link #getClientIdentifier}). - * @param userLocale IETF BCP 47 language tag of locale to use for user-visible text in responses, or - * {@code null} to use the user's Dropbox locale preference. - * @param httpRequestor HTTP client to use for issuing requests. - * - * @deprecated Use {@link #newBuilder} to customize configuration - */ - @Deprecated - public DbxRequestConfig(String clientIdentifier, /*@Nullable*/ String userLocale, HttpRequestor httpRequestor) { - this(clientIdentifier, userLocale, httpRequestor, 0); - } - - /** - * Returns an identifier for the API client, typically of the form "Name/Version". - * This is used to set the HTTP {@code User-Agent} header when making API requests. - * Example: {@code "PhotoEditServer/1.3"} - * - *

- * If you're the author a higher-level library on top of the basic SDK, and the - * "Photo Edit" Android app is using your library to access Dropbox, you should append - * your library's name and version to form the full identifier. For example, - * if your library is called "File Picker", you might set this field to: - * {@code "PhotoEditAndroid/2.4 FilePicker/0.1-beta"} - *

- * - *

- * The exact format of the {@code User-Agent} header is described in - * section 3.8 of the HTTP specification. - *

- * - *

- * Note that the underlying {@link autosaveworld.zlibs.com.dropbox.core.http.HttpRequestor HttpRequestor} may - * append other things to the {@code User-Agent}, such as the name of the library being used to - * actually make the HTTP request, or the version of the Java VM. - *

- * - * @return HTTP User-Agent identifier for the API client - */ - public String getClientIdentifier() { - return clientIdentifier; - } - - /** - * Returns the locale of the user of your app as an IETF BCP 47 language tag. This is used by - * the Dropbox server to localize user-visible strings returned by API calls. - * - *

If the value is {@code null} or some locale that Dropbox doesn't support, the strings - * will be localized based on the user's Dropbox locale preference. - * - *

Defaults to {@code null}. - * - * @return locale of app user, or {@code null} to use user's Dropbox locale settings. - */ - public String getUserLocale() { - return userLocale; - } - - /** - * The {@link HttpRequestor} implementation to use when making HTTP requests to the Dropbox API - * servers. - * - *

Defaults to {@link StandardHttpRequestor#INSTANCE}. - * - * @return HTTP requestor to use for issuing HTTP requests. - */ - public HttpRequestor getHttpRequestor() { - return httpRequestor; - } - - /** - * Returns whether or not the client should automatically retry RPC and download requests after - * recieving a {@link RetryException}. - * - *

If enabled, the client will retry the request a max number of times (specified by {@link - * #getMaxRetries}) before propagating the {@link RetryException}.

- * - *

Defaults to {@code false} (the client will not automatically retry any requests). - * - * @return whether this client will automatically retry requests that fail with a {@link - * RetryException} - */ - public boolean isAutoRetryEnabled() { - return maxRetries > 0; - } - - /** - * Returns the maximum number of times the client should automatically retry RPC and download - * requests that fail with a {@link RetryException}. - * - *

This value does not count the initial request attempt. For example, if maximum retries is - * 3, the client may issue a request a total of 4 times: once for the initial call, then 3 - * additional times for the 3 retries.

- * - *

This value is ignored unless {@link #isAutoRetryEnabled} is {@code true}. - * - *

The value returned by this method is always positive if retries are enabled, otherwise it - * is {@code 0}. - * - *

Defaults to {@code 3} when retries are enabled. - * - * @return maximum number of times the client will retry a request that throws a {@link - * RetryException}. - */ - public int getMaxRetries() { - return maxRetries; - } - - /** - * Returns a builder for building a copy of this configuration. Useful for modifying an existing - * configuration. - * - * @return builder configured to build a copy of this instance - */ - public Builder copy() { - return new Builder(clientIdentifier, userLocale, httpRequestor, maxRetries); - } - - - /** - * Returns a new builder for creating a {@link DbxRequestConfig} instance. - * - * Identifiers are typically of the form "Name/Version" (e.g. {@code - * "PhotoEditServer/1.3"}). See {@link #getClientIdentifier} for more details. - * - * @param clientIdentifier HTTP User-Agent identifier for the API app (see {@link - * #getClientIdentifier}), never {@code null} - */ - public static Builder newBuilder(String clientIdentifier) { - if (clientIdentifier == null) throw new NullPointerException("clientIdentifier"); - return new Builder(clientIdentifier); - } - - // Available in Java 7, but not in Java 6. Do a hacky version of it here. - private static String toLanguageTag(Locale locale) { - if (locale == null) { - return null; - } - StringBuilder tag = new StringBuilder(); - - tag.append(locale.getLanguage().toLowerCase()); - - if (!locale.getCountry().isEmpty()) { - tag.append("-"); - tag.append(locale.getCountry().toUpperCase()); - } - - return tag.toString(); - } - - // APIv1 accepts Locale.toString() formatted locales (e.g. 'en_US'), but APIv2 will return an - // error if the locale is not in proper Language Tag format. Attempt to convert old locale - // formats to the new one. - private static String toLanguageTag(String locale) { - if (locale == null) { - return null; - } - // assume we are already a language tag - if (!locale.contains("_")) { - return locale; - } - - // language can be missing, in which case we don't even bother - if (locale.startsWith("_")) { - return locale; - } - - // Java 6 does "lang_country_variant". If country is missing, then "lang__variant". If no - // variant, then just "lang_country". - String [] parts = locale.split("_", 3); - - String lang = parts[0]; - String country = parts[1]; - String variant = parts.length == 3 ? parts[2] : ""; - - return toLanguageTag(new Locale(lang, country, variant)); - } - - /** - * Builder for {@link DbxRequestConfig}. - */ - public static final class Builder { - private final String clientIdentifier; - - private /*@Nullable*/ String userLocale; - private HttpRequestor httpRequestor; - private int maxRetries; - - private Builder(String clientIdentifier, - /*@Nullable*/ String userLocale, - HttpRequestor httpRequestor, - int maxRetries) { - this.clientIdentifier = clientIdentifier; - this.userLocale = userLocale; - this.httpRequestor = httpRequestor; - this.maxRetries = maxRetries; - } - - private Builder(String clientIdentifier) { - this.clientIdentifier = clientIdentifier; - - this.userLocale = null; - this.httpRequestor = StandardHttpRequestor.INSTANCE; - this.maxRetries = 0; - } - - /** - * Set the locale of the app user. User-visible messages returned by the Dropbox servers - * will be localized to this locale. - * - *

Defaults to {@code null}, which means strings will be localized according to the - * user's Dropbox locale preference. - * - * @param userLocale locale of app user as an IETF BCP 47 language tag, or {@code null} to - * use the user's Dropbox locale settings. - * - * @return this builder - */ - public Builder withUserLocale(/*@Nullable*/ String userLocale) { - this.userLocale = userLocale; - return this; - } - - /** - * Set the locale of user-visible messages returned by the Dropbox servers to the user's - * Dropbox locale. - * - *

User-visible strings will be localized according to the user's Dropbox locale - * preference. - * - * @return this builder - */ - public Builder withUserLocaleFromPreferences() { - this.userLocale = null; - return this; - } - - /** - * Set the locale of the app user. User-visible messages returned by the Dropbox servers - * will be localized to this locale. - * - *

Defaults to {@code null}, which means strings will be localized according to the - * user's Dropbox locale preference. - * - * @param userLocale Locale of app user, or {@code null} to use user's Dropbox locale settings. - * - * @return this builder - */ - public Builder withUserLocaleFrom(/*@Nullable*/ Locale userLocale) { // not named withUserLocale because of ambiguous calls when passing 'null' - this.userLocale = toLanguageTag(userLocale); - return this; - } - - /** - * Set the HTTP requestor to use for issuing network requests to the Dropbox servers. - * - *

Defaults to {@link StandardHttpRequestor#INSTANCE}. - * - * @param httpRequestor HTTP requestor to use for network requests, never {@code null} - * - * @return this builder - */ - public Builder withHttpRequestor(HttpRequestor httpRequestor) { - if (httpRequestor == null) throw new NullPointerException("httpRequestor"); - this.httpRequestor = httpRequestor; - return this; - } - - /** - * Enables automatic retry of RPC and download requests that fail with a {@link - * RetryException}. - * - *

The default number of {@code 3} retries will be used in addition to the initial - * request. To specify the maximum number of retries, see {@link - * #withAutoRetryEnabled(int)}. - * - *

By default, the client will not automatically retry any requests. - * - * @return this builder - */ - public Builder withAutoRetryEnabled() { - return withAutoRetryEnabled(3); - } - - /** - * Disables automatic retry of RPC and download requests that fail with a {@link - * RetryException}. - * - *

By default, the client will not automatically retry any requests. - * - * @return this builder - * - * @see #withAutoRetryEnabled - */ - public Builder withAutoRetryDisabled() { - this.maxRetries = 0; - return this; - } - - /** - * Enables automatic retry of RPC and download requests that fail with a {@link - * RetryException}. - * - *

The client will retry failed requests a maximum of {@code maxRetries} times before - * propogating the exception. Note that {@code maxRetries} does not count the initial - * request attempt. For example, if {@code maxRetries} is 3, the client may issue a request - * a total of 4 times: once for the initial call, then 3 additional times for the 3 - * retries.

- * - *

By default, the client will not automatically retry any requests. - * - *

To enable automatic retries with the default maximum number of attempts, use {@link - * #withAutoRetryEnabled()}. - * - * @param maxRetries maximum number of times to retry a retriable failed request. Must be - * positive. - * - * @return this builder - * - * @throws IllegalArgumentException if {@code maxRetries} is not positive. - */ - public Builder withAutoRetryEnabled(int maxRetries) { - if (maxRetries <= 0) throw new IllegalArgumentException("maxRetries must be positive"); - this.maxRetries = maxRetries; - return this; - } - - /** - * Builds an instance of {@link DbxRequestConfig} with this builder's configured parameters - * or defaults. - * - * @return new {@code DbxRequestConfig} instance. - */ - public DbxRequestConfig build() { - return new DbxRequestConfig(clientIdentifier, userLocale, httpRequestor, maxRetries); - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/DbxRequestUtil.java b/src/autosaveworld/zlibs/com/dropbox/core/DbxRequestUtil.java deleted file mode 100644 index fa0dbfb5..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/DbxRequestUtil.java +++ /dev/null @@ -1,459 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core; - -import static autosaveworld.zlibs.com.dropbox.core.util.LangUtil.mkAssert; -import static autosaveworld.zlibs.com.dropbox.core.util.StringUtil.jq; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URLEncoder; -import java.nio.charset.CharacterCodingException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.concurrent.TimeUnit; - -import autosaveworld.zlibs.com.dropbox.core.http.HttpRequestor; -import autosaveworld.zlibs.com.dropbox.core.json.JsonReadException; -import autosaveworld.zlibs.com.dropbox.core.json.JsonReader; -import autosaveworld.zlibs.com.dropbox.core.util.IOUtil; -import autosaveworld.zlibs.com.dropbox.core.util.StringUtil; - -/*>>> import checkers.nullness.quals.Nullable; */ - -public final class DbxRequestUtil { - private static final Random RAND = new Random(); - - public static String encodeUrlParam(String s) { - try { - return URLEncoder.encode(s, "UTF-8"); - } catch (UnsupportedEncodingException ex) { - throw mkAssert("UTF-8 should always be supported", ex); - } - } - - public static String buildUrlWithParams(/*@Nullable*/String userLocale, - String host, - String path, - /*@Nullable*/String/*@Nullable*/[] params) { - return buildUri(host, path) + "?" + encodeUrlParams(userLocale, params); - } - - static String [] toParamsArray(Map params) { - String [] arr = new String[2 * params.size()]; - int i = 0; - for (Map.Entry entry : params.entrySet()) { - arr[i] = entry.getKey(); - arr[i + 1] = entry.getValue(); - i += 2; - } - return arr; - } - - public static String buildUri(String host, String path) { - try { - return new URI("https", host, "/" + path, null).toASCIIString(); - } - catch (URISyntaxException ex) { - throw mkAssert("URI creation failed, host=" + jq(host) + ", path=" + jq(path), ex); - } - } - - private static String encodeUrlParams(/*@Nullable*/String userLocale, - /*@Nullable*/String/*@Nullable*/[] params) { - StringBuilder buf = new StringBuilder(); - String sep = ""; - if (userLocale != null) { - buf.append("locale=").append(userLocale); - sep = "&"; - } - - if (params != null) { - if (params.length % 2 != 0) { - throw new IllegalArgumentException("'params.length' is " + params.length + "; expecting a multiple of two"); - } - for (int i = 0; i < params.length; ) { - String key = params[i]; - String value = params[i+1]; - if (key == null) throw new IllegalArgumentException("params[" + i + "] is null"); - if (value != null) { - buf.append(sep); sep = "&"; - buf.append(encodeUrlParam(key)); - buf.append("="); - buf.append(encodeUrlParam(value)); - } - i += 2; - } - } - - return buf.toString(); - } - - public static List addAuthHeader(/*@Nullable*/List headers, String accessToken) { - if (accessToken == null) throw new NullPointerException("accessToken"); - if (headers == null) headers = new ArrayList(); - - headers.add(new HttpRequestor.Header("Authorization", "Bearer " + accessToken)); - return headers; - } - - public static List addSelectUserHeader(/*@Nullable*/List headers, String memberId) { - if (memberId == null) throw new NullPointerException("memberId"); - if (headers == null) headers = new ArrayList(); - - headers.add(new HttpRequestor.Header("Dropbox-API-Select-User", memberId)); - return headers; - } - - public static List addBasicAuthHeader(/*@Nullable*/List headers, String username, String password) { - if (username == null) throw new NullPointerException("username"); - if (password == null) throw new NullPointerException("password"); - if (headers == null) headers = new ArrayList(); - - String credentials = username + ":" + password; - String base64Credentials = StringUtil.base64Encode(StringUtil.stringToUtf8(credentials)); - headers.add(new HttpRequestor.Header("Authorization", "Basic " + base64Credentials)); - return headers; - } - - public static List addUserAgentHeader( - /*@Nullable*/List headers, - DbxRequestConfig requestConfig, - String sdkUserAgentIdentifier - ) { - if (headers == null) headers = new ArrayList(); - headers.add(buildUserAgentHeader(requestConfig, sdkUserAgentIdentifier)); - return headers; - } - - public static List addUserLocaleHeader(/*@Nullable*/List headers, DbxRequestConfig requestConfig) { - if (requestConfig.getUserLocale() == null) { - return headers; - } - - if (headers == null) headers = new ArrayList(); - headers.add(new HttpRequestor.Header("Dropbox-API-User-Locale", requestConfig.getUserLocale())); - return headers; - } - - public static HttpRequestor.Header buildUserAgentHeader(DbxRequestConfig requestConfig, String sdkUserAgentIdentifier) { - return new HttpRequestor.Header("User-Agent", requestConfig.getClientIdentifier() + " " + sdkUserAgentIdentifier + "/" + "ASW 1.0 (JSDK 2.1.2)"); - } - - /** - * Convenience function for making HTTP GET requests. - */ - public static HttpRequestor.Response startGet(DbxRequestConfig requestConfig, - String accessToken, - String sdkUserAgentIdentifier, - String host, - String path, - /*@Nullable*/String/*@Nullable*/[] params, - /*@Nullable*/List headers) - throws NetworkIOException { - headers = copyHeaders(headers); - headers = addUserAgentHeader(headers, requestConfig, sdkUserAgentIdentifier); - headers = addAuthHeader(headers, accessToken); - - String url = buildUrlWithParams(requestConfig.getUserLocale(), host, path, params); - try { - return requestConfig.getHttpRequestor().doGet(url, headers); - } - catch (IOException ex) { - throw new NetworkIOException(ex); - } - } - - /** - * Convenience function for making HTTP PUT requests. - */ - public static HttpRequestor.Uploader startPut(DbxRequestConfig requestConfig, - String accessToken, - String sdkUserAgentIdentifier, - String host, String path, - /*@Nullable*/String/*@Nullable*/[] params, - /*@Nullable*/List headers) - throws NetworkIOException { - headers = copyHeaders(headers); - headers = addUserAgentHeader(headers, requestConfig, sdkUserAgentIdentifier); - headers = addAuthHeader(headers, accessToken); - - String url = buildUrlWithParams(requestConfig.getUserLocale(), host, path, params); - try { - return requestConfig.getHttpRequestor().startPut(url, headers); - } - catch (IOException ex) { - throw new NetworkIOException(ex); - } - } - - /** - * Convenience function for making HTTP POST requests. - */ - public static HttpRequestor.Response startPostNoAuth(DbxRequestConfig requestConfig, - String sdkUserAgentIdentifier, - String host, - String path, - /*@Nullable*/String/*@Nullable*/[] params, - /*@Nullable*/List headers) - throws NetworkIOException { - byte[] encodedParams = StringUtil.stringToUtf8(encodeUrlParams(requestConfig.getUserLocale(), params)); - - headers = copyHeaders(headers); - headers.add(new HttpRequestor.Header("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")); - - return startPostRaw(requestConfig, sdkUserAgentIdentifier, host, path, encodedParams, headers); - } - - - /** - * Convenience function for making HTTP POST requests. Like startPostNoAuth but takes byte[] instead of params. - */ - public static HttpRequestor.Response startPostRaw(DbxRequestConfig requestConfig, - String sdkUserAgentIdentifier, - String host, - String path, - byte[] body, - /*@Nullable*/List headers) - throws NetworkIOException { - String uri = buildUri(host, path); - - headers = copyHeaders(headers); - headers = addUserAgentHeader(headers, requestConfig, sdkUserAgentIdentifier); - headers.add(new HttpRequestor.Header("Content-Length", Integer.toString(body.length))); - - try { - HttpRequestor.Uploader uploader = requestConfig.getHttpRequestor().startPost(uri, headers); - try { - uploader.upload(body); - return uploader.finish(); - } finally { - uploader.close(); - } - } catch (IOException ex) { - throw new NetworkIOException(ex); - } - } - - private static List copyHeaders(List headers) { - if (headers == null) { - return new ArrayList(); - } else { - return new ArrayList(headers); - } - } - - public static byte[] loadErrorBody(HttpRequestor.Response response) - throws NetworkIOException { - if (response.getBody() == null) { - return new byte[0]; - } - - // Slurp the body into memory (up to 4k; anything past that is probably not useful). - try { - return IOUtil.slurp(response.getBody(), 4096); - } catch (IOException ex) { - throw new NetworkIOException(ex); - } - - } - - public static String parseErrorBody(String requestId, int statusCode, byte[] body) - throws BadResponseException { - // Read the error message from the body. - // TODO: Get charset from the HTTP Content-Type header. It's wrong to just assume UTF-8. - // TODO: Maybe try parsing the message as JSON and do something more structured? - try { - return StringUtil.utf8ToString(body); - } catch (CharacterCodingException e) { - throw new BadResponseException(requestId, "Got non-UTF8 response body: " + statusCode + ": " + e.getMessage()); - } - } - - public static DbxException unexpectedStatus(HttpRequestor.Response response) - throws NetworkIOException, BadResponseException { - String requestId = getRequestId(response); - byte[] body = loadErrorBody(response); - String message = parseErrorBody(requestId, response.getStatusCode(), body); - - switch (response.getStatusCode()) { - case 400: - return new BadRequestException(requestId, message); - case 401: - return new InvalidAccessTokenException(requestId, message); - case 429: - try { - int backoffSecs = Integer.parseInt(getFirstHeader(response, "Retry-After")); - return new RateLimitException(requestId, message, backoffSecs, TimeUnit.SECONDS); - } catch (NumberFormatException ex) { - return new BadResponseException(requestId, "Invalid value for HTTP header: \"Retry-After\""); - } - case 500: - return new ServerException(requestId, message); - case 503: - // API v1 may include Retry-After in 503 responses, v2 does not - String retryAfter = getFirstHeaderMaybe(response, "Retry-After"); - try { - if (retryAfter != null && !retryAfter.trim().isEmpty()) { - int backoffSecs = Integer.parseInt(retryAfter); - return new RetryException(requestId, message, backoffSecs, TimeUnit.SECONDS); - } else { - return new RetryException(requestId, message); - } - } catch (NumberFormatException ex) { - return new BadResponseException(requestId, "Invalid value for HTTP header: \"Retry-After\""); - } - default: - return new BadResponseCodeException( - requestId, - "unexpected HTTP status code: " + response.getStatusCode() + ": " + message, - response.getStatusCode() - ); - } - } - - public static T readJsonFromResponse(JsonReader reader, HttpRequestor.Response response) - throws BadResponseException, NetworkIOException { - try { - return reader.readFully(response.getBody()); - } catch (JsonReadException ex) { - String requestId = getRequestId(response); - throw new BadResponseException(requestId, "error in response JSON: " + ex.getMessage(), ex); - } catch (IOException ex) { - throw new NetworkIOException(ex); - } - } - - public static abstract class ResponseHandler { - public abstract T handle(HttpRequestor.Response response) throws DbxException; - } - - public static T doGet(final DbxRequestConfig requestConfig, - final String accessToken, - final String sdkUserAgentIdentifier, - final String host, - final String path, - final /*@Nullable*/String/*@Nullable*/[] params, - final /*@Nullable*/List headers, - final ResponseHandler handler) - throws DbxException { - return runAndRetry(requestConfig.getMaxRetries(), new RequestMaker() { - @Override - public T run() throws DbxException { - HttpRequestor.Response response = startGet(requestConfig, accessToken, sdkUserAgentIdentifier, host, path, params, headers); - try { - return handler.handle(response); - } finally { - try { - response.getBody().close(); - } catch (IOException ex) { - //noinspection ThrowFromFinallyBlock - throw new NetworkIOException(ex); - } - } - } - }); - } - - public static T doPost(DbxRequestConfig requestConfig, - String accessToken, - String sdkUserAgentIdentifier, - String host, - String path, - /*@Nullable*/String/*@Nullable*/[] params, - /*@Nullable*/List headers, - ResponseHandler handler) - throws DbxException { - headers = copyHeaders(headers); - headers = addAuthHeader(headers, accessToken); - return doPostNoAuth(requestConfig, sdkUserAgentIdentifier, host, path, params, headers, handler); - } - - public static T doPostNoAuth(final DbxRequestConfig requestConfig, - final String sdkUserAgentIdentifier, - final String host, - final String path, - final /*@Nullable*/String/*@Nullable*/[] params, - final /*@Nullable*/List headers, - final ResponseHandler handler) - throws DbxException { - return runAndRetry(requestConfig.getMaxRetries(), new RequestMaker() { - @Override - public T run() throws DbxException { - HttpRequestor.Response response = startPostNoAuth(requestConfig, sdkUserAgentIdentifier, host, path, params, headers); - return finishResponse(response, handler); - } - }); - } - - public static T finishResponse(HttpRequestor.Response response, ResponseHandler handler) throws DbxException { - try { - return handler.handle(response); - } finally { - IOUtil.closeInput(response.getBody()); - } - } - - public static String getFirstHeader(HttpRequestor.Response response, String name) throws BadResponseException { - List values = response.getHeaders().get(name); - if (values == null || values.isEmpty()) { - throw new BadResponseException(getRequestId(response), "missing HTTP header \"" + name + "\""); - } - return values.get(0); - } - - public static /*@Nullable*/String getFirstHeaderMaybe(HttpRequestor.Response response, String name) { - List values = response.getHeaders().get(name); - if (values == null || values.isEmpty()) { - return null; - } - return values.get(0); - } - - public static /*@Nullable*/ String getRequestId(HttpRequestor.Response response) { - return DbxRequestUtil.getFirstHeaderMaybe(response, "X-Dropbox-Request-Id"); - } - - public static abstract class RequestMaker { - public abstract T run() throws DbxException, E; - } - - public static T runAndRetry(int maxRetries, RequestMaker requestMaker) - throws DbxException, E { - int numRetries = 0; - while (true) { - long backoff; - DbxException thrown = null; - try { - return requestMaker.run(); - } catch (RetryException ex) { - backoff = ex.getBackoffMillis(); - thrown = ex; - } catch (ServerException ex) { - backoff = 0L; - thrown = ex; - } - - if (numRetries >= maxRetries) { - throw thrown; - } - - // add a random jitter to the backoff to avoid stampeding herd. This is especially - // useful for ServerExceptions, where backoff is 0. - backoff += RAND.nextInt(1000); - - if (backoff > 0L) { - try { - Thread.sleep(backoff); - } catch (InterruptedException ex) { - // preserve interrupt - Thread.currentThread().interrupt(); - } - } - - ++numRetries; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/DbxUploader.java b/src/autosaveworld/zlibs/com/dropbox/core/DbxUploader.java deleted file mode 100644 index 53593386..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/DbxUploader.java +++ /dev/null @@ -1,247 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core; - -import java.io.Closeable; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import autosaveworld.zlibs.com.dropbox.core.http.HttpRequestor; -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializer; -import autosaveworld.zlibs.com.dropbox.core.util.IOUtil; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonProcessingException; - -/** - * Class for completing upload requests. - * - * This class provides methods for uploading a request body and handling the server response. - * - * Example usage: - * - *


- *    FileInputStream in = new FileInputStream("test.txt");
- *    try {
- *        response = uploader.uploadAndFinish(in);
- *    } finally {
- *        in.close();
- *    }
- *
- * - * Example using {@link #getOutputStream}: - * - *

- *    try {
- *        OutputStream out = uploader.getOutputStream();
- *        out.write(data);
- *        response = uploader.finish();
- *    } finally {
- *        uploader.close();
- *    }
- *
- * - * @param response type returned by server on request success - * @param exception type returned by server on request failure - */ -public abstract class DbxUploader implements Closeable { - private final HttpRequestor.Uploader httpUploader; - private final StoneSerializer responseSerializer; - private final StoneSerializer errorSerializer; - - private boolean closed; - private boolean finished; - - protected DbxUploader(HttpRequestor.Uploader httpUploader, StoneSerializer responseSerializer, StoneSerializer errorSerializer) { - this.httpUploader = httpUploader; - this.responseSerializer = responseSerializer; - this.errorSerializer = errorSerializer; - - this.closed = false; - this.finished = false; - } - - protected abstract X newException(DbxWrappedException error); - - /** - * Uploads all bytes read from the given {@link InputStream} and returns the response. - * - * This method manages closing this uploader's resources, so no further calls to {@link #close} - * are necessary. The underlying {@code OutputStream} returned by {@link #getOutputStream} - * will be closed by this method. - * - * This method is the equivalent of - * - *

-     *    try {
-     *        OutputStream out = uploader.getOutputStream();
-     *        // read from in, write to out
-     *        response = uploader.finish();
-     *    } finally {
-     *        uploader.close();
-     *    }
-     * 
- * - * @param in {@code InputStream} containing data to upload - * - * @return Response from server - * - * @throws X if the server sent an error response for the request - * @throws DbxException if an error occurs uploading the data or reading the response - * @throws IOException if an error occurs reading the input stream. - * @throws IllegalStateException if this uploader has already been closed (see {@link #close}) or finished (see {@link #finish}) - */ - public R uploadAndFinish(InputStream in) throws X, DbxException, IOException { - try { - try { - httpUploader.upload(in); - } catch (IOException ex) { - // write exceptions and everything else is a Network I/O problem - throw new NetworkIOException(ex); - } - - return finish(); - } finally { - close(); - } - } - - /** - * Uploads up to {@code limit} bytes read from the given {@link InputStream} and returns the - * response. - * - * This method upload bytes from the given {@link InputStream} until {@code limit} bytes have - * been read or end-of-stream is detected. Use {@link #uploadAndFinish(InputStream)} to upload the entire - * stream. - * - * This method manages closing this uploader's resources, so no further calls to {@link #close} - * are necessary. The underlying {@code OutputStream} returned by {@link #getOutputStream} - * will be closed by this method. - * - * This method is the equivalent of - * - *

-     *    try {
-     *        OutputStream out = uploader.getOutputStream();
-     *        // read at most `limit` bytes from in, write to out
-     *        response = uploader.finish();
-     *    } finally {
-     *        uploader.close();
-     *    }
-     * 
- * - * @param in {@code InputStream} containing data to upload - * @param limit Maximum number of bytes to read from the given {@code InputStream} - * - * @return Response from server - * - * @throws X if the server sent an error response for the request - * @throws DbxException if an error occurs uploading the data or reading the response - * @throws IOException if an error occurs reading the input stream. - * @throws IllegalStateException if this uploader has already been closed (see {@link #close}) or finished (see {@link #finish}) - */ - public R uploadAndFinish(InputStream in, long limit) throws X, DbxException, IOException { - return uploadAndFinish(IOUtil.limit(in, limit)); - } - - /** - * Closes this upload request and releases its underlying resources. - * - * This method should always be called to allow for proper resource deallocation. - * - *

-     *    try {
-     *        OutputStream out = uploader.getOutputStream();
-     *        out.write(data);
-     *        response = uploader.finish();
-     *    } finally {
-     *        uploader.close();
-     *    }
-     * 
- */ - @Override - public void close() { - if (!closed) { - httpUploader.close(); - closed = true; - } - } - - /** - * Aborts this upload request and closes its underlying connection. - */ - public void abort() { - httpUploader.abort(); - } - - /** - * Returns an {@link OutputStream} that writes to the request body. Remember to call {@link - * #finish} to complete the request and retrieve the response. - * - * Data writen to this stream will be uploaded. - * - * Typically you will not need this method and can use the more convenient {@link - * #uploadAndFinish(InputStream)}. - * - * @return Request body output stream. - * - * @throws IllegalStateException if this uploader has already been closed (see {@link #close}) or finished (see {@link #finish}) - * - * @see #uploadAndFinish(InputStream) - */ - public OutputStream getOutputStream() { - assertOpenAndUnfinished(); - return this.httpUploader.getBody(); - } - - /** - * Completes the request and returns response from the server. - * - * This method should be called after writing data to the upload {@link OutputStream} (see - * {@link #getOutputStream}). - * - * @return Response from server - * - * @throws X if the server sent an error response for the request - * @throws DbxException if an error occurs sending the upload or reading the response - * @throws IllegalStateException if this uploader has already been closed (see {@link #close}) or finished (see {@link #finish}) - */ - public R finish() throws X, DbxException { - assertOpenAndUnfinished(); - - HttpRequestor.Response response = null; - try { - response = httpUploader.finish(); - - try { - if (response.getStatusCode() == 200) { - return responseSerializer.deserialize(response.getBody()); - } - else if (response.getStatusCode() == 409) { - DbxWrappedException wrapped = DbxWrappedException.fromResponse(errorSerializer, response); - throw newException(wrapped); - } - else { - throw DbxRequestUtil.unexpectedStatus(response); - } - } catch (JsonProcessingException ex) { - String requestId = DbxRequestUtil.getRequestId(response); - throw new BadResponseException(requestId, "Bad JSON in response: " + ex, ex); - } - } catch (IOException ex) { - throw new NetworkIOException(ex); - } finally { - // Make sure input stream is closed - if (response != null) { - IOUtil.closeQuietly(response.getBody()); - } - finished = true; - } - } - - private void assertOpenAndUnfinished() { - if (closed) { - throw new IllegalStateException("This uploader is already closed."); - } - if (finished) { - throw new IllegalStateException("This uploader is already finished and cannot be used to upload more data."); - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/DbxWrappedException.java b/src/autosaveworld/zlibs/com/dropbox/core/DbxWrappedException.java deleted file mode 100644 index bd1350c9..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/DbxWrappedException.java +++ /dev/null @@ -1,46 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core; - -import java.io.IOException; - -import autosaveworld.zlibs.com.dropbox.core.http.HttpRequestor; -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; - -/** - * For internal use only. - */ -public final class DbxWrappedException extends Exception { - private static final long serialVersionUID = 0L; - - private final Object errValue; // Really an ErrT instance, but Throwable does not allow generic subclasses. - private final String requestId; - private final LocalizedText userMessage; - - public DbxWrappedException(Object errValue, String requestId, LocalizedText userMessage) { - this.errValue = errValue; - this.requestId = requestId; - this.userMessage = userMessage; - } - - public Object getErrorValue() { - return errValue; - } - - public String getRequestId() { - return requestId; - } - - public LocalizedText getUserMessage() { - return userMessage; - } - - public static DbxWrappedException fromResponse(StoneSerializer errSerializer, HttpRequestor.Response response) - throws IOException, JsonParseException { - String requestId = DbxRequestUtil.getRequestId(response); - - ApiErrorResponse apiResponse = new ApiErrorResponse.Serializer(errSerializer) - .deserialize(response.getBody()); - - return new DbxWrappedException(apiResponse.getError(), requestId, apiResponse.getUserMessage()); - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/InvalidAccessTokenException.java b/src/autosaveworld/zlibs/com/dropbox/core/InvalidAccessTokenException.java deleted file mode 100644 index def73939..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/InvalidAccessTokenException.java +++ /dev/null @@ -1,20 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core; - -/** - * Gets thrown when the access token you're using to make API calls is invalid. - * - *

- * A more typical situation is that your access token was valid, but the - * user has since "unlinked" your application via the Dropbox website - * (http://www.dropbox.com/account#applications). - * When a user unlinks your application, your access tokens for that user become - * invalid. You can re-run the authorization process to obtain a new access token. - *

- */ -public class InvalidAccessTokenException extends DbxException { - private static final long serialVersionUID = 0; - - public InvalidAccessTokenException(String requestId, String message) { - super(requestId, message); - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/LocalizedText.java b/src/autosaveworld/zlibs/com/dropbox/core/LocalizedText.java deleted file mode 100644 index bf07d348..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/LocalizedText.java +++ /dev/null @@ -1,103 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core; - -import java.io.IOException; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializer; -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * Human-readable text localized to a specific locale. - */ -public final class LocalizedText { - private final String text; - private final String locale; - - /** - * Create a {@link LocalizedText} object that contains the given {@code text} already localized - * to {@code locale}. - * - * @param text Localized, human-readable text. Must not be {@code null} - * @param locale IETF BCP 47 language tag of text locale. Must not be {@code null} - */ - public LocalizedText(String text, String locale) { - if (text == null) { - throw new NullPointerException("text"); - } - if (locale == null) { - throw new NullPointerException("locale"); - } - - this.text = text; - this.locale = locale; - } - - /** - * Returns the localized, human-readable text. - * - * @return localized, human-readable text, never {@code null} - */ - public String getText() { - return text; - } - - /** - * Returns locale of the text in IETF BCP 47 language tag format. - * - * @return locale of text in IETF BCP 47 language tag format, never {@code null} - */ - public String getLocale() { - return locale; - } - - @Override - public String toString() { - return text; - } - - /** - * For internal use only. - */ - static final StoneSerializer STONE_SERIALIZER = new StoneSerializer() { - @Override - public void serialize(LocalizedText value, JsonGenerator g) throws IOException, JsonGenerationException { - throw new UnsupportedOperationException("Error wrapper serialization not supported."); - } - - @Override - public LocalizedText deserialize(JsonParser p) throws IOException, JsonParseException { - String text = null; - String locale = null; - - expectStartObject(p); - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("text".equals(field)) { - text = StoneSerializers.string().deserialize(p); - } else if ("locale".equals(field)) { - locale = StoneSerializers.string().deserialize(p); - } else { - skipValue(p); - } - } - - if (text == null) { - throw new JsonParseException(p, "Required field \"text\" missing."); - } - - if (locale == null) { - throw new JsonParseException(p, "Required field \"locale\" missing."); - } - - LocalizedText value = new LocalizedText(text, locale); - expectEndObject(p); - - return value; - } - }; -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/NetworkIOException.java b/src/autosaveworld/zlibs/com/dropbox/core/NetworkIOException.java deleted file mode 100644 index 87b4d45b..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/NetworkIOException.java +++ /dev/null @@ -1,26 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core; - -import java.io.IOException; - -/** - * This gets thrown when there's an {@link IOException} when reading or writing to the - * network (when communicating with the Dropbox API servers). - * - *

We use a separate exception class (instead of just relaying {@code IOException}) to make it - * easier for you to distinguish between I/O errors communicating with Dropbox and I/O errors from - * your own code.

- */ -public class NetworkIOException extends DbxException { - private static final long serialVersionUID = 0L; - - public NetworkIOException(IOException cause) { - super(cause.getMessage(), cause); - } - - @Override - public IOException getCause() { - // guaranteed to be an IOException - return (IOException) super.getCause(); - } -} - diff --git a/src/autosaveworld/zlibs/com/dropbox/core/ProtocolException.java b/src/autosaveworld/zlibs/com/dropbox/core/ProtocolException.java deleted file mode 100644 index ea2bb89e..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/ProtocolException.java +++ /dev/null @@ -1,26 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core; - -/** - * Something unexpected happened with either the request or the response. - * This can happen if there's a bug in the client code (including this - * library), if there's a bug in on the Dropbox server, or if Dropbox - * made a change to the API that changed the behavior of something and - * we haven't upgraded our SDK yet. - * - *

- * Typically, these kinds of exceptions should be logged, so you can - * investigate later. - *

- */ -public abstract class ProtocolException extends DbxException { - private static final long serialVersionUID = 0; - - public ProtocolException(String requestId, String message) { - super(requestId, message); - } - - public ProtocolException(String requestId, String message, Throwable cause) { - super(requestId, message, cause); - } -} - diff --git a/src/autosaveworld/zlibs/com/dropbox/core/RateLimitException.java b/src/autosaveworld/zlibs/com/dropbox/core/RateLimitException.java deleted file mode 100644 index c1ec6ba6..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/RateLimitException.java +++ /dev/null @@ -1,16 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core; - -import java.util.concurrent.TimeUnit; - -/** - * The server is overloaded, or you have hit a rate limit. Try again later after the designated - * backoff (see {@link #getBackoffMillis}). - */ -public class RateLimitException extends RetryException { - private static final long serialVersionUID = 0L; - - public RateLimitException(String requestId, String message, long backoff, TimeUnit unit) { - super(requestId, message, backoff, unit); - } -} - diff --git a/src/autosaveworld/zlibs/com/dropbox/core/RetryException.java b/src/autosaveworld/zlibs/com/dropbox/core/RetryException.java deleted file mode 100644 index 2a784c87..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/RetryException.java +++ /dev/null @@ -1,48 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core; - -import java.util.concurrent.TimeUnit; - -/** - * A transient exception has occurred and the request should be retried. Clients should only retry - * requests after waiting the requested backoff duration (see {@link #getBackoffMillis}). - */ -public class RetryException extends DbxException { - private static final long serialVersionUID = 0L; - - private final long backoffMillis; - - /** - * Creates an instance of this exception with no retry backoff. - * - * @param requestId ID assigned to request by Dropbox servers - * @param message Error message - */ - public RetryException(String requestId, String message) { - this(requestId, message, 0L, TimeUnit.MILLISECONDS); - } - - /** - * Creates an instance of this exception with the given retry backoff. - * - * @param requestId ID assigned to request by Dropbox servers - * @param message Error message - * @param backoff amount of time to backoff before retrying the request - * @param unit unit of time for {@code backoff} - */ - public RetryException(String requestId, String message, long backoff, TimeUnit unit) { - super(requestId, message); - - this.backoffMillis = unit.toMillis(backoff); - } - - /** - * Returns the number of milliseconds the client should backoff before retrying the request. - * - * @return backoff time, in seconds, before retrying the request, or {@code 0} if the request - * can be retried immediately. - */ - public long getBackoffMillis() { - return backoffMillis; - } -} - diff --git a/src/autosaveworld/zlibs/com/dropbox/core/ServerException.java b/src/autosaveworld/zlibs/com/dropbox/core/ServerException.java deleted file mode 100644 index d888a7db..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/ServerException.java +++ /dev/null @@ -1,33 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core; - -/** - * The server said that something went wrong on its end (HTTP 500 error code). - * This indicates bug on the Dropbox server, but there are multiple potential causes. - * - *
    - *
  • Sometimes it's just a bug and there's nothing you can - * do about it until its fixed. Report it on the Dropbox API forums. - *
  • - *
  • Sometimes you're actually making an invalid request, but for some reason - * the server's validation logic isn't catching the problem and it's - * causing the server to error-out somewhere down the line. You may be able to - * fix your request and get things working. This is still a bug on Dropbox's end, - * so you should still report it on the Dropbox API forums.
  • - *
  • Sometimes the error is intermittent. It may only happen once every few - * requests, in which case you can temporarily work around the issue by - * retrying the request. Again, this still counts as a bug so report it on - * the forums.
  • - *
  • Sometimes the error is temporary. For example, Dropbox might be experiencing - * a temporary network or hardware issue. If you wait a few minutes, the error - * might stop happening. You might want to check the forums to see if other - * people are seeing the same thing.
  • - *
- */ -public class ServerException extends DbxException { - private static final long serialVersionUID = 0; - - public ServerException(String requestId, String message) { - super(requestId, message); - } -} - diff --git a/src/autosaveworld/zlibs/com/dropbox/core/http/HttpRequestor.java b/src/autosaveworld/zlibs/com/dropbox/core/http/HttpRequestor.java deleted file mode 100644 index f98735b1..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/http/HttpRequestor.java +++ /dev/null @@ -1,158 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.http; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; -import java.util.concurrent.TimeUnit; - -import autosaveworld.zlibs.com.dropbox.core.util.IOUtil; - -/** - * An interface that the Dropbox client library uses to make HTTP requests. - * If you're fine with the standard Java {@link java.net.HttpURLConnection} - * implementation, then just use {@link StandardHttpRequestor#INSTANCE}. - */ -public abstract class HttpRequestor -{ - /** - * Default timeout, in milliseconds, for opening a connection to a network resource. - * - * A value of 0 indicates the timeout should be disabled. - */ - public static final long DEFAULT_CONNECT_TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(20); - /** - * Default timeout, in milliseconds, for receiving a response from a network resource. - * - * A value of 0 indicates the timeout should be disabled. - */ - // Careful about lowering this value. Large file uploads can result in slow responses from the - // server. - public static final long DEFAULT_READ_TIMEOUT_MILLIS = TimeUnit.MINUTES.toMillis(2); - - public abstract Response doGet(String url, Iterable
headers) throws IOException; - public abstract Uploader startPost(String url, Iterable
headers) throws IOException; - public abstract Uploader startPut(String url, Iterable
headers) throws IOException; - - /** - * A simple structure holding an HTTP header, which is key/value pair. - * Used with {@link HttpRequestor}. - */ - public static final class Header { - private final String key; - private final String value; - - public Header(String key, String value) { - this.key = key; - this.value = value; - } - - /** - * Returns header name. - * - * @return header name - */ - public String getKey() { - return key; - } - - /** - * Returns header value. - * - * @return header value - */ - public String getValue() { - return value; - } - } - - public static abstract class Uploader { - public abstract OutputStream getBody(); - public abstract void close(); - public abstract void abort(); - public abstract Response finish() throws IOException; - - public void upload(InputStream in, long limit) throws IOException { - upload(IOUtil.limit(in, limit)); - } - - public void upload(InputStream in) throws IOException { - OutputStream out = getBody(); - try { - IOUtil.copyStreamToStream(in, out); - } catch (IOUtil.ReadException ex) { - throw ex.getCause(); - } finally { - out.close(); - } - } - - public void upload(byte [] body) throws IOException { - OutputStream out = getBody(); - try { - out.write(body); - } finally { - out.close(); - } - } - } - - public static final class Response { - private final int statusCode; - private final InputStream body; - private final Map> headers; - - public Response(int statusCode, InputStream body, Map> headers) { - this.statusCode = statusCode; - this.body = body; - this.headers = asUnmodifiableCaseInsensitiveMap(headers); - } - - /** - * Returns HTTP status response code. - * - * @return HTTP status code - */ - public int getStatusCode() { - return statusCode; - } - - /** - * Returns an {@link InputStream} for reading the HTTP response body. - * - *

The returned stream must be fully read before closing. - * - * @return HTTP response body - */ - public InputStream getBody() { - return body; - } - - /** - * Returns a case-insensitive, unmodifiable mapping of header fields to their values. - * - * @return case-insensitive, unmodifiable headers - */ - public Map> getHeaders() { - return headers; - } - - private static final Map> asUnmodifiableCaseInsensitiveMap(Map> original) { - Map> insensitive = new TreeMap>(String.CASE_INSENSITIVE_ORDER); - for (Map.Entry> entry : original.entrySet()) { - // Java HttpURLConnection puts status line as the 'null' key, e.g.: - // - // HTTP/1.1 409 bad_member/invalid_dropbox_id/... - // - if (entry.getKey() == null || entry.getKey().trim().length() == 0) { - continue; - } - insensitive.put(entry.getKey(), Collections.unmodifiableList(entry.getValue())); - } - return Collections.unmodifiableMap(insensitive); - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/http/StandardHttpRequestor.java b/src/autosaveworld/zlibs/com/dropbox/core/http/StandardHttpRequestor.java deleted file mode 100644 index 8b05581a..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/http/StandardHttpRequestor.java +++ /dev/null @@ -1,430 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.http; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.Proxy; -import java.net.URL; -import java.util.concurrent.TimeUnit; - -import javax.net.ssl.HttpsURLConnection; - -import autosaveworld.zlibs.com.dropbox.core.util.IOUtil; - -/*>>> import checkers.nullness.quals.Nullable; */ - -/** - * {@link HttpRequestor} implementation that uses Java's standard library - * {@link HttpsURLConnection}. If you just want a connection with the - * default settings, use the predefined {@link #INSTANCE}. - * - *

- * If you want to customize the way the connection is configured, create a - * subclass that overrides {@link #configureConnection}. - *

- */ -public class StandardHttpRequestor extends HttpRequestor { - /** - * A thread-safe instance of {@code StandardHttpRequestor} that connects directly - * (as opposed to using a proxy). - */ - public static final StandardHttpRequestor INSTANCE = new StandardHttpRequestor(Config.DEFAULT_INSTANCE); - - private final Config config; - - /** - * Creates an instance that connects through the given proxy. - */ - public StandardHttpRequestor(Config config) { - this.config = config; - } - - private Response toResponse(HttpURLConnection conn) throws IOException { - int responseCode = conn.getResponseCode(); - InputStream bodyStream; - if (responseCode >= 400 || responseCode == -1) { - bodyStream = conn.getErrorStream(); - } else { - bodyStream = conn.getInputStream(); - } - interceptResponse(conn); - return new Response(responseCode, bodyStream, conn.getHeaderFields()); - } - - @Override - public Response doGet(String url, Iterable
headers) throws IOException { - HttpURLConnection conn = prepRequest(url, headers); - conn.setRequestMethod("GET"); - conn.connect(); - return toResponse(conn); - } - - @Override - public Uploader startPost(String url, Iterable
headers) throws IOException { - HttpURLConnection conn = prepRequest(url, headers); - conn.setRequestMethod("POST"); - return new Uploader(conn); - } - - @Override - public Uploader startPut(String url, Iterable
headers) throws IOException { - HttpURLConnection conn = prepRequest(url, headers); - conn.setRequestMethod("PUT"); - return new Uploader(conn); - } - - /** - * Can be overridden to configure the underlying {@link HttpsURLConnection} used to make - * network requests. If you override this method, you should probably call - * {@code super.configureConnection(conn)} in your overridden method. - * - * @deprecated use {@link #configure} instead. - */ - @Deprecated - protected void configureConnection(HttpsURLConnection conn) throws IOException { } - - /** - * Can be overriden to configure the underlying {@link HttpURLConnection} used to make network - * requests using https. Typically the connection will be a {@link - * javax.net.ssl.HttpsURLConnection}, but that is dependent on the Java runtime. Care should be - * taken when casting the connection (check your JRE). - * - *

If you are using Google App Engine, configure your {@link - * autosaveworld.zlibs.com.dropbox.core.DbxRequestConfig} to use {@link GoogleAppEngineRequestor} as its default - * {@code HttpRequestor}. If you use {@link StandardHttpRequestor} in Google App Engine, SSL - * certificates may not be validated and your app will susceptible to Man-in-the-Middle attacks. - * - * @param conn URL connection object returned after creating an https network request. - */ - protected void configure(HttpURLConnection conn) throws IOException { } - - /** - * Called before returning {@link Response} from a request. - * - *

This method should be used by subclasses to add any logging, analytics, or cleanup - * necessary. Note that the connection response code and response streams will already be - * fetched before calling this method. This means any {@link IOException} from reading the - * response should already have occurred before this method is called. - * - *

Do not consume the response or error streams in this method. - * - * @param conn HTTP URL connection - */ - protected void interceptResponse(HttpURLConnection conn) throws IOException { } - - private static OutputStream getOutputStream(HttpURLConnection conn) throws IOException { - conn.setDoOutput(true); - return conn.getOutputStream(); - } - - private class Uploader extends HttpRequestor.Uploader { - private final OutputStream out; - - private HttpURLConnection conn; - - public Uploader(HttpURLConnection conn) throws IOException { - this.conn = conn; - this.out = getOutputStream(conn); - - conn.connect(); - } - - @Override - public OutputStream getBody() { - return out; - } - - @Override - public void abort() { - if (conn == null) { - throw new IllegalStateException("Can't abort(). Uploader already closed."); - } - // disconnecting is "harsh" in that it can close the underlying streams and socket. This - // prevents connection re-use. - conn.disconnect(); - conn = null; - } - - @Override - public void close() { - if (conn == null) return; - - // close input and output streams to allow for connection re-use. - if (conn.getDoOutput()) { - try { - IOUtil.closeQuietly(conn.getOutputStream()); - } catch (IOException ex) { - // ignore - } - } - - // should not need to disconnect after closing the relevant streams - conn = null; - } - - @Override - public Response finish() throws IOException { - if (conn == null) { - throw new IllegalStateException("Can't finish(). Uploader already closed."); - } - - try { - return toResponse(conn); - } finally { - conn = null; - } - } - } - - private HttpURLConnection prepRequest(String url, Iterable

headers) throws IOException { - URL urlObject = new URL(url); - HttpURLConnection conn = (HttpURLConnection) urlObject.openConnection(config.getProxy()); - - conn.setConnectTimeout((int) config.getConnectTimeoutMillis()); - conn.setReadTimeout((int) config.getReadTimeoutMillis()); - conn.setUseCaches(false); - conn.setAllowUserInteraction(false); - - // Some JREs (like the one provided by Google AppEngine) will return HttpURLConnection - // instead of HttpsURLConnection. So we have to check here. - // AutoSaveWorld - do not do pinning for now -// if (conn instanceof HttpsURLConnection) { -// SSLConfig.apply((HttpsURLConnection) conn); -// configureConnection((HttpsURLConnection) conn); -// } else { -// logCertificatePinningWarning(); -// } - - configure(conn); - - for (Header header : headers) { - conn.addRequestProperty(header.getKey(), header.getValue()); - } - - return conn; - } - -// private static void logCertificatePinningWarning() { -// if (!certPinningWarningLogged) { -// certPinningWarningLogged = true; -// LOGGER.warning("Certificate pinning disabled for HTTPS connections. This is likely because your JRE does not " + -// "return javax.net.ssl.HttpsURLConnection objects for https network connections. Be aware your app " + -// "may be prone to man-in-the-middle attacks without proper SSL certificate validation. If you are " + -// "using Google App Engine, please configure DbxRequestConfig to use GoogleAppEngineRequestor."); -// } -// } - - /** - * Configuration for {@link StandardHttpRequestor} that determines - * how network connections to the server are established. - * - * Use this class to configure timeouts and proxy settings. - * - * Some requests may require different connection settings than - * others. Create multiple {@link StandardHttpRequestor} objects - * with different configurations to handle these requests. For - * example, calls to {@link - * autosaveworld.zlibs.com.dropbox.core.v2.files.DbxUserFilesRequests#listFolderLongpoll(String,long)} should - * use a {@code StandardHttpRequestor} with its read timeout (see - * {@link Builder#withReadTimeout}) set longer than the longpoll - * timeout. - */ - public static final class Config { - /** - * {@link Config} with all its attributes set to their default - * values. - */ - public static final Config DEFAULT_INSTANCE = builder().build(); - - private final Proxy proxy; - private final long connectTimeoutMillis; - private final long readTimeoutMillis; - - private Config(Proxy proxy, - long connectTimeoutMillis, - long readTimeoutMillis) { - this.proxy = proxy; - this.connectTimeoutMillis = connectTimeoutMillis; - this.readTimeoutMillis = readTimeoutMillis; - } - - /** - * Returns the proxy configuration for network connections. - * - * @return proxy configuration to use for network connections. - */ - public Proxy getProxy() { - return proxy; - } - - /** - * Returns the timeout, in milliseconds, for opening a - * connection to the servers. - * - * If the timeout is 0, then connect timeouts are disabled. - * - * @return timeout, in milliseconds, for opening connections - * to the servers. - */ - public long getConnectTimeoutMillis() { - return connectTimeoutMillis; - } - - /** - * Returns the timeout, in milliseconds, for receiving a - * response from the servers. - * - * If the timeout is 0, then read timeouts are disabled. - * - * @return timeout, in milliseconds, for receiving a response - * from the server. - */ - public long getReadTimeoutMillis() { - return readTimeoutMillis; - } - - /** - * Returns a new builder for creating a copy of this - * config. The builder is configured to use this config's - * values as its default. - * - * @return builder for creating a copy of this config. - */ - public Builder copy() { - return new Builder(proxy, connectTimeoutMillis, readTimeoutMillis); - } - - /** - * Returns a new builder for creating a {@link Config}. - * - * @return builder for creating an instance of this class - */ - public static Builder builder() { - return new Builder(); - } - - /** - * Builder for {@link Config}. - */ - public static final class Builder { - private Proxy proxy; - private long connectTimeoutMillis; - private long readTimeoutMillis; - - private Builder() { - this(Proxy.NO_PROXY, DEFAULT_CONNECT_TIMEOUT_MILLIS, DEFAULT_READ_TIMEOUT_MILLIS); - } - - private Builder(Proxy proxy, long connectTimeoutMillis, long readTimeoutMillis) { - this.proxy = proxy; - this.connectTimeoutMillis = connectTimeoutMillis; - this.readTimeoutMillis = readTimeoutMillis; - } - - /** - * Set proxy configuration for network connections. - * - * @param proxy Proxy configuration - * - * @return this builder - * - * @throws NullPointerException if {@code proxy} is {@code null} - */ - public Builder withProxy(Proxy proxy) { - if (proxy == null) { - throw new NullPointerException("proxy"); - } - this.proxy = proxy; - return this; - } - - /** - * Disables timeouts for opening a connection to the - * servers. - * - * @return this builder - */ - public Builder withNoConnectTimeout() { - return withConnectTimeout(0L, TimeUnit.MILLISECONDS); - } - - /** - * Set timeout for opening a connection to the servers. - * - * A timeout of 0 will disable any connnect timeouts. - * - * @param timeout time to wait for a network connection to open - * @param unit unit of time - * - * @return this builder - * - * @throws IllegalArgumentException if {@code timeout} is negative - * @throws NullPointerException if {@code unit} is {@code null} - */ - public Builder withConnectTimeout(long timeout, TimeUnit unit) { - this.connectTimeoutMillis = checkTimeoutMillis(timeout, unit); - return this; - } - - /** - * Disables timeout for receiving a response from the servers. - * - * @return this builder - */ - public Builder withNoReadTimeout() { - return withReadTimeout(0L, TimeUnit.MILLISECONDS); - } - - /** - * Sets timeout for receiving a response from the servers. - * - * This timeout is not for receiving the entire server - * response. A server that responds with bytes slowly will - * not trigger the timeout, unless the specified amount of - * time has passed between received bytes. - * - * A timeout of 0 will disable any read timeouts. - * - * @param timeout time to wait for a response from the server - * @param unit unit of time - * - * @return this builder - * - * @throws IllegalArgumentException if {@code timeout} is negative - * @throws NullPointerException if {@code unit} is {@code null} - */ - public Builder withReadTimeout(long timeout, TimeUnit unit) { - this.readTimeoutMillis = checkTimeoutMillis(timeout, unit); - return this; - } - - /** - * Returns a {@link Config} with the values set by this builder. - * - * @return {@link Config} with this builder's values - */ - public Config build() { - return new Config( - proxy, - connectTimeoutMillis, - readTimeoutMillis - ); - } - - private static long checkTimeoutMillis(long timeout, TimeUnit unit) { - if (unit == null) { - throw new NullPointerException("unit"); - } - if (timeout < 0) { - throw new IllegalArgumentException("timeout must be non-negative"); - } - long millis = unit.toMillis(timeout); - if (Integer.MAX_VALUE < millis) { - throw new IllegalArgumentException("timeout too large, must be less than: " + Integer.MAX_VALUE); - } - return millis; - } - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/json/JsonArrayReader.java b/src/autosaveworld/zlibs/com/dropbox/core/json/JsonArrayReader.java deleted file mode 100644 index 7a67f6fa..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/json/JsonArrayReader.java +++ /dev/null @@ -1,56 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.json; - -import java.io.IOException; -import java.util.List; - -import autosaveworld.zlibs.com.dropbox.core.util.Collector; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; - -public class JsonArrayReader extends JsonReader -{ - public final JsonReader elementReader; - public final Collector collector; - - public JsonArrayReader(JsonReader elementReader, Collector collector) - { - this.elementReader = elementReader; - this.collector = collector; - } - - public static JsonArrayReader> mk(JsonReader elementReader) - { - return new JsonArrayReader>(elementReader, new Collector.ArrayListCollector()); - } - - public static JsonArrayReader mk(JsonReader elementReader, Collector collector) - { - return new JsonArrayReader(elementReader, collector); - } - - public L read(JsonParser parser) - throws JsonReadException, IOException - { - return read(elementReader, collector, parser); - } - - public static L read(JsonReader elementReader, Collector collector, JsonParser parser) - throws JsonReadException, IOException - { - expectArrayStart(parser); - - int index = 0; - while (!isArrayEnd(parser)) { - try { - T value = elementReader.read(parser); - collector.add(value); - index++; - } - catch (JsonReadException ex) { - throw ex.addArrayContext(index); - } - } - - parser.nextToken(); - return collector.finish(); - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/json/JsonDateReader.java b/src/autosaveworld/zlibs/com/dropbox/core/json/JsonDateReader.java deleted file mode 100644 index 165486f8..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/json/JsonDateReader.java +++ /dev/null @@ -1,292 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.json; - -import java.io.IOException; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonLocation; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; - -public class JsonDateReader -{ - /** - * A parser for dates returned by the Dropbox API. - */ - public static final JsonReader Dropbox = new JsonReader() { - @Override - public Date read(JsonParser parser) throws IOException, JsonReadException - { - JsonLocation l = parser.getCurrentLocation(); - try { - char[] buffer = parser.getTextCharacters(); - int offset = parser.getTextOffset(); - int length = parser.getTextLength(); - Date d = parseDropboxDate(buffer, offset, length); - parser.nextToken(); - return d; - } - catch (JsonParseException ex) { - throw JsonReadException.fromJackson(ex); - } - catch (java.text.ParseException ex) { - throw new JsonReadException("bad date: \"" + ex.getMessage() + " at offset " + ex.getErrorOffset(), l); - } - } - }; - - public static Date parseDropboxDate(char[] buffer, int offset, int length) - throws java.text.ParseException - { - int i = offset; - char[] b = buffer; - - if (length != 31) { - throw new java.text.ParseException("expecting date to be 31 characters, got " + length, 0); - } - - // Hopefully this check lets the JVM eliminate array bounds checks for the rest of the function. - if (b.length < i + 31 || i < 0) { - throw new IllegalArgumentException("range is not within 'b'"); - } - - // 0 1 2 3 - // 0123456789012345678901234567890 - // DDD, DD MMM YYYY HH:MM:SS +0000 - - // Check for fixed values. Using non-short-circuit OR because it's faster - // for the common case of them all being correct. - if (b[i+3] != ',' | b[i+4] != ' ' | b[i+7] != ' ' | b[i+11] != ' ' - | b[i+16] != ' ' | b[i+19] != ':' | b[i+22] != ':' | b[i+25] != ' ' - | b[i+26] != '+' | b[i+27] != '0' | b[i+28] != '0' | b[i+29] != '0' | b[i+30] != '0') { - if (b[i+3] != ',') throw new java.text.ParseException("expecting ','", 3); - if (b[i+4] != ' ') throw new java.text.ParseException("expecting ' '", 4); - if (b[i+7] != ' ') throw new java.text.ParseException("expecting ' '", 7); - if (b[i+11] != ' ') throw new java.text.ParseException("expecting ' '", 11); - if (b[i+16] != ' ') throw new java.text.ParseException("expecting ' '", 16); - if (b[i+19] != ':') throw new java.text.ParseException("expecting ':'", 19); - if (b[i+22] != ':') throw new java.text.ParseException("expecting ':'", 22); - if (b[i+25] != ' ') throw new java.text.ParseException("expecting ' '", 25); - if (b[i+26] != '+') throw new java.text.ParseException("expecting '+'", 26); - if (b[i+27] != '0') throw new java.text.ParseException("expecting '0'", 27); - if (b[i+28] != '0') throw new java.text.ParseException("expecting '0'", 28); - if (b[i+29] != '0') throw new java.text.ParseException("expecting '0'", 29); - if (b[i+30] != '0') throw new java.text.ParseException("expecting '0'", 30); - throw new AssertionError("unreachable"); - } - - // Parse day of week string. - if (!isValidDayOfWeek(b[i], b[i+1], b[i+2])) { - throw new java.text.ParseException("invalid day of week", i); - } - - // Month string. - int month = getMonthIndex(b[i+8], b[i+9], b[i+10]); - if (month == -1) { - throw new java.text.ParseException("invalid month", 8); - } - - // Day of month. - char d1 = b[i+5]; - char d2 = b[i+6]; - - if (!isDigit(d1) || !isDigit(d2)) { - throw new java.text.ParseException("invalid day of month", 5); - } - - int dayOfMonth = d1*10 + d2 - ('0' * 11); - - // Year - char y1 = b[i+12]; - char y2 = b[i+13]; - char y3 = b[i+14]; - char y4 = b[i+15]; - - if (!isDigit(y1) | !isDigit(y2) | !isDigit(y3) | !isDigit(y4)) { - throw new java.text.ParseException("invalid year", 12); - } - - int year = y1*1000 + y2*100 + y3*10 + y4 - ('0' * 1111); - - // Hour - char h1 = b[i+17]; - char h2 = b[i+18]; - - if (!isDigit(h1) | !isDigit(h2)) { - throw new java.text.ParseException("invalid hour", 17); - } - - int hour = h1*10 + h2 - ('0' * 11); - - // Minute - char m1 = b[i+20]; - char m2 = b[i+21]; - - if (!isDigit(m1) | !isDigit(m2)) { - throw new java.text.ParseException("invalid minute", 20); - } - - int minute = m1*10 + m2 - ('0' * 11); - - // Second - char s1 = b[i+23]; - char s2 = b[i+24]; - - if (!isDigit(s1) | !isDigit(s2)) { - throw new java.text.ParseException("invalid second", 23); - } - - int second = s1*10 + s2 - ('0' * 11); - - // TODO: How do we validate that the numbers are in range? - GregorianCalendar c = new GregorianCalendar(year, month, dayOfMonth, hour, minute, second); - c.setTimeZone(UTC); - return c.getTime(); - } - - public static final TimeZone UTC = TimeZone.getTimeZone("UTC"); - - private static boolean isDigit(char c) - { - return c >= '0' && c <= '9'; - } - - public static boolean isValidDayOfWeek(char a, char b, char c) - { - // Using non-short-circuit AND because it's faster for the common case of the values being correct. - switch (a) { - case 'S': - if (b == 'u' & c == 'n') return true; - if (b == 'a' & c == 't') return true; - return false; - case 'M': - if (b == 'o' & c == 'n') return true; - return false; - case 'T': - if (b == 'u' & c == 'e') return true; - if (b == 'h' & c == 'u') return true; - return false; - case 'W': - if (b == 'e' & c == 'd') return true; - return false; - case 'F': - if (b == 'r' & c == 'i') return true; - return false; - default: - return false; - } - } - - public static int getMonthIndex(char a, char b, char c) - { - switch (a) { - case 'J': - if (b == 'a' & c == 'n') return 0; - if (b == 'u') { - if (c == 'n') return 5; - if (c == 'l') return 6; - return -1; - } - return -1; - case 'F': - if (b == 'e' & c == 'b') return 1; - return 0; - case 'M': - if (b == 'a') { - if (c == 'r') return 2; - if (c == 'y') return 4; - return -1; - } - return -1; - case 'A': - if (b == 'p' & c == 'r') return 3; - if (b == 'u' & c == 'g') return 7; - return -1; - case 'S': - if (b == 'e' & c == 'p') return 8; - return -1; - case 'O': - if (b == 'c' & c == 't') return 9; - return -1; - case 'N': - if (b == 'o' & c == 'v') return 10; - return -1; - case 'D': - if (b == 'e' & c == 'c') return 11; - return -1; - default: - return -1; - } - } - - /** - * A parser for dates returned by the Dropbox V2 API. - * - * This parses only the new ISO 8601 format - * (e.g. {@literal "2010-01-01T12:00:00Z"} - * or {@literal "2010-01-01T12:00:00.000Z"}). - */ - public static final JsonReader DropboxV2 = new JsonReader() { - @Override - public Date read(JsonParser parser) throws IOException, JsonReadException - { - JsonLocation l = parser.getCurrentLocation(); - try { - char[] buffer = parser.getTextCharacters(); - int offset = parser.getTextOffset(); - int length = parser.getTextLength(); - Date d = parseDropbox8601Date(buffer, offset, length); - parser.nextToken(); - return d; - } - catch (JsonParseException ex) { - throw JsonReadException.fromJackson(ex); - } - catch (java.text.ParseException ex) { - throw new JsonReadException("bad date: \"" + ex.getMessage() + " at offset " + ex.getErrorOffset(), l); - } - } - }; - - public static Date parseDropbox8601Date(char[] buffer, int offset, int length) - throws java.text.ParseException - { - int i = offset; - char[] b = buffer; - - if (length != 20 && length != 24) { - throw new java.text.ParseException("expecting date to be 20 or 24 characters, got " + length, 0); - } - - // TODO: This needs to be looked at further. - // Does this need to handle arbitrary timezones? - String s = new String(b, i, length); - final DateFormat format; - if (length == 20) { - // Assume this is an ISO 8601 date with a trailing Z to indicate UTC: - // e.g. "2015-04-01T12:01:12Z", - format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); - } else { - // Assume this is an ISO 8601 date with a trailing Z to indicate UTC: - // plus milliseconds, e.g. "2012-04-23T18:25:43.511Z". - format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); - } - format.setTimeZone(TimeZone.getTimeZone("UTC")); - - Date result; - try { - result = format.parse(s); - } catch (IllegalArgumentException ex) { - throw new java.text.ParseException("invalid characters in date" + s, 0); - } - - if (result == null) { - throw new java.text.ParseException("invalid date" + s, 0); - } - - return result; - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/json/JsonReadException.java b/src/autosaveworld/zlibs/com/dropbox/core/json/JsonReadException.java deleted file mode 100644 index e9586e69..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/json/JsonReadException.java +++ /dev/null @@ -1,109 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.json; - -import java.io.File; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonLocation; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonProcessingException; - -/*>>> import checkers.nullness.quals.Nullable; */ - -public final class JsonReadException extends java.lang.Exception -{ - public static final long serialVersionUID = 0; - - public final String error; - public final JsonLocation location; - private /*@Nullable*/PathPart path; - - public JsonReadException(String error, JsonLocation location) - { - this.error = error; - this.location = location; - this.path = null; - } - - public JsonReadException(String error, JsonLocation location, Throwable cause) - { - super(cause); - this.error = error; - this.location = location; - this.path = null; - } - - public JsonReadException addFieldContext(String fieldName) - { - this.path = new PathPart('"' + fieldName + '"', this.path); - return this; - } - - public JsonReadException addArrayContext(int index) - { - this.path = new PathPart(Integer.toString(index), this.path); - return this; - } - - public String getMessage() - { - StringBuilder buf = new StringBuilder(); - - // Location - toStringLocation(buf, location); - buf.append(": "); - - // "Logical Path" - if (path != null) { - PathPart p = path; - buf.append(p.description); - while (p.next != null) { - p = p.next; - buf.append("."); - buf.append(p.description); - } - buf.append(": "); - } - - // Actual error message. - buf.append(error); - - return buf.toString(); - } - - public static void toStringLocation(StringBuilder buf, JsonLocation location) - { - Object sourceRef = location.getSourceRef(); - if (sourceRef instanceof File) { - File f = (File) sourceRef; - buf.append(f.getPath()); - buf.append(": "); - } - - buf.append(location.getLineNr()); - buf.append("."); - buf.append(location.getColumnNr()); - } - - public static final class PathPart - { - public final String description; - public final /*@Nullable*/PathPart next; - - public PathPart(String description, /*@Nullable*/PathPart next) - { - this.description = description; - this.next = next; - } - } - - public static JsonReadException fromJackson(JsonProcessingException ex) - { - String message = ex.getMessage(); - - // Strip off location. - int locPos = message.lastIndexOf(" at [Source"); - if (locPos >= 0) { - message = message.substring(0, locPos); - } - - return new JsonReadException(message, ex.getLocation()); - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/json/JsonReader.java b/src/autosaveworld/zlibs/com/dropbox/core/json/JsonReader.java deleted file mode 100644 index c105cb7a..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/json/JsonReader.java +++ /dev/null @@ -1,574 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.json; - -import static autosaveworld.zlibs.com.dropbox.core.util.LangUtil.mkAssert; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; - -import autosaveworld.zlibs.com.dropbox.core.util.IOUtil; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonFactory; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonLocation; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/*>>> import checkers.nullness.quals.Nullable; */ - -public abstract class JsonReader -{ - public abstract T read(JsonParser parser) - throws IOException, JsonReadException; - - public T readFromTags(String[] tags, JsonParser parser) - throws IOException, JsonReadException - { - return null; // Must override for struct - } - - public T readFields(JsonParser parser) - throws IOException, JsonReadException - { - return null; // Must override for struct - } - - public void validate(T value) - { - // Base implementation does nothing. - } - - public final T readField(JsonParser parser, String fieldName, /*@Nullable*/T v) - throws IOException, JsonReadException - { - if (v != null) throw new JsonReadException("duplicate field \"" + fieldName + "\"", parser.getTokenLocation()); - return read(parser); - } - - public final /*@Nullable*/T readOptional(JsonParser parser) - throws IOException, JsonReadException - { - if (parser.getCurrentToken() == JsonToken.VALUE_NULL) { - parser.nextToken(); - return null; - } else { - return read(parser); - } - } - - /** - * Helper to read and parse the optional ".tag" field. If one is found, positions the parser - * at the next field (or the closing brace); otherwise leaves the parser position unchanged. - * Returns null if there isn't a ".tag" field; otherwise an array of strings (the tags). - * Initially the parser must be positioned right after the opening brace. - */ - public static String[] readTags(JsonParser parser) - throws IOException, JsonReadException - { - if (parser.getCurrentToken() != JsonToken.FIELD_NAME) { - return null; - } - if (!".tag".equals(parser.getCurrentName())) { - return null; - } - parser.nextToken(); - if (parser.getCurrentToken() != JsonToken.VALUE_STRING) { - throw new JsonReadException("expected a string value for .tag field", parser.getTokenLocation()); - } - String tag = parser.getText(); - parser.nextToken(); - return tag.split("\\."); - } - - /** - * A wrapper around 'JsonParser.nextToken' that throws our own better {@link JsonReadException} - * instead of Jackson's {@link JsonParseException}. - *

- * JsonParseException is bad for two reasons. First, it extends IOException, which makes it easy to - * miss. Second, there's no way to get the original error message, which makes it hard to chain - * logical location information (see {@link JsonReadException#addFieldContext} and - * {@link JsonReadException#addArrayContext}). - */ - public static JsonToken nextToken(JsonParser parser) - throws IOException, JsonReadException - { - try { - return parser.nextToken(); - } - catch (JsonParseException ex) { - throw JsonReadException.fromJackson(ex); - } - } - - // ------------------------------------------------------------------ - // Delimiter checking helpers. - - public static JsonLocation expectObjectStart(JsonParser parser) - throws IOException, JsonReadException - { - if (parser.getCurrentToken() != JsonToken.START_OBJECT) { - throw new JsonReadException("expecting the start of an object (\"{\")", parser.getTokenLocation()); - } - JsonLocation loc = parser.getTokenLocation(); - nextToken(parser); - return loc; - } - - public static void expectObjectEnd(JsonParser parser) - throws IOException, JsonReadException - { - if (parser.getCurrentToken() != JsonToken.END_OBJECT) { - throw new JsonReadException("expecting the end of an object (\"}\")", parser.getTokenLocation()); - } - nextToken(parser); - } - - public static JsonLocation expectArrayStart(JsonParser parser) - throws IOException, JsonReadException - { - if (parser.getCurrentToken() != JsonToken.START_ARRAY) { - throw new JsonReadException("expecting the start of an array (\"[\")", parser.getTokenLocation()); - } - JsonLocation loc = parser.getTokenLocation(); - nextToken(parser); - return loc; - } - - public static JsonLocation expectArrayEnd(JsonParser parser) - throws IOException, JsonReadException - { - if (parser.getCurrentToken() != JsonToken.END_ARRAY) { - throw new JsonReadException("expecting the end of an array (\"[\")", parser.getTokenLocation()); - } - JsonLocation loc = parser.getTokenLocation(); - nextToken(parser); - return loc; - } - - public static boolean isArrayEnd(JsonParser parser) - { - return (parser.getCurrentToken() == JsonToken.END_ARRAY); - } - - public static boolean isArrayStart(JsonParser parser) - { - return (parser.getCurrentToken() == JsonToken.START_ARRAY); - } - - public static void skipValue(JsonParser parser) - throws IOException, JsonReadException - { - try { - parser.skipChildren(); - parser.nextToken(); - } - catch (JsonParseException ex) { - throw JsonReadException.fromJackson(ex); - } - } - - // ------------------------------------------------------------------ - // Helpers for various types. - - public static final JsonReader UnsignedLongReader = new JsonReader() { - @Override - public Long read(JsonParser parser) - throws IOException, JsonReadException - { - return readUnsignedLong(parser); - } - }; - - public static long readUnsignedLong(JsonParser parser) - throws IOException, JsonReadException - { - try { - long v = parser.getLongValue(); - if (v < 0) { - throw new JsonReadException("expecting a non-negative number, got: " + v, parser.getTokenLocation()); - } - parser.nextToken(); - return v; - } - catch (JsonParseException ex) { - throw JsonReadException.fromJackson(ex); - } - } - - public static long readUnsignedLongField(JsonParser parser, String fieldName, long v) - throws IOException, JsonReadException - { - if (v >= 0) throw new JsonReadException("duplicate field \"" + fieldName + "\"", parser.getCurrentLocation()); - return JsonReader.readUnsignedLong(parser); - } - - public static final JsonReader Int64Reader = new JsonReader() - { - public Long read(JsonParser parser) - throws IOException, JsonReadException - { - long v = parser.getLongValue(); - parser.nextToken(); - return v; - } - }; - - public static final JsonReader Int32Reader = new JsonReader() - { - public Integer read(JsonParser parser) - throws IOException, JsonReadException - { - int v = parser.getIntValue(); - parser.nextToken(); - return v; - } - }; - - // NOTE: This can't read values >= 2**63. - public static final JsonReader UInt64Reader = new JsonReader() - { - public Long read(JsonParser parser) - throws IOException, JsonReadException - { - return readUnsignedLong(parser); - } - }; - - // NOTE: This stores the value in a Long. - public static final JsonReader UInt32Reader = new JsonReader() - { - public Long read(JsonParser parser) - throws IOException, JsonReadException - { - long v = readUnsignedLong(parser); - if (v >= 4294967296L) { - throw new JsonReadException("expecting a 32-bit unsigned integer, got: " + v, parser.getTokenLocation()); - } - return v; - } - }; - - public static final JsonReader Float64Reader = new JsonReader() - { - public Double read(JsonParser parser) - throws IOException, JsonReadException - { - double v = parser.getDoubleValue(); - parser.nextToken(); - return v; - } - }; - - public static final JsonReader Float32Reader = new JsonReader() - { - public Float read(JsonParser parser) - throws IOException, JsonReadException - { - float v = parser.getFloatValue(); - parser.nextToken(); - return v; - } - }; - - public static final JsonReader StringReader = new JsonReader() - { - public String read(JsonParser parser) - throws IOException, JsonReadException - { - try { - String v = parser.getText(); - parser.nextToken(); - return v; - } - catch (JsonParseException ex) { - throw JsonReadException.fromJackson(ex); - } - } - }; - - public static final JsonReader BinaryReader = new JsonReader() - { - public byte[] read(JsonParser parser) - throws IOException, JsonReadException - { - try { - // TODO: Jackson's base64 parser is more lenient than we want (it allows whitespace - // and other junk in some places). Switch to something more strict. - byte[] v = parser.getBinaryValue(); - parser.nextToken(); - return v; - } - catch (JsonParseException ex) { - throw JsonReadException.fromJackson(ex); - } - } - }; - - public static final JsonReader BooleanReader = new JsonReader() - { - public Boolean read(JsonParser parser) - throws IOException, JsonReadException - { - return readBoolean(parser); - } - }; - - public static boolean readBoolean(JsonParser parser) - throws IOException, JsonReadException - { - try { - boolean b = parser.getBooleanValue(); - parser.nextToken(); - return b; - } - catch (JsonParseException ex) { - throw JsonReadException.fromJackson(ex); - } - } - - public static double readDouble(JsonParser parser) - throws IOException, JsonReadException - { - try { - double v = parser.getDoubleValue(); - parser.nextToken(); - return v; - } catch (JsonParseException ex) { - throw JsonReadException.fromJackson(ex); - } - } - - public static final JsonReader VoidReader = new JsonReader() - { - public Object read(JsonParser parser) - throws IOException, JsonReadException - { - skipValue(parser); - return null; - } - }; - - public static T readEnum(JsonParser parser, HashMap values, T catch_all) - throws IOException, JsonReadException - { - if (parser.getCurrentToken() == JsonToken.START_OBJECT) { - // Allow {".tag": "foo"} or {"foo": } or {".tag": "foo", "foo": }. - parser.nextToken(); - String text; - String[] tags = readTags(parser); - if (tags != null && parser.getCurrentToken() == JsonToken.END_OBJECT) { - assert tags.length == 1 && tags[0] != null; - text = tags[0]; - } - else if (parser.getCurrentToken() == JsonToken.FIELD_NAME) { - text = parser.getText(); - assert tags == null || tags[0].equals(text); - parser.nextToken(); - skipValue(parser); - } - else { - throw new JsonReadException("expecting a field name", parser.getTokenLocation()); - } - T value = values.get(text); - if (value == null) - value = catch_all; - if (value == null) - throw new JsonReadException("Expected one of " + values + ", got: " + text, parser.getTokenLocation()); - expectObjectEnd(parser); - return value; - } - if (parser.getCurrentToken() != JsonToken.VALUE_STRING) - throw new JsonReadException("Expected a string value", parser.getTokenLocation()); - String text = parser.getText(); - T value = values.get(text); - if (value == null) - value = catch_all; - if (value == null) - throw new JsonReadException("Expected one of " + values + ", got: " + text, parser.getTokenLocation()); - parser.nextToken(); - return value; - } - - /** - * If you're implementing a {@link JsonReader} for a JSON object, you can use this to map - * field names to a number you can {@code switch} on to efficiently locate assign a - * field. - */ - public static final class FieldMapping - { - // This is not optimized. Potential optimizations: - // - Store 'int' values instead of 'Integer' values. - // - Don't use "HashMap". Do something gperf-like that generates a faster hash - // function for when you know the valid strings ahead-of-time. - // - The get() could take (char[], offset, length) instead of String, which we can - // provide straight from JsonParser's internal buffer. This makes error reporting - // tricky, though, because we won't have a string for addFieldContext. - public final HashMap fields; - - private FieldMapping(HashMap fields) - { - assert fields != null; - this.fields = fields; - } - - public int get(String fieldName) - { - Integer i = fields.get(fieldName); - if (i == null) return -1; - return i; - } - - public static final class Builder - { - private /*@Nullable*/HashMap fields = new HashMap(); - - public void add(String fieldName, int expectedIndex) - { - if (fields == null) throw new IllegalStateException("already called build(); can't call add() anymore"); - int i = fields.size(); - if (expectedIndex != i) { - throw new IllegalStateException("expectedIndex = " + expectedIndex + ", actual = " + i); - } - Object displaced = fields.put(fieldName, i); - if (displaced != null) { - throw new IllegalStateException("duplicate field name: \"" + fieldName + "\""); - } - } - - public FieldMapping build() - { - if (fields == null) throw new IllegalStateException("already called build(); can't call build() again"); - HashMap f = fields; - this.fields = null; - return new FieldMapping(f); - } - } - } - - static final JsonFactory jsonFactory = new JsonFactory(); - - public T readFully(InputStream utf8Body) - throws IOException, JsonReadException - { - try { - JsonParser parser = jsonFactory.createParser(utf8Body); - return readFully(parser); - } - catch (JsonParseException ex) { - throw JsonReadException.fromJackson(ex); - } - } - - public T readFully(String body) - throws JsonReadException - { - try { - JsonParser parser = jsonFactory.createParser(body); - try { - return readFully(parser); - } - finally { - parser.close(); - } - } - catch (JsonParseException ex) { - throw JsonReadException.fromJackson(ex); - } - catch (IOException ex) { - throw mkAssert("IOException reading from String", ex); - } - } - - public T readFully(byte[] utf8Body) - throws JsonReadException - { - try { - JsonParser parser = jsonFactory.createParser(utf8Body); - try { - return readFully(parser); - } - finally { - parser.close(); - } - } - catch (JsonParseException ex) { - throw JsonReadException.fromJackson(ex); - } - catch (IOException ex) { - throw mkAssert("IOException reading from byte[]", ex); - } - } - - public T readFromFile(String filePath) - throws FileLoadException - { - return readFromFile(new File(filePath)); - } - - public T readFromFile(File file) - throws FileLoadException - { - try { - InputStream in = new FileInputStream(file); - try { - return readFully(in); - } - finally { - IOUtil.closeInput(in); - } - } - catch (JsonReadException ex) { - throw new FileLoadException.JsonError(file, ex); - } - catch (IOException ex) { - throw new FileLoadException.IOError(file, ex); - } - } - - public static abstract class FileLoadException extends Exception { - private static final long serialVersionUID = 0L; - - protected FileLoadException(String message) - { - super(message); - } - - public static final class IOError extends FileLoadException { - private static final long serialVersionUID = 0L; - - public final IOException reason; - - public IOError(File file, IOException reason) - { - super("unable to read file \"" + file.getPath() + "\": " + reason.getMessage()); - this.reason = reason; - } - } - - public static final class JsonError extends FileLoadException { - private static final long serialVersionUID = 0L; - - public final JsonReadException reason; - - public JsonError(File file, JsonReadException reason) - { - super(file.getPath() + ": " + reason.getMessage()); - this.reason = reason; - } - } - } - - public T readFully(JsonParser parser) - throws IOException, JsonReadException - { - parser.nextToken(); - T value = this.read(parser); - if (parser.getCurrentToken() != null) { - throw new AssertionError("The JSON library should ensure there's no tokens after the main value: " - + parser.getCurrentToken() + "@" + parser.getCurrentLocation()); - } - validate(value); - return value; - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/json/JsonWriter.java b/src/autosaveworld/zlibs/com/dropbox/core/json/JsonWriter.java deleted file mode 100644 index e946e8e9..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/json/JsonWriter.java +++ /dev/null @@ -1,164 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.json; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -import autosaveworld.zlibs.com.dropbox.core.util.LangUtil; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; - -public abstract class JsonWriter -{ - private static final TimeZone UTC = TimeZone.getTimeZone("UTC"); - private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; - - public static String formatDate(Date date) { - DateFormat df = new SimpleDateFormat(DATE_FORMAT); - df.setTimeZone(UTC); - return df.format(date); - } - - public abstract void write(T value, JsonGenerator g) - throws IOException; - - public void write(T value, JsonGenerator g, int level) - throws IOException - { - write(value, g); - } - - public void writeFields(T value, JsonGenerator g) - throws IOException - { - // Default does nothing. Override for struct fields. - } - - public final String writeToString(T value, boolean indent) - { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - try { - JsonGenerator g = JsonReader.jsonFactory.createGenerator(out); - if (indent) { - g = g.useDefaultPrettyPrinter(); - } - try { - write(value, g); - } - finally { - g.flush(); - } - return new String(out.toByteArray(), "UTF-8"); - - } - catch (IOException ex) { - // We don't want to see exceptions. - throw LangUtil.mkAssert("Impossible", ex); - } - } - - public final String writeToString(T value) - { - return writeToString(value, true); - } - - public final void writeToStream(T value, OutputStream out, boolean indent) - throws IOException - { - JsonGenerator g = JsonReader.jsonFactory.createGenerator(out); - if (indent) { - g = g.useDefaultPrettyPrinter(); - } - try { - write(value, g); - } - finally { - g.flush(); - } - } - - public final void writeToStream(T value, OutputStream out) - throws IOException - { - writeToStream(value, out, true); - } - - public final void writeToFile(T value, File file, boolean indent) - throws IOException - { - FileOutputStream fout = new FileOutputStream(file); - try { - writeToStream(value, fout, indent); - } - finally { - fout.close(); - } - } - - public final void writeToFile(T value, File file) - throws IOException - { - writeToFile(value, file, true); - } - - public final void writeToFile(T value, String fileName, boolean indent) - throws IOException - { - writeToFile(value, new File(fileName), indent); - } - - public final void writeToFile(T value, String fileName) - throws IOException - { - writeToFile(value, fileName, true); - } - - public final void writeDateIso(java.util.Date date, JsonGenerator g) - throws IOException - { - g.writeString(formatDate(date)); - } - - static private final String weekdays[] = {null, "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; - static private final String months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", null}; - - public final void writeDate(java.util.Date date, JsonGenerator g) - throws IOException - { - GregorianCalendar c = new GregorianCalendar(JsonDateReader.UTC); - c.setTime(date); - - String year = Integer.toString(c.get(Calendar.YEAR)); - String month = months[c.get(Calendar.MONTH)]; - String day = zeroPad(Integer.toString(c.get(Calendar.DAY_OF_MONTH)), 2); - String hour = zeroPad(Integer.toString(c.get(Calendar.HOUR_OF_DAY)), 2); - String minute = zeroPad(Integer.toString(c.get(Calendar.MINUTE)), 2); - String second = zeroPad(Integer.toString(c.get(Calendar.SECOND)), 2); - String weekday = weekdays[c.get(Calendar.DAY_OF_WEEK)]; - - StringBuilder buf = new StringBuilder(); - - buf.append(weekday).append(", "); - buf.append(day).append(" ").append(month).append(" ").append(year).append(" "); - buf.append(hour).append(":").append(minute).append(":").append(second).append(" +0000"); - - g.writeString(buf.toString()); - } - - private static String zeroPad(String v, int desiredLength) - { - while (v.length() < desiredLength) { - v = "0" + v; - } - return v; - } - - // TODO: Convert JsonGenerationExceptions to RuntimeExceptions. -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/stone/CompositeSerializer.java b/src/autosaveworld/zlibs/com/dropbox/core/stone/CompositeSerializer.java deleted file mode 100644 index 3241105d..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/stone/CompositeSerializer.java +++ /dev/null @@ -1,35 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.stone; - -import java.io.IOException; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -public abstract class CompositeSerializer extends StoneSerializer { - protected static final String TAG_FIELD = ".tag"; - - protected static boolean hasTag(JsonParser p) throws IOException, JsonParseException { - return p.getCurrentToken() == JsonToken.FIELD_NAME && TAG_FIELD.equals(p.getCurrentName()); - } - - protected static String readTag(JsonParser p) throws IOException, JsonParseException { - if (!hasTag(p)) { - return null; - } - p.nextToken(); - String tag = getStringValue(p); - p.nextToken(); - - return tag; - } - - protected void writeTag(String tag, JsonGenerator g) throws IOException, JsonGenerationException { - if (tag != null) { - g.writeStringField(TAG_FIELD, tag); - } - } -} - diff --git a/src/autosaveworld/zlibs/com/dropbox/core/stone/StoneSerializer.java b/src/autosaveworld/zlibs/com/dropbox/core/stone/StoneSerializer.java deleted file mode 100644 index 73b6f342..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/stone/StoneSerializer.java +++ /dev/null @@ -1,141 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.stone; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.charset.Charset; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -public abstract class StoneSerializer { - private static final Charset UTF8 = Charset.forName("UTF-8"); - - public String serialize(T value) { - return serialize(value, false); - } - - public String serialize(T value, boolean pretty) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - try { - serialize(value, out, pretty); - } catch (JsonGenerationException ex) { - throw new IllegalStateException("Impossible JSON exception", ex); - } catch (IOException ex) { - throw new IllegalStateException("Impossible I/O exception", ex); - } - return new String(out.toByteArray(), UTF8); - } - - public void serialize(T value, OutputStream out) throws IOException { - serialize(value, out, false); - } - - public void serialize(T value, OutputStream out, boolean pretty) throws IOException { - JsonGenerator g = Util.JSON.createGenerator(out); - if (pretty) { - g.useDefaultPrettyPrinter(); - } - try { - serialize(value, g); - } catch (JsonGenerationException ex) { - throw new IllegalStateException("Impossible JSON generation exception", ex); - } - g.flush(); - } - - public T deserialize(String json) throws JsonParseException { - try { - JsonParser p = Util.JSON.createParser(json); - p.nextToken(); - return deserialize(p); - } catch (JsonParseException ex) { - throw ex; - } catch (IOException ex) { - throw new IllegalStateException("Impossible I/O exception", ex); - } - } - - public T deserialize(InputStream json) throws IOException, JsonParseException { - JsonParser p = Util.JSON.createParser(json); - p.nextToken(); - return deserialize(p); - } - - public abstract void serialize(T value, JsonGenerator g) throws IOException, JsonGenerationException; - public abstract T deserialize(JsonParser p) throws IOException, JsonParseException; - - protected static String getStringValue(JsonParser p) throws IOException, JsonParseException { - if (p.getCurrentToken() != JsonToken.VALUE_STRING) { - throw new JsonParseException(p, "expected string value, but was " + p.getCurrentToken()); - } - return p.getText(); - } - - protected static void expectField(String name, JsonParser p) throws IOException, JsonParseException { - if (p.getCurrentToken() != JsonToken.FIELD_NAME) { - throw new JsonParseException(p, "expected field name, but was: " + p.getCurrentToken()); - } - if (!name.equals(p.getCurrentName())) { - throw new JsonParseException(p, "expected field '" + name + "', but was: '" + p.getCurrentName() + "'"); - } - p.nextToken(); - } - - protected static void expectStartObject(JsonParser p) throws IOException, JsonParseException { - if (p.getCurrentToken() != JsonToken.START_OBJECT) { - throw new JsonParseException(p, "expected object value."); - } - p.nextToken(); - } - - protected static void expectEndObject(JsonParser p) throws IOException, JsonParseException { - if (p.getCurrentToken() != JsonToken.END_OBJECT) { - throw new JsonParseException(p, "expected end of object value."); - } - p.nextToken(); - } - - protected static void expectStartArray(JsonParser p) throws IOException, JsonParseException { - if (p.getCurrentToken() != JsonToken.START_ARRAY) { - throw new JsonParseException(p, "expected array value."); - } - p.nextToken(); - } - - protected static void expectEndArray(JsonParser p) throws IOException, JsonParseException { - if (p.getCurrentToken() != JsonToken.END_ARRAY) { - throw new JsonParseException(p, "expected end of array value."); - } - p.nextToken(); - } - - protected static void skipValue(JsonParser p) throws IOException, JsonParseException { - if (p.getCurrentToken().isStructStart()) { - p.skipChildren(); // will leave parser at end token (e.g. '}' or ']') - p.nextToken(); - } else if (p.getCurrentToken().isScalarValue()) { - p.nextToken(); - } else { - throw new JsonParseException(p, "Can't skip JSON value token: " + p.getCurrentToken()); - } - } - - protected static void skipFields(JsonParser p) throws IOException, JsonParseException { - while (p.getCurrentToken() != null && !p.getCurrentToken().isStructEnd()) { - if (p.getCurrentToken().isStructStart()) { - p.skipChildren(); - } else if (p.getCurrentToken() == JsonToken.FIELD_NAME) { - p.nextToken(); - } else if (p.getCurrentToken().isScalarValue()) { - p.nextToken(); - } else { - throw new JsonParseException(p, "Can't skip token: " + p.getCurrentToken()); - } - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/stone/StoneSerializers.java b/src/autosaveworld/zlibs/com/dropbox/core/stone/StoneSerializers.java deleted file mode 100644 index 8c2fb976..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/stone/StoneSerializers.java +++ /dev/null @@ -1,272 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.stone; - -import java.io.IOException; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -public final class StoneSerializers { - - public static StoneSerializer uInt64() { - return LongSerializer.INSTANCE; - } - - public static StoneSerializer int64() { - return LongSerializer.INSTANCE; - } - - public static StoneSerializer uInt32() { - return LongSerializer.INSTANCE; - } - - public static StoneSerializer int32() { - return IntSerializer.INSTANCE; - } - - public static StoneSerializer float64() { - return DoubleSerializer.INSTANCE; - } - - public static StoneSerializer float32() { - return FloatSerializer.INSTANCE; - } - - public static StoneSerializer boolean_() { - return BooleanSerializer.INSTANCE; - } - - public static StoneSerializer binary() { - return ByteArraySerializer.INSTANCE; - } - - public static StoneSerializer string() { - return StringSerializer.INSTANCE; - } - - public static StoneSerializer timestamp() { - return DateSerializer.INSTANCE; - } - - public static StoneSerializer void_() { - return VoidSerializer.INSTANCE; - } - - public static StoneSerializer nullable(StoneSerializer underlying) { - return new NullableSerializer(underlying); - } - - public static StoneSerializer> list(StoneSerializer underlying) { - return new ListSerializer(underlying); - } - - - private static final class LongSerializer extends StoneSerializer { - public static final LongSerializer INSTANCE = new LongSerializer(); - - @Override - public void serialize(Long value, JsonGenerator g) throws IOException, JsonGenerationException { - g.writeNumber(value); - } - - @Override - public Long deserialize(JsonParser p) throws IOException, JsonParseException { - Long value = p.getLongValue(); - p.nextToken(); - return value; - } - } - - private static final class IntSerializer extends StoneSerializer { - public static final IntSerializer INSTANCE = new IntSerializer(); - - @Override - public void serialize(Integer value, JsonGenerator g) throws IOException, JsonGenerationException { - g.writeNumber(value); - } - - @Override - public Integer deserialize(JsonParser p) throws IOException, JsonParseException { - Integer value = p.getIntValue(); - p.nextToken(); - return value; - } - } - - private static final class DoubleSerializer extends StoneSerializer { - public static final DoubleSerializer INSTANCE = new DoubleSerializer(); - - @Override - public void serialize(Double value, JsonGenerator g) throws IOException, JsonGenerationException { - g.writeNumber(value); - } - - @Override - public Double deserialize(JsonParser p) throws IOException, JsonParseException { - Double value = p.getDoubleValue(); - p.nextToken(); - return value; - } - } - - private static final class FloatSerializer extends StoneSerializer { - public static final FloatSerializer INSTANCE = new FloatSerializer(); - - @Override - public void serialize(Float value, JsonGenerator g) throws IOException, JsonGenerationException { - g.writeNumber(value); - } - - @Override - public Float deserialize(JsonParser p) throws IOException, JsonParseException { - Float value = p.getFloatValue(); - p.nextToken(); - return value; - } - } - - private static final class BooleanSerializer extends StoneSerializer { - public static final BooleanSerializer INSTANCE = new BooleanSerializer(); - - @Override - public void serialize(Boolean value, JsonGenerator g) throws IOException, JsonGenerationException { - g.writeBoolean(value); - } - - @Override - public Boolean deserialize(JsonParser p) throws IOException, JsonParseException { - Boolean value = p.getBooleanValue(); - p.nextToken(); - return value; - } - } - - private static final class ByteArraySerializer extends StoneSerializer { - public static final ByteArraySerializer INSTANCE = new ByteArraySerializer(); - - @Override - public void serialize(byte [] value, JsonGenerator g) throws IOException, JsonGenerationException { - g.writeBinary(value); - } - - @Override - public byte [] deserialize(JsonParser p) throws IOException, JsonParseException { - byte [] value = p.getBinaryValue(); - p.nextToken(); - return value; - } - } - - private static final class StringSerializer extends StoneSerializer { - public static final StringSerializer INSTANCE = new StringSerializer(); - - @Override - public void serialize(String value, JsonGenerator g) throws IOException, JsonGenerationException { - g.writeString(value); - } - - @Override - public String deserialize(JsonParser p) throws IOException, JsonParseException { - String value = getStringValue(p); - p.nextToken(); - return value; - } - } - - private static final class DateSerializer extends StoneSerializer { - public static final DateSerializer INSTANCE = new DateSerializer(); - - @Override - public void serialize(Date value, JsonGenerator g) throws IOException, JsonGenerationException { - g.writeString(Util.formatTimestamp(value)); - } - - @Override - public Date deserialize(JsonParser p) throws IOException, JsonParseException { - String text = getStringValue(p); - p.nextToken(); - try { - return Util.parseTimestamp(text); - } catch (ParseException ex) { - throw new JsonParseException(p, "Malformed timestamp: '" + text + "'", ex); - } - } - } - - private static final class VoidSerializer extends StoneSerializer { - public static final VoidSerializer INSTANCE = new VoidSerializer(); - - @Override - public void serialize(Void value, JsonGenerator g) throws IOException, JsonGenerationException { - g.writeNull(); - } - - @Override - public Void deserialize(JsonParser p) throws IOException, JsonParseException { - skipValue(p); - return null; - } - } - - private static final class NullableSerializer extends StoneSerializer { - private final StoneSerializer underlying; - - public NullableSerializer(StoneSerializer underlying) { - this.underlying = underlying; - } - - @Override - public void serialize(T value, JsonGenerator g) throws IOException, JsonGenerationException { - if (value == null) { - g.writeNull(); - } else { - underlying.serialize(value, g); - } - } - - @Override - public T deserialize(JsonParser p) throws IOException, JsonParseException { - if (p.getCurrentToken() == JsonToken.VALUE_NULL) { - p.nextToken(); - return null; - } else { - return underlying.deserialize(p); - } - } - } - - private static final class ListSerializer extends StoneSerializer> { - private final StoneSerializer underlying; - - public ListSerializer(StoneSerializer underlying) { - this.underlying = underlying; - } - - @Override - public void serialize(List value, JsonGenerator g) throws IOException, JsonGenerationException { - g.writeStartArray(value.size()); - for (T elem : value) { - underlying.serialize(elem, g); - } - g.writeEndArray(); - } - - @Override - public List deserialize(JsonParser p) throws IOException, JsonParseException { - expectStartArray(p); - List list = new ArrayList(); - while (p.getCurrentToken() != JsonToken.END_ARRAY) { - T elem = underlying.deserialize(p); - list.add(elem); - } - expectEndArray(p); - return list; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/stone/StructSerializer.java b/src/autosaveworld/zlibs/com/dropbox/core/stone/StructSerializer.java deleted file mode 100644 index 84c7ca32..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/stone/StructSerializer.java +++ /dev/null @@ -1,25 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.stone; - -import java.io.IOException; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; - -public abstract class StructSerializer extends CompositeSerializer { - - @Override - public void serialize(T value, JsonGenerator g) throws IOException, JsonGenerationException { - serialize(value, g, false); - } - - public abstract void serialize(T value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException; - - @Override - public T deserialize(JsonParser p) throws IOException, JsonParseException { - return deserialize(p, false); - } - - public abstract T deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException; -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/stone/UnionSerializer.java b/src/autosaveworld/zlibs/com/dropbox/core/stone/UnionSerializer.java deleted file mode 100644 index 40adfcd6..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/stone/UnionSerializer.java +++ /dev/null @@ -1,3 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.stone; - -public abstract class UnionSerializer extends CompositeSerializer {} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/stone/Util.java b/src/autosaveworld/zlibs/com/dropbox/core/stone/Util.java deleted file mode 100644 index 889c21b4..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/stone/Util.java +++ /dev/null @@ -1,42 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.stone; - -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonFactory; - -final class Util { - public static final JsonFactory JSON = new JsonFactory(); - - private static final TimeZone UTC = TimeZone.getTimeZone("UTC"); - private static final String DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; - private static final String DATE_FORMAT = "yyyy-MM-dd"; - private static final int LONG_FORMAT_LENGTH = DATE_TIME_FORMAT.replace("'", "").length(); - private static final int SHORT_FORMAT_LENGTH = DATE_FORMAT.replace("'", "").length(); - - public static String formatTimestamp(Date timestamp) { - DateFormat format = new SimpleDateFormat(DATE_TIME_FORMAT); - format.setCalendar(new GregorianCalendar(UTC)); - return format.format(timestamp); - } - - public static Date parseTimestamp(String timestamp) throws ParseException { - int length = timestamp.length(); - - DateFormat format = null; - if (length == LONG_FORMAT_LENGTH) { - format = new SimpleDateFormat(DATE_TIME_FORMAT); - } else if (length == SHORT_FORMAT_LENGTH) { - format = new SimpleDateFormat(DATE_FORMAT); - } else { - throw new ParseException("timestamp has unexpected format: '" + timestamp + "'", 0); - } - - format.setCalendar(new GregorianCalendar(UTC)); - return format.parse(timestamp); - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/util/Collector.java b/src/autosaveworld/zlibs/com/dropbox/core/util/Collector.java deleted file mode 100644 index 7712eea2..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/util/Collector.java +++ /dev/null @@ -1,57 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.util; - -import java.util.ArrayList; - -/*>>> import checkers.nullness.quals.Nullable; */ - -public abstract class Collector -{ - public abstract void add(E element); - public abstract L finish(); - - public static final class ArrayListCollector extends Collector> - { - private /*@Nullable*/ArrayList list = new ArrayList(); - - public void add(E element) - { - if (list == null) throw new IllegalStateException("already called finish()"); - this.list.add(element); - } - - public ArrayList finish() - { - ArrayList list = this.list; - if (list == null) throw new IllegalStateException("already called finish()"); - this.list = null; - return list; - } - } - - public static final class NullSkipper extends Collector - { - private final Collector underlying; - - public NullSkipper(Collector underlying) - { - this.underlying = underlying; - } - - public static Collector mk(Collector underlying) - { - return new NullSkipper(underlying); - } - - public void add(/*@Nullable*/E element) - { - if (element != null) { - underlying.add(element); - } - } - - public L finish() - { - return underlying.finish(); - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/util/CountingOutputStream.java b/src/autosaveworld/zlibs/com/dropbox/core/util/CountingOutputStream.java deleted file mode 100644 index c5721349..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/util/CountingOutputStream.java +++ /dev/null @@ -1,53 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.util; - -import java.io.IOException; -import java.io.OutputStream; - -public class CountingOutputStream extends OutputStream -{ - private final OutputStream out; - private long bytesWritten = 0; - - public CountingOutputStream(OutputStream out) - { - this.out = out; - } - - public long getBytesWritten() - { - return bytesWritten; - } - - @Override - public void write(int b) throws IOException - { - bytesWritten++; - out.write(b); - } - - @Override - public void write(byte[] b) throws IOException - { - bytesWritten += b.length; - out.write(b); - } - - @Override - public void write(byte[] b, int off, int len) throws IOException - { - bytesWritten += len; - out.write(b, off, len); - } - - @Override - public void flush() throws IOException - { - out.flush(); - } - - @Override - public void close() throws IOException - { - throw new UnsupportedOperationException("You aren't allowed to call close() on this object."); - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/util/DumpWriter.java b/src/autosaveworld/zlibs/com/dropbox/core/util/DumpWriter.java deleted file mode 100644 index ba15362d..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/util/DumpWriter.java +++ /dev/null @@ -1,284 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.util; - -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; - -import autosaveworld.zlibs.com.dropbox.core.json.JsonDateReader; - -/*>>> import checkers.nullness.quals.Nullable; */ - -public abstract class DumpWriter -{ - public abstract DumpWriter recordStart(/*@Nullable*/String name); - public abstract DumpWriter recordEnd(); - public abstract DumpWriter f(String name); // Write a field name. You should write a value after. - public abstract DumpWriter listStart(); - public abstract DumpWriter listEnd(); - public abstract DumpWriter verbatim(String s); - - public static final class Multiline extends DumpWriter - { - private final StringBuilder buf; - private final int indentAmount; - private int currentIndent; - - public Multiline(StringBuilder buf, int indentAmount, int currentIndent, boolean nl) - { - if (buf == null) throw new IllegalArgumentException("'buf' must not be null"); - if (indentAmount < 0) throw new IllegalArgumentException("'indentAmount' must be non-negative"); - if (currentIndent < 0) throw new IllegalArgumentException("'currentIndent' must be non-negative"); - this.buf = buf; - this.indentAmount = indentAmount; - this.currentIndent = currentIndent; - this.nl = nl; - } - - public Multiline(StringBuilder buf, int indentAmount, boolean nl) - { - this(buf, indentAmount, 0, nl); - } - - boolean nl = true; - - private void prefix() - { - if (nl) { - int l = currentIndent; - for (int i = 0; i < l; i++) { - buf.append(' '); - } - } - } - - private void indentMore() - { - currentIndent += indentAmount; - } - - private void indentLess() - { - if (indentAmount > currentIndent) throw new IllegalStateException("indent went negative"); - currentIndent -= indentAmount; - } - - @Override - public DumpWriter recordStart(/*@Nullable*/String name) - { - prefix(); - if (name != null) { - buf.append(name).append(" "); - } - buf.append("{\n"); - nl = true; - indentMore(); - return this; - } - - @Override - public DumpWriter recordEnd() - { - if (!nl) throw new AssertionError("called recordEnd() in a bad state"); - indentLess(); - prefix(); - buf.append("}\n"); - nl = true; - return this; - } - - @Override - public DumpWriter f(String name) - { - if (!nl) throw new AssertionError("called fieldStart() in a bad state"); - prefix(); - buf.append(name).append(" = "); - nl = false; - return this; - } - - @Override - public DumpWriter listStart() - { - prefix(); - buf.append("[\n"); - nl = true; - indentMore(); - return this; - } - - @Override - public DumpWriter listEnd() - { - if (!nl) throw new AssertionError("called listEnd() in a bad state"); - indentLess(); - prefix(); - buf.append("]\n"); - nl = true; - return this; - } - - @Override - public DumpWriter verbatim(String s) - { - prefix(); - buf.append(s); - buf.append('\n'); - nl = true; - return this; - } - } - - public static final class Plain extends DumpWriter - { - private StringBuilder buf; - - public Plain(StringBuilder buf) - { - this.buf = buf; - } - - private boolean needSep = false; - - private void sep() - { - if (needSep) { - buf.append(", "); - } else { - needSep = true; - } - } - - @Override - public DumpWriter recordStart(/*@Nullable*/String name) - { - if (name != null) { - buf.append(name); - } - buf.append("("); - needSep = false; - return this; - } - - @Override - public DumpWriter recordEnd() - { - buf.append(")"); - needSep = true; - return this; - } - - @Override - public DumpWriter f(String name) - { - sep(); - buf.append(name).append('='); - needSep = false; - return this; - } - - @Override - public DumpWriter listStart() - { - sep(); - buf.append("["); - needSep = false; - return this; - } - - @Override - public DumpWriter listEnd() - { - buf.append("]"); - needSep = true; - return this; - } - - @Override - public DumpWriter verbatim(String s) - { - sep(); - buf.append(s); - return this; - } - } - - public DumpWriter fieldVerbatim(String name, String s) - { - return f(name).verbatim(s); - } - - public DumpWriter v(/*@Nullable*/Iterable list) - { - if (list == null) { - verbatim("null"); - } else { - listStart(); - for (Dumpable d : list) { - v(d); - } - listEnd(); - } - return this; - } - - public DumpWriter v(/*@Nullable*/String v) - { - if (v == null) { - verbatim("null"); - } else { - verbatim(StringUtil.jq(v)); - } - return this; - } - - public DumpWriter v(int v) { return verbatim(Integer.toString(v)); } - public DumpWriter v(long v) { return verbatim(Long.toString(v)); } - public DumpWriter v(boolean v) { return verbatim(Boolean.toString(v)); } - public DumpWriter v(float v) { return verbatim(Float.toString(v)); } - public DumpWriter v(double v) { return verbatim(Double.toString(v)); } - public DumpWriter v(/*@Nullable*/Date v) { return verbatim(toStringDate(v)); } - public DumpWriter v(/*@Nullable*/Long v) { return verbatim(v == null ? "null" : Long.toString(v)); } - - public DumpWriter v(/*@Nullable*/Dumpable v) - { - if (v == null) { - verbatim("null"); - } - else { - recordStart(v.getTypeName()); - v.dumpFields(this); - recordEnd(); - } - return this; - } - - public static String toStringDate(/*@Nullable*/Date date) - { - if (date == null) { - return "null"; - } else { - StringBuilder buf = new StringBuilder(); - GregorianCalendar c = new GregorianCalendar(JsonDateReader.UTC); - c.setTime(date); - String year = Integer.toString(c.get(Calendar.YEAR)); - String month = zeroPad(Integer.toString(c.get(Calendar.MONTH) + 1), 2); - String day = zeroPad(Integer.toString(c.get(Calendar.DAY_OF_MONTH)), 2); - String hour = zeroPad(Integer.toString(c.get(Calendar.HOUR_OF_DAY)), 2); - String minute = zeroPad(Integer.toString(c.get(Calendar.MINUTE)), 2); - String second = zeroPad(Integer.toString(c.get(Calendar.SECOND)), 2); - buf.append('"'); - buf.append(year).append("/").append(month).append("/").append(day).append(" "); - buf.append(hour).append(":").append(minute).append(":").append(second).append(" UTC"); - buf.append('"'); - return buf.toString(); - } - } - - private static String zeroPad(String v, int desiredLength) - { - while (v.length() < desiredLength) { - v = "0" + v; - } - return v; - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/util/Dumpable.java b/src/autosaveworld/zlibs/com/dropbox/core/util/Dumpable.java deleted file mode 100644 index c3a82a41..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/util/Dumpable.java +++ /dev/null @@ -1,62 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.util; - -/*>>> import checkers.nullness.quals.Nullable; */ - -/** - * A common superclass for pure-data classes. Contains a function to dump - * the data (for debugging purposes). - */ -public abstract class Dumpable -{ - public final String toString() - { - StringBuilder buf = new StringBuilder(); - toString(buf); - return buf.toString(); - } - - public final void toString(StringBuilder buf) - { - new DumpWriter.Plain(buf).v(this); - } - - /** - * Like {@link #toString} except returns a multi-line string. Every line will - * always end in a {@code "\n"}. - * - *

- * Don't depend on the format of the output to stay the same. Newer versions of the SDK - * may change the format. - *

- */ - public final String toStringMultiline() - { - StringBuilder buf = new StringBuilder(); - toStringMultiline(buf, 0, true); - return buf.toString(); - } - - /** - * Like {@link #toStringMultiline()}, but appends the result to {@code buf} - * instead of returning a string. - * - *

- * Don't depend on the format of the output to stay the same. Newer versions of the SDK - * may change the format. - *

- * - * @param currentIndent - * The number of spaces to use as the initial indentation level. - * - * @param nl - * Whether you will start displaying this value on its own line (and will need indentation - * on the first line) or not. - */ - public final void toStringMultiline(StringBuilder buf, int currentIndent, boolean nl) - { - new DumpWriter.Multiline(buf, 2, currentIndent, nl).v(this); - } - - protected /*@Nullable*/String getTypeName() { return null; } - protected abstract void dumpFields(DumpWriter out); -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/util/IOUtil.java b/src/autosaveworld/zlibs/com/dropbox/core/util/IOUtil.java deleted file mode 100644 index 64251e9e..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/util/IOUtil.java +++ /dev/null @@ -1,293 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.util; - -import java.io.ByteArrayOutputStream; -import java.io.Closeable; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.io.Writer; -import java.nio.charset.CharacterCodingException; - -public class IOUtil { - public static final int DEFAULT_COPY_BUFFER_SIZE = 16 << 10; // 16 KiB - - public static Reader utf8Reader(InputStream in) { - // NOTE: Just passing StringUtil.UTF8 instead of StringUtil.UTF8.newDecoder() would be wrong. - // The former will cause the InputStreamReader to ignore UTF-8 errors in the input. - return new InputStreamReader(in, StringUtil.UTF8.newDecoder()); - } - - public static Writer utf8Writer(OutputStream out) { - return new OutputStreamWriter(out, StringUtil.UTF8.newEncoder()); - } - - public static String toUtf8String(InputStream in) throws ReadException, CharacterCodingException { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - try { - copyStreamToStream(in, out); - } catch (WriteException ex) { - throw new RuntimeException("impossible", ex); - } - return StringUtil.utf8ToString(out.toByteArray()); - } - - public static void copyStreamToStream(InputStream in, OutputStream out) throws ReadException, WriteException { - copyStreamToStream(in, out, DEFAULT_COPY_BUFFER_SIZE); - } - - public static void copyStreamToStream(InputStream in, OutputStream out, byte[] copyBuffer) - throws ReadException, WriteException { - while (true) { - int count; - try { - count = in.read(copyBuffer); - } catch (IOException ex) { - throw new ReadException(ex); - } - - if (count == -1) break; - - try { - out.write(copyBuffer, 0, count); - } catch (IOException ex) { - throw new WriteException(ex); - } - } - } - - public static void copyStreamToStream(InputStream in, OutputStream out, int copyBufferSize) - throws ReadException, WriteException { - copyStreamToStream(in, out, new byte[copyBufferSize]); - } - - public static byte[] slurp(InputStream in, int byteLimit) throws IOException { - return slurp(in, byteLimit, new byte[DEFAULT_COPY_BUFFER_SIZE]); - } - - public static byte[] slurp(InputStream in, int byteLimit, byte[] slurpBuffer) throws IOException { - if (byteLimit < 0) throw new RuntimeException("'byteLimit' must be non-negative: " + byteLimit); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - copyStreamToStream(in, baos, slurpBuffer); - return baos.toByteArray(); - } - - public void copyFileToStream(File fin, OutputStream out) throws ReadException, WriteException { - copyFileToStream(fin, out, DEFAULT_COPY_BUFFER_SIZE); - } - - public void copyFileToStream(File fin, OutputStream out, int copyBufferSize) throws ReadException, WriteException { - FileInputStream in; - try { - in = new FileInputStream(fin); - } catch (IOException ex) { - throw new ReadException(ex); - } - - try { - copyStreamToStream(in, out, copyBufferSize); - } finally { - closeInput(in); - } - } - - public void copyStreamToFile(InputStream in, File fout) throws ReadException, WriteException { - copyStreamToFile(in, fout, DEFAULT_COPY_BUFFER_SIZE); - } - - public void copyStreamToFile(InputStream in, File fout, int copyBufferSize) throws ReadException, WriteException { - FileOutputStream out; - try { - out = new FileOutputStream(fout); - } catch (IOException ex) { - throw new WriteException(ex); - } - - try { - copyStreamToStream(in, out, copyBufferSize); - } finally { - try { out.close(); } catch (IOException ex) { - //noinspection ThrowFromFinallyBlock - throw new WriteException(ex); - } - } - } - - /** - * Closes the given input stream and ignores the IOException. - */ - public static void closeInput(InputStream in) { - try { - in.close(); - } catch (IOException ex) { - // Ignore. We're done reading from it so we don't care if there are input errors. - } - } - - /** - * Closes the given Reader and ignores the IOException. - */ - public static void closeInput(Reader in) { - try { - in.close(); - } catch (IOException ex) { - // Ignore. We're done reading from it so we don't care if there are input errors. - } - } - - public static void closeQuietly(Closeable obj) { - if (obj != null) { - try { - obj.close(); - } catch (IOException ex) { - // Ignore - } - } - } - - public static InputStream limit(InputStream in, long limit) { - return new LimitInputStream(in, limit); - } - - public static abstract class WrappedException extends IOException { - private static final long serialVersionUID = 0; - - public WrappedException(String message, IOException underlying) { - super(message + ": " + underlying.getMessage(), underlying); - } - - public WrappedException(IOException underlying) { - super(underlying); - } - - @Override - public IOException getCause() { - return (IOException) super.getCause(); - } - - @Override - public String getMessage() { - String m = super.getCause().getMessage(); - if (m == null) return ""; - else return m; - } - } - - public static final class ReadException extends WrappedException { - private static final long serialVersionUID = 0; - - public ReadException(String message, IOException underlying) { - super(message, underlying); - } - - public ReadException(IOException underlying) { - super(underlying); - } - } - - public static final class WriteException extends WrappedException { - private static final long serialVersionUID = 0; - - public WriteException(String message, IOException underlying) { - super(message, underlying); - } - - public WriteException(IOException underlying) { - super(underlying); - } - } - - public static final InputStream EmptyInputStream = new InputStream() { - public int read() { return -1; } - public int read(byte[] data) { return -1; } - public int read(byte[] data, int off, int len) { return -1; } - }; - - public static final OutputStream BlackHoleOutputStream = new OutputStream() { - public void write(int b) {} - public void write(byte[] data) {} - public void write(byte[] data, int off, int len) {} - }; - - /** - * {@link InputStream} that limits the amount of bytes read from its underlying {@code - * InputStream}. - */ - private static final class LimitInputStream extends FilterInputStream { - private long left; - - public LimitInputStream(InputStream in, long limit) { - super(in); - - if (in == null) { - throw new NullPointerException("in"); - } - - if (limit < 0) { - throw new IllegalArgumentException("limit must be non-negative"); - } - - this.left = limit; - } - - @Override - public int available() throws IOException { - return (int) Math.min(in.available(), left); - } - - @Override - public synchronized void reset() throws IOException { - throw new IOException("mark not supported"); - } - - @Override - public boolean markSupported() { - return false; - } - - @Override - public int read() throws IOException { - if (left == 0) { - return -1; - } - - int read = in.read(); - if (read != -1) { - --left; - } - - return read; - } - - @Override - public int read(byte [] b, int off, int len) throws IOException { - if (left == 0) { - return -1; - } - - len = (int) Math.min(len, left); - int read = in.read(b, off, len); - - if (read != -1) { - left -= read; - } - - return read; - } - - @Override - public long skip(long n) throws IOException { - n = Math.min(n, left); - long skipped = in.skip(n); - left -= skipped; - return skipped; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/util/LangUtil.java b/src/autosaveworld/zlibs/com/dropbox/core/util/LangUtil.java deleted file mode 100644 index 3fd81fdd..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/util/LangUtil.java +++ /dev/null @@ -1,78 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.util; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.List; - -/*>>> import checkers.nullness.quals.Nullable; */ -/*>>> import checkers.nullness.quals.NonNull; */ - -public class LangUtil -{ - public static RuntimeException mkAssert(String messagePrefix, Throwable cause) - { - RuntimeException ae = new RuntimeException(messagePrefix + ": " + cause.getMessage()); - ae.initCause(cause); - return ae; - // XXX: Using AssertionError doesn't work for some reason (maybe Android bug). Trying - // to call initCause results in "cause already initialized" exception. Switching to - // RuntimeException worked. - } - - public static AssertionError badType(Object a) - { - String msg; - if (a == null) { - msg = "bad type: null"; - } else { - msg = "bad type: " + a.getClass().getName(); - } - return new AssertionError(msg); - } - - public static T[] arrayConcat(T[] a, T[] b) - { - if (a == null) throw new IllegalArgumentException("'a' can't be null"); - if (b == null) throw new IllegalArgumentException("'b' can't be null"); - /*@Nullable*/T[] rn = Arrays.copyOf(a, a.length + b.length); - System.arraycopy(b, 0, rn, a.length, b.length); - T[] r = rn; - return r; - } - - public static boolean nullableEquals(/*@Nullable*/T a, /*@Nullable*/T b) - { - if (a == null) return (b == null); - if (b == null) return false; - return a.equals(b); - } - - public static int nullableHashCode(/*@Nullable*/Object o) - { - if (o == null) return 0; - return o.hashCode() + 1; - } - - public static Date truncateMillis(/*@Nullable*/Date date) { - if (date != null) { - long time = date.getTime(); - return new Date(time - (time % 1000L)); - } else { - return date; - } - } - - public static List truncateMillis(/*@Nullable*/List dates) { - if (dates != null) { - List truncated = new ArrayList(dates.size()); - for (Date date : dates) { - long time = date.getTime(); - truncated.add(new Date(time - (time % 1000L))); - } - return truncated; - } else { - return dates; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/util/Maybe.java b/src/autosaveworld/zlibs/com/dropbox/core/util/Maybe.java deleted file mode 100644 index cc46f1cb..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/util/Maybe.java +++ /dev/null @@ -1,75 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.util; - -public abstract class Maybe -{ - private Maybe() {} - - public abstract boolean isNothing(); - public abstract boolean isJust(); - public abstract T getJust(); - public abstract T get(T def); - public abstract String toString(); - public abstract int hashCode(); - public abstract boolean equals(Maybe other); - - public static Maybe Just(T value) - { - return new Just(value); - } - - private static final class Just extends Maybe - { - private final T value; - private Just(T value) - { - this.value = value; - } - - public boolean isNothing() { return false; } - public boolean isJust() { return true; } - public T getJust() { return value; } - public T get(T def) { return value; } - public String toString() { return "Just(" + value + ")"; } - public int hashCode() { return 1 + LangUtil.nullableHashCode(value); } - - @Override - public boolean equals(Maybe other) - { - if (other instanceof Just) { - Just j = (Just) other; - return LangUtil.nullableEquals(value, j.value); - } - else if (other instanceof Nothing) { - return false; - } - else { - throw LangUtil.badType(other); - } - } - } - - @SuppressWarnings("unchecked") - public static Maybe Nothing() - { - return (Maybe) Nothing; - } - - private static final Maybe Nothing = new Nothing(); - private static final class Nothing extends Maybe - { - private Nothing() {} - - public boolean isNothing() { return true; } - public boolean isJust() { return false; } - public T getJust() { throw new IllegalStateException("can't call getJust() on a Nothing"); } - public T get(T def) { return def; } - public String toString() { return "Nothing"; } - public int hashCode() { return 0; } - - @Override - public boolean equals(Maybe other) - { - return other == this; // There's only a single Nothing instance. - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/util/StringUtil.java b/src/autosaveworld/zlibs/com/dropbox/core/util/StringUtil.java deleted file mode 100644 index 9310a1fc..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/util/StringUtil.java +++ /dev/null @@ -1,215 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.util; - -import static autosaveworld.zlibs.com.dropbox.core.util.LangUtil.mkAssert; - -import java.io.UnsupportedEncodingException; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; - -public class StringUtil -{ - public static final Charset UTF8 = Charset.forName("UTF-8"); - - private static final char[] HexDigits = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f',}; - public static char hexDigit(int i) { return HexDigits[i]; } - - public static String utf8ToString(byte[] utf8Data) - throws CharacterCodingException - { - return utf8ToString(utf8Data, 0, utf8Data.length); - } - - public static String utf8ToString(byte[] utf8Data, int offset, int length) - throws CharacterCodingException - { - // NOTE: Using the String(..., UTF8) constructor would be wrong. That method will - // ignore UTF-8 errors in the input. - CharsetDecoder decoder = UTF8.newDecoder(); - CharBuffer result = decoder.decode(ByteBuffer.wrap(utf8Data, offset, length)); - return result.toString(); - } - - public static byte[] stringToUtf8(String s) - { - try { - // Java 1.5 doesn't have the version of getBytes that takes a Charset object, so we - // just use this one and catch the exception. - return s.getBytes("UTF-8"); - } - catch (UnsupportedEncodingException ex) { - throw mkAssert("UTF-8 should always be supported", ex); - } - } - - /** - * Given a string, returns the representation of that string - * as a Java string literal. - */ - public static String javaQuotedLiteral(String value) - { - StringBuilder b = new StringBuilder(value.length() * 2); - b.append('"'); - for (int i = 0; i < value.length(); i++) { - char c = value.charAt(i); - switch (c) { - case '"': b.append("\\\""); break; - case '\\': b.append("\\\\"); break; - case '\n': b.append("\\n"); break; - case '\r': b.append("\\t"); break; - case '\t': b.append("\\r"); break; - case '\0': b.append("\\000"); break; // Inserting '\0' isn't safe if there's a digit after - default: - if (c >= 0x20 && c <= 0x7e) { - b.append(c); - } else { - int h1 = (c >> 12) & 0xf; - int h2 = (c >> 8) & 0xf; - int h3 = (c >> 4) & 0xf; - int h4 = c & 0xf; - b.append("\\u"); - b.append(hexDigit(h1)); - b.append(hexDigit(h2)); - b.append(hexDigit(h3)); - b.append(hexDigit(h4)); - } - break; - } - } - b.append('"'); - return b.toString(); - } - - /** Shorthand for {@link #javaQuotedLiteral}. */ - public static String jq(String value) { return javaQuotedLiteral(value); } - - public static String binaryToHex(byte[] data) - { - return binaryToHex(data, 0, data.length); - } - - /** - * Convert a string of binary bytes to the equivalent hexadecimal string. - * The resulting String will have two characters for every byte in the - * input. - */ - public static String binaryToHex(byte[] data, int offset, int length) - { - assert offset < data.length && offset >= 0 : offset + ", " + data.length; - int end = offset + length; - assert end <= data.length && end >= 0 : offset + ", " + length + ", " + data.length; - - char[] chars = new char[length*2]; - int j = 0; - for (int i = offset; i < end; i++) { - int b = data[i]; - chars[j++] = hexDigit(b >>> 4 & 0xF); - chars[j++] = hexDigit(b & 0xF); - } - - return new String(chars); - } - - /** - * When you're comparing two strings for equality and one of them is a value that could be - * provided by an attacker and the other is a value that the attacker shouldn't know, use - * this function to check for equality. Using regular {@code String.equals} is not - * secure. - */ - public static boolean secureStringEquals(String a, String b) - { - if (a.length() != b.length()) return false; - - // Prevent timing attacks by making sure the running time of this loop doesn't - // depend on the contents of the two strings. - int result = 0; - for (int i = 0; i < a.length(); i++) { - char ca = a.charAt(i); - char cb = b.charAt(i); - result |= (ca ^ cb); - } - return result == 0; - } - - public static final String Base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - public static final String UrlSafeBase64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; - static { - assert Base64Digits.length() == 64 : Base64Digits.length(); - assert UrlSafeBase64Digits.length() == 64 : UrlSafeBase64Digits.length(); - } - - public static String base64Encode(byte[] data) - { - return base64EncodeGeneric(Base64Digits, data); - } - - public static String urlSafeBase64Encode(byte[] data) - { - return base64EncodeGeneric(UrlSafeBase64Digits, data); - } - - public static String base64EncodeGeneric(String digits, byte[] data) - { - if (data == null) throw new IllegalArgumentException("'data' can't be null"); - if (digits == null) throw new IllegalArgumentException("'digits' can't be null"); - if (digits.length() != 64) throw new IllegalArgumentException("'digits' must be 64 characters long: " + jq(digits)); - - int numGroupsOfThreeInputBytes = (data.length + 2) / 3; - int numOutputChars = numGroupsOfThreeInputBytes * 4; - StringBuilder buf = new StringBuilder(numOutputChars); - - // Do chunks of three bytes at a time. - int i = 0; - while ((i + 3) <= data.length) { - int b1 = ((int) data[i++]) & 0xff; - int b2 = ((int) data[i++]) & 0xff; - int b3 = ((int) data[i++]) & 0xff; - - int d1 = b1 >>> 2; - int d2 = ((b1 & 0x3) << 4) | (b2 >>> 4); - int d3 = ((b2 & 0xf) << 2) | (b3 >>> 6); - int d4 = b3 & 0x3f; - - buf.append(digits.charAt(d1)); - buf.append(digits.charAt(d2)); - buf.append(digits.charAt(d3)); - buf.append(digits.charAt(d4)); - } - - // Do the leftover bytes (either 1 or 2) - int remaining = data.length - i; - if (remaining == 0) { - // All done. - } - else if (remaining == 1) { - int b1 = ((int) data[i++]) & 0xff; - - int d1 = b1 >>> 2; - int d2 = (b1 & 0x3) << 4; - - buf.append(digits.charAt(d1)); - buf.append(digits.charAt(d2)); - buf.append("=="); - } - else if (remaining == 2) { - int b1 = ((int) data[i++]) & 0xff; - int b2 = ((int) data[i++]) & 0xff; - - int d1 = b1 >>> 2; - int d2 = ((b1 & 0x3) << 4) | (b2 >>> 4); - int d3 = ((b2 & 0xf) << 2); - - buf.append(digits.charAt(d1)); - buf.append(digits.charAt(d2)); - buf.append(digits.charAt(d3)); - buf.append('='); - } - else { - throw new AssertionError("data.length: " + data.length + ", i: " + i); - } - - return buf.toString(); - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/DbxClientV2.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/DbxClientV2.java deleted file mode 100644 index 87fb78ec..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/DbxClientV2.java +++ /dev/null @@ -1,80 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.v2; - -import java.util.List; - -import autosaveworld.zlibs.com.dropbox.core.DbxHost; -import autosaveworld.zlibs.com.dropbox.core.DbxRequestConfig; -import autosaveworld.zlibs.com.dropbox.core.DbxRequestUtil; -import autosaveworld.zlibs.com.dropbox.core.http.HttpRequestor; - -/** - * Use this class to make remote calls to the Dropbox API user endpoints. User - * endpoints expose actions you can perform as a Dropbox user. You'll need an - * access token first, normally acquired by directing a Dropbox user through the - * auth flow using {@link com.dropbox.core.DbxWebAuth}. - * - *

This class has no mutable state, so it's thread safe as long as you pass - * in a thread safe {@link HttpRequestor} implementation.

- */ -public class DbxClientV2 extends DbxClientV2Base { - - /** - * Creates a client that uses the given OAuth 2 access token as - * authorization when performing requests against the default Dropbox hosts. - * - * @param requestConfig Default attributes to use for each request - * @param accessToken OAuth 2 access token (that you got from Dropbox) that - * gives your app the ability to make Dropbox API calls. Typically - * acquired through {@link com.dropbox.core.DbxWebAuth} - */ - public DbxClientV2(DbxRequestConfig requestConfig, String accessToken) { - this(requestConfig, accessToken, DbxHost.DEFAULT); - } - - /** - * Same as {@link #DbxClientV2(DbxRequestConfig, String)} except you can - * also set the hostnames of the Dropbox API servers. This is used in - * testing. You don't normally need to call this. - * - * @param requestConfig Default attributes to use for each request - * @param accessToken OAuth 2 access token (that you got from Dropbox) that - * gives your app the ability to make Dropbox API calls. Typically - * acquired through {@link com.dropbox.core.DbxWebAuth} - * @param host Dropbox hosts to send requests to (used for mocking and - * testing) - */ - public DbxClientV2(DbxRequestConfig requestConfig, String accessToken, DbxHost host) { - super(new DbxUserRawClientV2(requestConfig, accessToken, host)); - } - - /** - * For internal use only. - * - *

Used by other clients to provide functionality like DbxTeamClientV2.asMember(..) - * - * @param client Raw v2 client ot use for issuing requests - */ - DbxClientV2(DbxRawClientV2 client) { - super(client); - } - - /** - * {@link DbxRawClientV2} raw client that adds user OAuth2 auth headers to all requests. - */ - private static final class DbxUserRawClientV2 extends DbxRawClientV2 { - private final String accessToken; - - public DbxUserRawClientV2(DbxRequestConfig requestConfig, String accessToken, DbxHost host) { - super(requestConfig, host); - - if (accessToken == null) throw new NullPointerException("accessToken"); - - this.accessToken = accessToken; - } - - @Override - protected void addAuthHeaders(List headers) { - DbxRequestUtil.addAuthHeader(headers, accessToken); - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/DbxClientV2Base.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/DbxClientV2Base.java deleted file mode 100644 index 067323c2..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/DbxClientV2Base.java +++ /dev/null @@ -1,35 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated by Stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2; - -import autosaveworld.zlibs.com.dropbox.core.v2.files.DbxUserFilesRequests; - -/** - * Base class for user auth clients. - */ -public class DbxClientV2Base { - protected final DbxRawClientV2 _client; - - private final DbxUserFilesRequests files; - - /** - * For internal use only. - * - * @param _client Raw v2 client to use for issuing requests - */ - protected DbxClientV2Base(DbxRawClientV2 _client) { - this._client = _client; - this.files = new DbxUserFilesRequests(_client); - } - - /** - * Returns client for issuing requests in the {@code "files"} namespace. - * - * @return Dropbox files client - */ - public DbxUserFilesRequests files() { - return files; - } - -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/DbxPathV2.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/DbxPathV2.java deleted file mode 100644 index 02702a20..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/DbxPathV2.java +++ /dev/null @@ -1,90 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.v2; - -/*>>> import checkers.nullness.quals.Nullable; */ - -/** - * Utility functions for working with Dropbox paths. This SDK uses {@code String}s - * to represent paths. - * - *

- * Dropbox paths always start with with a slash ({@code "/"}). - * For full-Dropbox apps, the path is relative to the - * root of the user's Dropbox. For App Folder apps, - * the path is relative to the App Folder. - *

- */ -public class DbxPathV2 -{ - public static boolean isValid(String path) - { - String error = findError(path); - return (error == null); - } - - public static /*@Nullable*/String findError(String path) - { - if (path.length() == 0) return null; // Special case for "" - - if (!path.startsWith("/")) return "expecting first character to be \"/\""; - if (path.endsWith("/")) return "must not end with \"/\""; - - // TODO: More checks. - // - No trailing white space in any path component. - // - No extended unicode. - // - Even more checks. - - return null; - } - - /** - * Returns just the last component of the path. - *
    - *
  • {@code getName("")} → {@code null}
  • - *
  • {@code getName("/Photos")} → {@code "Photos"}
  • - *
  • {@code getName("/Photos/Home.jpeg")} → {@code "Home.jpeg"}
  • - *
- */ - public static String getName(String path) - { - if (path == null) throw new IllegalArgumentException("'path' can't be null"); - if (path.length() == 0) return null; - if (!path.startsWith("/")) throw new IllegalArgumentException("Not a valid path. Doesn't start with a \"/\": \"" + path + "\""); - if (path.endsWith("/")) throw new IllegalArgumentException("Not a valid path. Ends with a \"/\": \"" + path + "\""); - - int start = path.length() - 1; - while (path.charAt(start) != '/') { - start--; - } - return path.substring(start+1); - } - - public static String[] split(String path) - { - if (path == null) throw new IllegalArgumentException("'path' can't be null"); - if (path.length() == 0) return new String[0]; - if (!path.startsWith("/")) throw new IllegalArgumentException("Not a valid path. Doesn't start with a \"/\": \"" + path + "\""); - if (path.endsWith("/")) throw new IllegalArgumentException("Not a valid path. Ends with a \"/\": \"" + path + "\""); - - return path.substring(1).split("/"); - } - - /** - * Returns the parent path of the given path or {@code null} if the path - * is {@code "/"}. - *
    - *
  • {@code getParent("")} → {@code null}
  • - *
  • {@code getParent("/Photos")} → {@code "/"}
  • - *
  • {@code getParent("/Photos/Recent/Home.jpeg")} → {@code "/Photos/Recent"}
  • - *
- */ - public static /*@Nullable*/String getParent(String path) - { - if (path == null) throw new IllegalArgumentException("'path' can't be null"); - if (path.length() == 0) return null; - if (!path.startsWith("/")) throw new IllegalArgumentException("Not a valid path. Doesn't start with a \"/\": \"" + path + "\""); - if (path.endsWith("/")) throw new IllegalArgumentException("Not a valid path. Ends with a \"/\": \"" + path + "\""); - - int lastSlash = path.lastIndexOf("/"); - return path.substring(0, lastSlash); - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/DbxRawClientV2.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/DbxRawClientV2.java deleted file mode 100644 index 6e8eeb62..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/DbxRawClientV2.java +++ /dev/null @@ -1,230 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.v2; - -import static autosaveworld.zlibs.com.dropbox.core.DbxRequestUtil.addUserLocaleHeader; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -import autosaveworld.zlibs.com.dropbox.core.BadResponseException; -import autosaveworld.zlibs.com.dropbox.core.DbxException; -import autosaveworld.zlibs.com.dropbox.core.DbxHost; -import autosaveworld.zlibs.com.dropbox.core.DbxRequestConfig; -import autosaveworld.zlibs.com.dropbox.core.DbxRequestUtil; -import autosaveworld.zlibs.com.dropbox.core.DbxWrappedException; -import autosaveworld.zlibs.com.dropbox.core.NetworkIOException; -import autosaveworld.zlibs.com.dropbox.core.RetryException; -import autosaveworld.zlibs.com.dropbox.core.http.HttpRequestor; -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializer; -import autosaveworld.zlibs.com.dropbox.core.util.LangUtil; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonFactory; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonProcessingException; - -/*>>> import checkers.nullness.quals.NonNull; */ -/*>>> import checkers.nullness.quals.Nullable; */ -/*>>> import checkers.nullness.quals.MonotonicNonNull; */ -/*>>> import checkers.initialization.quals.Initialized; */ - -/** - * Use this class to make remote calls to the Dropbox API. You'll need an access token first, - * normally acquired via {@link DbxWebAuth}. - * - *

- * This class has no mutable state, so it's thread safe as long as you pass in a thread safe - * {@link HttpRequestor} implementation. - *

- */ -public abstract class DbxRawClientV2 { - public static final String USER_AGENT_ID = "OfficialDropboxJavaSDKv2"; - - private static final JsonFactory JSON = new JsonFactory(); - private static final Random RAND = new Random(); - - private final DbxRequestConfig requestConfig; - private final DbxHost host; - - /** - * @param requestConfig Configuration controlling How requests should be issued to Dropbox - * servers. - * @param host Dropbox server hostnames (primarily for internal use) - */ - protected DbxRawClientV2(DbxRequestConfig requestConfig, DbxHost host) { - if (requestConfig == null) throw new NullPointerException("requestConfig"); - if (host == null) throw new NullPointerException("host"); - - this.requestConfig = requestConfig; - this.host = host; - } - - /** - * Add the appropriate authentication headers to the request, if any. - * - * @param headers List of request headers. Add authentication headers to this list. - */ - protected abstract void addAuthHeaders(List headers); - - public ResT rpcStyle(final String host, - final String path, - final ArgT arg, - final boolean noAuth, - final StoneSerializer argSerializer, - final StoneSerializer responseSerializer, - final StoneSerializer errorSerializer) - throws DbxWrappedException, DbxException { - - final byte [] body = writeAsBytes(argSerializer, arg); - final List headers = new ArrayList(); - if (!noAuth) { - addAuthHeaders(headers); - } - if (!this.host.getNotify().equals(host)) { - // TODO(krieb): fix this ugliness - addUserLocaleHeader(headers, requestConfig); - } - - headers.add(new HttpRequestor.Header("Content-Type", "application/json; charset=utf-8")); - - return executeRetriable(requestConfig.getMaxRetries(), new RetriableExecution () { - @Override - public ResT execute() throws DbxWrappedException, DbxException { - HttpRequestor.Response response = DbxRequestUtil.startPostRaw(requestConfig, USER_AGENT_ID, host, path, body, headers); - try { - switch (response.getStatusCode()) { - case 200: - return responseSerializer.deserialize(response.getBody()); - case 409: - throw DbxWrappedException.fromResponse(errorSerializer, response); - default: - throw DbxRequestUtil.unexpectedStatus(response); - } - } catch (JsonProcessingException ex) { - String requestId = DbxRequestUtil.getRequestId(response); - throw new BadResponseException(requestId, "Bad JSON: " + ex.getMessage(), ex); - } catch (IOException ex) { - throw new NetworkIOException(ex); - } - } - }); - } - - private static byte [] writeAsBytes(StoneSerializer serializer, T arg) throws DbxException { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - try { - serializer.serialize(arg, out); - } catch (IOException ex) { - throw LangUtil.mkAssert("Impossible", ex); - } - return out.toByteArray(); - } - - private static String headerSafeJson(StoneSerializer serializer, T value) { - StringWriter out = new StringWriter(); - try { - JsonGenerator g = JSON.createGenerator(out); - // Escape 0x7F, because it's not allowed in an HTTP header. - // Escape all non-ASCII because the new HTTP spec recommends against non-ASCII in headers. - g.setHighestNonEscapedChar(0x7E); - serializer.serialize(value, g); - g.flush(); - } catch (IOException ex) { - throw LangUtil.mkAssert("Impossible", ex); - } - return out.toString(); - } - - public HttpRequestor.Uploader uploadStyle(String host, - String path, - ArgT arg, - boolean noAuth, - StoneSerializer argSerializer) - throws DbxException { - - String uri = DbxRequestUtil.buildUri(host, path); - List headers = new ArrayList(); - if (!noAuth) { - addAuthHeaders(headers); - } - addUserLocaleHeader(headers, requestConfig); - headers.add(new HttpRequestor.Header("Content-Type", "application/octet-stream")); - headers = DbxRequestUtil.addUserAgentHeader(headers, requestConfig, USER_AGENT_ID); - headers.add(new HttpRequestor.Header("Dropbox-API-Arg", headerSafeJson(argSerializer, arg))); - try { - return requestConfig.getHttpRequestor().startPost(uri, headers); - } - catch (IOException ex) { - throw new NetworkIOException(ex); - } - } - - /** - * Returns the {@code DbxRequestConfig} that was passed in to the constructor. - * - * @return configuration to use for issuing requests. - */ - public DbxRequestConfig getRequestConfig() { - return requestConfig; - } - - /** - * Returns the {@code DbxHost} that was passed in to the constructor. - * - * @return Dropbox hosts to use for requests. - */ - public DbxHost getHost() { - return host; - } - - /** - * Retries the execution at most a maximum number of times. - * - *

This method is an alternative implementation to {@code DbxRequestUtil.runAndRetry(..)} - * that does not retry 500 errors ({@link autosaveworld.zlibs.com.dropbox.core.ServerException}). To maintain - * behavior backwards compatibility in v1, we leave the old implementation in {@code - * DbxRequestUtil} unchanged. - */ - private static T executeRetriable(int maxRetries, RetriableExecution execution) throws DbxWrappedException, DbxException { - if (maxRetries == 0) { - return execution.execute(); - } - - int retries = 0; - while (true) { - try { - return execution.execute(); - } catch (RetryException ex) { - if (retries < maxRetries) { - ++retries; - sleepQuietlyWithJitter(ex.getBackoffMillis()); - } else { - throw ex; - } - } - } - } - - private static void sleepQuietlyWithJitter(long millis) { - // add a small jitter to the sleep to avoid stampeding herd problem, especially when millis - // is 0. - long jitter = RAND.nextInt(1000); - long sleepMillis = millis + jitter; - - if (sleepMillis <= 0) { - return; - } - - try { - Thread.sleep(sleepMillis); - } catch (InterruptedException ex) { - // preserve interrupt - Thread.currentThread().interrupt(); - } - } - - private interface RetriableExecution { - T execute() throws DbxWrappedException, DbxException; - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/DbxUploadStyleBuilder.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/DbxUploadStyleBuilder.java deleted file mode 100644 index 6449ef94..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/DbxUploadStyleBuilder.java +++ /dev/null @@ -1,116 +0,0 @@ -package autosaveworld.zlibs.com.dropbox.core.v2; - -import java.io.IOException; -import java.io.InputStream; - -import autosaveworld.zlibs.com.dropbox.core.DbxApiException; -import autosaveworld.zlibs.com.dropbox.core.DbxException; -import autosaveworld.zlibs.com.dropbox.core.DbxUploader; - -/** - * The common interface for all builders associated with upload style methods. After setting any - * optional request parameters, use {@link #start} or {@link #uploadAndFinish} to initiate the - * request. - * - * Example usage: - * - *


- *    // set our optional request parameters
- *    UploadUploader uploader = client.files.uploadBuilder("/test.txt")
- *        .autorename(true)
- *        .mute(true)
- *        .clientModified(new Date())
- *        .start();
- *
- *    byte [] data = // ... your data here
- *    try {
- *        // set our upload content
- *        OutputStream out = uploader.getOutputStream();
- *        out.write(data);
- *
- *        // complete request and get server response
- *        response = uploader.finish();
- *    } finally {
- *        uploader.close();
- *    }
- *
- * - * Same example using the {@link #uploadAndFinish} convenience method: - * - *

- *    FileInputStream in = new FileInputStream(file);
- *    try {
- *        // set our optional request parameters
- *        response = client.files.uploadBuilder("/test.txt")
- *            .autorename(true)
- *            .mute(true)
- *            .clientModified(new Date())
- *            .uploadAndFinish(in);
- *    } finally {
- *        in.close();
- *    }
- *
- * - * @param response type returned by server on request success - * @param error type returned by server on request failure - * @param exception type thrown by server on request failure (wraps error type) - */ -public abstract class DbxUploadStyleBuilder { - - /** - * Begins the upload request using this builder's request parameters and returns a {@link - * DbxUploader} for writing the request body. - * - * Callers can complete the request by writing the upload data to the {@link java.io.OutputStream} - * returned by {@link DbxUploader#getOutputStream} and receiving the server response using - * {@link DbxUploader#finish}. - * - * See {@link #uploadAndFinish} convenience method for a simpler way to complete the request. - * - * @return {@link DbxUploader} used to upload data and complete the request - * - * @throws DbxException if an error occursing initializing the request - */ - public abstract DbxUploader start() throws DbxException; - - /** - * Convenience method for {@link DbxUploader#uploadAndFinish(InputStream)}: - * - *

-     *    builder.start().uploadAndFinish(in);
-     * 
- * - * @param in {@code InputStream} containing data to upload - * - * @return Response from server - * - * @throws X if the server sent an error response for the request - * @throws DbxException if an error occurs uploading the data or reading the response - * @throws IOException if an error occurs reading the input stream. - */ - public R uploadAndFinish(InputStream in) throws X, DbxException, IOException - { - return start().uploadAndFinish(in); - } - - /** - * Convenience method for {@link DbxUploader#uploadAndFinish(InputStream, long)}: - * - *

-     *    builder.start().uploadAndFinish(in, limit);
-     * 
- * - * @param in {@code InputStream} containing data to upload - * @param limit Maximum number of bytes to read from the given {@code InputStream} - * - * @return Response from server - * - * @throws X if the server sent an error response for the request - * @throws DbxException if an error occurs uploading the data or reading the response - * @throws IOException if an error occurs reading the input stream. - */ - public R uploadAndFinish(InputStream in, long limit) throws X, DbxException, IOException - { - return start().uploadAndFinish(in, limit); - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/async/LaunchEmptyResult.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/async/LaunchEmptyResult.java deleted file mode 100644 index ccfcaa01..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/async/LaunchEmptyResult.java +++ /dev/null @@ -1,268 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from async.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.async; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.UnionSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * Result returned by methods that may either launch an asynchronous job or - * complete synchronously. Upon synchronous completion of the job, no additional - * information is returned. - * - *

This class is a tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isAbc()} - * methods will return {@code true}. You can use {@link #tag()} to determine the - * tag associated with this instance.

- */ -public final class LaunchEmptyResult { - // union async.LaunchEmptyResult (async.stone) - - /** - * Discriminating tag type for {@link LaunchEmptyResult}. - */ - public enum Tag { - /** - * This response indicates that the processing is asynchronous. The - * string is an id that can be used to obtain the status of the - * asynchronous job. - */ - ASYNC_JOB_ID, // String - /** - * The job finished synchronously and successfully. - */ - COMPLETE; - } - - /** - * The job finished synchronously and successfully. - */ - public static final LaunchEmptyResult COMPLETE = new LaunchEmptyResult(Tag.COMPLETE, null); - - private final Tag _tag; - private final String asyncJobIdValue; - - /** - * Result returned by methods that may either launch an asynchronous job or - * complete synchronously. Upon synchronous completion of the job, no - * additional information is returned. - * - * @param asyncJobIdValue This response indicates that the processing is - * asynchronous. The string is an id that can be used to obtain the - * status of the asynchronous job. Must have length of at least 1 and - * not be {@code null}. - * @param _tag Discriminating tag for this instance. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - private LaunchEmptyResult(Tag _tag, String asyncJobIdValue) { - this._tag = _tag; - this.asyncJobIdValue = asyncJobIdValue; - } - - /** - * Returns the tag for this instance. - * - *

This class is a tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isXyz()} - * methods will return {@code true}. Callers are recommended to use the tag - * value in a {@code switch} statement to properly handle the different - * values for this {@code LaunchEmptyResult}.

- * - * @return the tag for this instance. - */ - public Tag tag() { - return _tag; - } - - /** - * Returns {@code true} if this instance has the tag {@link - * Tag#ASYNC_JOB_ID}, {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link - * Tag#ASYNC_JOB_ID}, {@code false} otherwise. - */ - public boolean isAsyncJobId() { - return this._tag == Tag.ASYNC_JOB_ID; - } - - /** - * Returns an instance of {@code LaunchEmptyResult} that has its tag set to - * {@link Tag#ASYNC_JOB_ID}. - * - *

This response indicates that the processing is asynchronous. The - * string is an id that can be used to obtain the status of the asynchronous - * job.

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code LaunchEmptyResult} with its tag set to {@link - * Tag#ASYNC_JOB_ID}. - * - * @throws IllegalArgumentException if {@code value} is shorter than 1 or - * is {@code null}. - */ - public static LaunchEmptyResult asyncJobId(String value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - if (value.length() < 1) { - throw new IllegalArgumentException("String is shorter than 1"); - } - return new LaunchEmptyResult(Tag.ASYNC_JOB_ID, value); - } - - /** - * This response indicates that the processing is asynchronous. The string - * is an id that can be used to obtain the status of the asynchronous job. - * - *

This instance must be tagged as {@link Tag#ASYNC_JOB_ID}.

- * - * @return The {@link String} value associated with this instance if {@link - * #isAsyncJobId} is {@code true}. - * - * @throws IllegalStateException If {@link #isAsyncJobId} is {@code false}. - */ - public String getAsyncJobIdValue() { - if (this._tag != Tag.ASYNC_JOB_ID) { - throw new IllegalStateException("Invalid tag: required Tag.ASYNC_JOB_ID, but was Tag." + this._tag.name()); - } - return asyncJobIdValue; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#COMPLETE}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#COMPLETE}, - * {@code false} otherwise. - */ - public boolean isComplete() { - return this._tag == Tag.COMPLETE; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - _tag, - asyncJobIdValue - }); - hash = (31 * super.hashCode()) + hash; - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - else if (obj instanceof LaunchEmptyResult) { - LaunchEmptyResult other = (LaunchEmptyResult) obj; - if (this._tag != other._tag) { - return false; - } - switch (_tag) { - case ASYNC_JOB_ID: - return (this.asyncJobIdValue == other.asyncJobIdValue) || (this.asyncJobIdValue.equals(other.asyncJobIdValue)); - case COMPLETE: - return true; - default: - return false; - } - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - public static class Serializer extends UnionSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(LaunchEmptyResult value, JsonGenerator g) throws IOException, JsonGenerationException { - switch (value.tag()) { - case ASYNC_JOB_ID: { - g.writeStartObject(); - writeTag("async_job_id", g); - g.writeFieldName("async_job_id"); - StoneSerializers.string().serialize(value.asyncJobIdValue, g); - g.writeEndObject(); - break; - } - case COMPLETE: { - g.writeString("complete"); - break; - } - default: { - throw new IllegalArgumentException("Unrecognized tag: " + value.tag()); - } - } - } - - @Override - public LaunchEmptyResult deserialize(JsonParser p) throws IOException, JsonParseException { - LaunchEmptyResult value; - boolean collapsed; - String tag; - if (p.getCurrentToken() == JsonToken.VALUE_STRING) { - collapsed = true; - tag = getStringValue(p); - p.nextToken(); - } - else { - collapsed = false; - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); - } - else if ("async_job_id".equals(tag)) { - String fieldValue = null; - expectField("async_job_id", p); - fieldValue = StoneSerializers.string().deserialize(p); - value = LaunchEmptyResult.asyncJobId(fieldValue); - } - else if ("complete".equals(tag)) { - value = LaunchEmptyResult.COMPLETE; - } - else { - throw new JsonParseException(p, "Unknown tag: " + tag); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/async/LaunchResultBase.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/async/LaunchResultBase.java deleted file mode 100644 index f723b01e..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/async/LaunchResultBase.java +++ /dev/null @@ -1,241 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from async.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.async; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.UnionSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * Result returned by methods that launch an asynchronous job. A method who may - * either launch an asynchronous job, or complete the request synchronously, can - * use this union by extending it, and adding a 'complete' field with the type - * of the synchronous response. See {@link LaunchEmptyResult} for an example. - * - *

This class is a tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isAbc()} - * methods will return {@code true}. You can use {@link #tag()} to determine the - * tag associated with this instance.

- */ -public final class LaunchResultBase { - // union async.LaunchResultBase (async.stone) - - /** - * Discriminating tag type for {@link LaunchResultBase}. - */ - public enum Tag { - /** - * This response indicates that the processing is asynchronous. The - * string is an id that can be used to obtain the status of the - * asynchronous job. - */ - ASYNC_JOB_ID; // String - } - - private final Tag _tag; - private final String asyncJobIdValue; - - /** - * Result returned by methods that launch an asynchronous job. A method who - * may either launch an asynchronous job, or complete the request - * synchronously, can use this union by extending it, and adding a - * 'complete' field with the type of the synchronous response. See {@link - * LaunchEmptyResult} for an example. - * - * @param asyncJobIdValue This response indicates that the processing is - * asynchronous. The string is an id that can be used to obtain the - * status of the asynchronous job. Must have length of at least 1 and - * not be {@code null}. - * @param _tag Discriminating tag for this instance. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - private LaunchResultBase(Tag _tag, String asyncJobIdValue) { - this._tag = _tag; - this.asyncJobIdValue = asyncJobIdValue; - } - - /** - * Returns the tag for this instance. - * - *

This class is a tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isXyz()} - * methods will return {@code true}. Callers are recommended to use the tag - * value in a {@code switch} statement to properly handle the different - * values for this {@code LaunchResultBase}.

- * - * @return the tag for this instance. - */ - public Tag tag() { - return _tag; - } - - /** - * Returns {@code true} if this instance has the tag {@link - * Tag#ASYNC_JOB_ID}, {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link - * Tag#ASYNC_JOB_ID}, {@code false} otherwise. - */ - public boolean isAsyncJobId() { - return this._tag == Tag.ASYNC_JOB_ID; - } - - /** - * Returns an instance of {@code LaunchResultBase} that has its tag set to - * {@link Tag#ASYNC_JOB_ID}. - * - *

This response indicates that the processing is asynchronous. The - * string is an id that can be used to obtain the status of the asynchronous - * job.

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code LaunchResultBase} with its tag set to {@link - * Tag#ASYNC_JOB_ID}. - * - * @throws IllegalArgumentException if {@code value} is shorter than 1 or - * is {@code null}. - */ - public static LaunchResultBase asyncJobId(String value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - if (value.length() < 1) { - throw new IllegalArgumentException("String is shorter than 1"); - } - return new LaunchResultBase(Tag.ASYNC_JOB_ID, value); - } - - /** - * This response indicates that the processing is asynchronous. The string - * is an id that can be used to obtain the status of the asynchronous job. - * - *

This instance must be tagged as {@link Tag#ASYNC_JOB_ID}.

- * - * @return The {@link String} value associated with this instance if {@link - * #isAsyncJobId} is {@code true}. - * - * @throws IllegalStateException If {@link #isAsyncJobId} is {@code false}. - */ - public String getAsyncJobIdValue() { - if (this._tag != Tag.ASYNC_JOB_ID) { - throw new IllegalStateException("Invalid tag: required Tag.ASYNC_JOB_ID, but was Tag." + this._tag.name()); - } - return asyncJobIdValue; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - _tag, - asyncJobIdValue - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - else if (obj instanceof LaunchResultBase) { - LaunchResultBase other = (LaunchResultBase) obj; - if (this._tag != other._tag) { - return false; - } - switch (_tag) { - case ASYNC_JOB_ID: - return (this.asyncJobIdValue == other.asyncJobIdValue) || (this.asyncJobIdValue.equals(other.asyncJobIdValue)); - default: - return false; - } - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - public static class Serializer extends UnionSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(LaunchResultBase value, JsonGenerator g) throws IOException, JsonGenerationException { - switch (value.tag()) { - case ASYNC_JOB_ID: { - g.writeStartObject(); - writeTag("async_job_id", g); - g.writeFieldName("async_job_id"); - StoneSerializers.string().serialize(value.asyncJobIdValue, g); - g.writeEndObject(); - break; - } - default: { - throw new IllegalArgumentException("Unrecognized tag: " + value.tag()); - } - } - } - - @Override - public LaunchResultBase deserialize(JsonParser p) throws IOException, JsonParseException { - LaunchResultBase value; - boolean collapsed; - String tag; - if (p.getCurrentToken() == JsonToken.VALUE_STRING) { - collapsed = true; - tag = getStringValue(p); - p.nextToken(); - } - else { - collapsed = false; - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); - } - else if ("async_job_id".equals(tag)) { - String fieldValue = null; - expectField("async_job_id", p); - fieldValue = StoneSerializers.string().deserialize(p); - value = LaunchResultBase.asyncJobId(fieldValue); - } - else { - throw new JsonParseException(p, "Unknown tag: " + tag); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/async/PollArg.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/async/PollArg.java deleted file mode 100644 index 19812051..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/async/PollArg.java +++ /dev/null @@ -1,147 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from async.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.async; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * Arguments for methods that poll the status of an asynchronous job. - */ -public class PollArg { - // struct async.PollArg (async.stone) - - protected final String asyncJobId; - - /** - * Arguments for methods that poll the status of an asynchronous job. - * - * @param asyncJobId Id of the asynchronous job. This is the value of a - * response returned from the method that launched the job. Must have - * length of at least 1 and not be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public PollArg(String asyncJobId) { - if (asyncJobId == null) { - throw new IllegalArgumentException("Required value for 'asyncJobId' is null"); - } - if (asyncJobId.length() < 1) { - throw new IllegalArgumentException("String 'asyncJobId' is shorter than 1"); - } - this.asyncJobId = asyncJobId; - } - - /** - * Id of the asynchronous job. This is the value of a response returned from - * the method that launched the job. - * - * @return value for this field, never {@code null}. - */ - public String getAsyncJobId() { - return asyncJobId; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - asyncJobId - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - PollArg other = (PollArg) obj; - return (this.asyncJobId == other.asyncJobId) || (this.asyncJobId.equals(other.asyncJobId)); - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - public static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(PollArg value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("async_job_id"); - StoneSerializers.string().serialize(value.asyncJobId, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public PollArg deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - PollArg value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - String f_asyncJobId = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("async_job_id".equals(field)) { - f_asyncJobId = StoneSerializers.string().deserialize(p); - } - else { - skipValue(p); - } - } - if (f_asyncJobId == null) { - throw new JsonParseException(p, "Required field \"async_job_id\" missing."); - } - value = new PollArg(f_asyncJobId); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/async/PollEmptyResult.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/async/PollEmptyResult.java deleted file mode 100644 index bd968934..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/async/PollEmptyResult.java +++ /dev/null @@ -1,86 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from async.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.async; - -import java.io.IOException; - -import autosaveworld.zlibs.com.dropbox.core.stone.UnionSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * Result returned by methods that poll for the status of an asynchronous job. - * Upon completion of the job, no additional information is returned. - */ -public enum PollEmptyResult { - // union async.PollEmptyResult (async.stone) - /** - * The asynchronous job is still in progress. - */ - IN_PROGRESS, - /** - * The asynchronous job has completed successfully. - */ - COMPLETE; - - /** - * For internal use only. - */ - public static class Serializer extends UnionSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(PollEmptyResult value, JsonGenerator g) throws IOException, JsonGenerationException { - switch (value) { - case IN_PROGRESS: { - g.writeString("in_progress"); - break; - } - case COMPLETE: { - g.writeString("complete"); - break; - } - default: { - throw new IllegalArgumentException("Unrecognized tag: " + value); - } - } - } - - @Override - public PollEmptyResult deserialize(JsonParser p) throws IOException, JsonParseException { - PollEmptyResult value; - boolean collapsed; - String tag; - if (p.getCurrentToken() == JsonToken.VALUE_STRING) { - collapsed = true; - tag = getStringValue(p); - p.nextToken(); - } - else { - collapsed = false; - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); - } - else if ("in_progress".equals(tag)) { - value = PollEmptyResult.IN_PROGRESS; - } - else if ("complete".equals(tag)) { - value = PollEmptyResult.COMPLETE; - } - else { - throw new JsonParseException(p, "Unknown tag: " + tag); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/async/PollError.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/async/PollError.java deleted file mode 100644 index 881f8d9f..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/async/PollError.java +++ /dev/null @@ -1,96 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from async.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.async; - -import java.io.IOException; - -import autosaveworld.zlibs.com.dropbox.core.stone.UnionSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * Error returned by methods for polling the status of asynchronous job. - */ -public enum PollError { - // union async.PollError (async.stone) - /** - * The job ID is invalid. - */ - INVALID_ASYNC_JOB_ID, - /** - * Something went wrong with the job on Dropbox's end. You'll need to verify - * that the action you were taking succeeded, and if not, try again. This - * should happen very rarely. - */ - INTERNAL_ERROR, - /** - * Catch-all used for unknown tag values returned by the Dropbox servers. - * - *

Receiving a catch-all value typically indicates this SDK version is - * not up to date. Consider updating your SDK version to handle the new - * tags.

- */ - OTHER; // *catch_all - - /** - * For internal use only. - */ - public static class Serializer extends UnionSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(PollError value, JsonGenerator g) throws IOException, JsonGenerationException { - switch (value) { - case INVALID_ASYNC_JOB_ID: { - g.writeString("invalid_async_job_id"); - break; - } - case INTERNAL_ERROR: { - g.writeString("internal_error"); - break; - } - default: { - g.writeString("other"); - } - } - } - - @Override - public PollError deserialize(JsonParser p) throws IOException, JsonParseException { - PollError value; - boolean collapsed; - String tag; - if (p.getCurrentToken() == JsonToken.VALUE_STRING) { - collapsed = true; - tag = getStringValue(p); - p.nextToken(); - } - else { - collapsed = false; - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); - } - else if ("invalid_async_job_id".equals(tag)) { - value = PollError.INVALID_ASYNC_JOB_ID; - } - else if ("internal_error".equals(tag)) { - value = PollError.INTERNAL_ERROR; - } - else { - value = PollError.OTHER; - skipFields(p); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/async/PollErrorException.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/async/PollErrorException.java deleted file mode 100644 index 50ff1efb..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/async/PollErrorException.java +++ /dev/null @@ -1,80 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated by Stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.async; - -import autosaveworld.zlibs.com.dropbox.core.DbxApiException; -import autosaveworld.zlibs.com.dropbox.core.LocalizedText; - -/** - * Exception thrown when the server responds with a {@link PollError} error. - * - *

This exception is raised by {@link - * autosaveworld.zlibs.com.dropbox.core.v2.team.DbxTeamTeamRequests#membersAddJobStatusGet(String)}, - * {@link - * autosaveworld.zlibs.com.dropbox.core.v2.files.DbxUserFilesRequests#saveUrlCheckJobStatus(String)}, - * {@link - * autosaveworld.zlibs.com.dropbox.core.v2.team.DbxTeamTeamRequests#membersRemoveJobStatusGet(String)}, - * {@link - * autosaveworld.zlibs.com.dropbox.core.v2.sharing.DbxUserSharingRequests#checkJobStatus(String)}, - * {@link - * autosaveworld.zlibs.com.dropbox.core.v2.files.DbxUserFilesRequests#moveBatchCheck(String)}, - * {@link - * autosaveworld.zlibs.com.dropbox.core.v2.files.DbxUserFilesRequests#copyBatchCheck(String)}, - * {@link - * autosaveworld.zlibs.com.dropbox.core.v2.files.DbxUserFilesRequests#deleteBatchCheck(String)}, - * {@link - * autosaveworld.zlibs.com.dropbox.core.v2.files.DbxUserFilesRequests#uploadSessionFinishBatchCheck(String)}, - * {@link - * autosaveworld.zlibs.com.dropbox.core.v2.sharing.DbxUserSharingRequests#checkShareJobStatus(String)}, - * and {@link - * autosaveworld.zlibs.com.dropbox.core.v2.sharing.DbxUserSharingRequests#checkRemoveMemberJobStatus(String)}. - *

- */ -public class PollErrorException extends DbxApiException { - // exception for routes: - // 2/team/members/add/job_status/get - // 2/files/save_url/check_job_status - // 2/team/members/remove/job_status/get - // 2/sharing/check_job_status - // 2/files/move_batch/check - // 2/files/copy_batch/check - // 2/files/delete_batch/check - // 2/files/upload_session/finish_batch/check - // 2/sharing/check_share_job_status - // 2/sharing/check_remove_member_job_status - - private static final long serialVersionUID = 0L; - - /** - * The error reported by {@link - * autosaveworld.zlibs.com.dropbox.core.v2.team.DbxTeamTeamRequests#membersAddJobStatusGet(String)}, - * {@link - * autosaveworld.zlibs.com.dropbox.core.v2.files.DbxUserFilesRequests#saveUrlCheckJobStatus(String)}, - * {@link - * autosaveworld.zlibs.com.dropbox.core.v2.team.DbxTeamTeamRequests#membersRemoveJobStatusGet(String)}, - * {@link - * autosaveworld.zlibs.com.dropbox.core.v2.sharing.DbxUserSharingRequests#checkJobStatus(String)}, - * {@link - * autosaveworld.zlibs.com.dropbox.core.v2.files.DbxUserFilesRequests#moveBatchCheck(String)}, - * {@link - * autosaveworld.zlibs.com.dropbox.core.v2.files.DbxUserFilesRequests#copyBatchCheck(String)}, - * {@link - * autosaveworld.zlibs.com.dropbox.core.v2.files.DbxUserFilesRequests#deleteBatchCheck(String)}, - * {@link - * autosaveworld.zlibs.com.dropbox.core.v2.files.DbxUserFilesRequests#uploadSessionFinishBatchCheck(String)}, - * {@link - * autosaveworld.zlibs.com.dropbox.core.v2.sharing.DbxUserSharingRequests#checkShareJobStatus(String)}, - * and {@link - * autosaveworld.zlibs.com.dropbox.core.v2.sharing.DbxUserSharingRequests#checkRemoveMemberJobStatus(String)}. - */ - public final PollError errorValue; - - public PollErrorException(String routeName, String requestId, LocalizedText userMessage, PollError errorValue) { - super(requestId, userMessage, buildMessage(routeName, userMessage, errorValue)); - if (errorValue == null) { - throw new NullPointerException("errorValue"); - } - this.errorValue = errorValue; - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/CommitInfo.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/CommitInfo.java deleted file mode 100644 index a3e628df..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/CommitInfo.java +++ /dev/null @@ -1,412 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Date; -import java.util.regex.Pattern; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.dropbox.core.util.LangUtil; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -public class CommitInfo { - // struct files.CommitInfo (files.stone) - - protected final String path; - protected final WriteMode mode; - protected final boolean autorename; - protected final Date clientModified; - protected final boolean mute; - - /** - * Use {@link newBuilder} to create instances of this class without - * specifying values for all optional fields. - * - * @param path Path in the user's Dropbox to save the file. Must match - * pattern "{@code (/(.|[\\r\\n])*)|(ns:[0-9]+(/.*)?)}" and not be - * {@code null}. - * @param mode Selects what to do if the file already exists. Must not be - * {@code null}. - * @param autorename If there's a conflict, as determined by {@link - * CommitInfo#getMode}, have the Dropbox server try to autorename the - * file to avoid conflict. - * @param clientModified The value to store as the {@link - * CommitInfo#getClientModified} timestamp. Dropbox automatically - * records the time at which the file was written to the Dropbox - * servers. It can also record an additional timestamp, provided by - * Dropbox desktop clients, mobile clients, and API apps of when the - * file was actually created or modified. - * @param mute Normally, users are made aware of any file modifications in - * their Dropbox account via notifications in the client software. If - * {@code true}, this tells the clients that this modification shouldn't - * result in a user notification. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public CommitInfo(String path, WriteMode mode, boolean autorename, Date clientModified, boolean mute) { - if (path == null) { - throw new IllegalArgumentException("Required value for 'path' is null"); - } - if (!Pattern.matches("(/(.|[\\r\\n])*)|(ns:[0-9]+(/.*)?)", path)) { - throw new IllegalArgumentException("String 'path' does not match pattern"); - } - this.path = path; - if (mode == null) { - throw new IllegalArgumentException("Required value for 'mode' is null"); - } - this.mode = mode; - this.autorename = autorename; - this.clientModified = LangUtil.truncateMillis(clientModified); - this.mute = mute; - } - - /** - * None - * - *

The default values for unset fields will be used.

- * - * @param path Path in the user's Dropbox to save the file. Must match - * pattern "{@code (/(.|[\\r\\n])*)|(ns:[0-9]+(/.*)?)}" and not be - * {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public CommitInfo(String path) { - this(path, WriteMode.ADD, false, null, false); - } - - /** - * Path in the user's Dropbox to save the file. - * - * @return value for this field, never {@code null}. - */ - public String getPath() { - return path; - } - - /** - * Selects what to do if the file already exists. - * - * @return value for this field, or {@code null} if not present. Defaults to - * WriteMode.ADD. - */ - public WriteMode getMode() { - return mode; - } - - /** - * If there's a conflict, as determined by {@link CommitInfo#getMode}, have - * the Dropbox server try to autorename the file to avoid conflict. - * - * @return value for this field, or {@code null} if not present. Defaults to - * false. - */ - public boolean getAutorename() { - return autorename; - } - - /** - * The value to store as the {@link CommitInfo#getClientModified} timestamp. - * Dropbox automatically records the time at which the file was written to - * the Dropbox servers. It can also record an additional timestamp, provided - * by Dropbox desktop clients, mobile clients, and API apps of when the file - * was actually created or modified. - * - * @return value for this field, or {@code null} if not present. - */ - public Date getClientModified() { - return clientModified; - } - - /** - * Normally, users are made aware of any file modifications in their Dropbox - * account via notifications in the client software. If {@code true}, this - * tells the clients that this modification shouldn't result in a user - * notification. - * - * @return value for this field, or {@code null} if not present. Defaults to - * false. - */ - public boolean getMute() { - return mute; - } - - /** - * Returns a new builder for creating an instance of this class. - * - * @param path Path in the user's Dropbox to save the file. Must match - * pattern "{@code (/(.|[\\r\\n])*)|(ns:[0-9]+(/.*)?)}" and not be - * {@code null}. - * - * @return builder for this class. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public static Builder newBuilder(String path) { - return new Builder(path); - } - - /** - * Builder for {@link CommitInfo}. - */ - public static class Builder { - protected final String path; - - protected WriteMode mode; - protected boolean autorename; - protected Date clientModified; - protected boolean mute; - - protected Builder(String path) { - if (path == null) { - throw new IllegalArgumentException("Required value for 'path' is null"); - } - if (!Pattern.matches("(/(.|[\\r\\n])*)|(ns:[0-9]+(/.*)?)", path)) { - throw new IllegalArgumentException("String 'path' does not match pattern"); - } - this.path = path; - this.mode = WriteMode.ADD; - this.autorename = false; - this.clientModified = null; - this.mute = false; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code - * WriteMode.ADD}.

- * - * @param mode Selects what to do if the file already exists. Must not - * be {@code null}. Defaults to {@code WriteMode.ADD} when set to - * {@code null}. - * - * @return this builder - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public Builder withMode(WriteMode mode) { - if (mode != null) { - this.mode = mode; - } - else { - this.mode = WriteMode.ADD; - } - return this; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}. - *

- * - * @param autorename If there's a conflict, as determined by {@link - * CommitInfo#getMode}, have the Dropbox server try to autorename - * the file to avoid conflict. Defaults to {@code false} when set to - * {@code null}. - * - * @return this builder - */ - public Builder withAutorename(Boolean autorename) { - if (autorename != null) { - this.autorename = autorename; - } - else { - this.autorename = false; - } - return this; - } - - /** - * Set value for optional field. - * - * @param clientModified The value to store as the {@link - * CommitInfo#getClientModified} timestamp. Dropbox automatically - * records the time at which the file was written to the Dropbox - * servers. It can also record an additional timestamp, provided by - * Dropbox desktop clients, mobile clients, and API apps of when the - * file was actually created or modified. - * - * @return this builder - */ - public Builder withClientModified(Date clientModified) { - this.clientModified = LangUtil.truncateMillis(clientModified); - return this; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}. - *

- * - * @param mute Normally, users are made aware of any file modifications - * in their Dropbox account via notifications in the client - * software. If {@code true}, this tells the clients that this - * modification shouldn't result in a user notification. Defaults to - * {@code false} when set to {@code null}. - * - * @return this builder - */ - public Builder withMute(Boolean mute) { - if (mute != null) { - this.mute = mute; - } - else { - this.mute = false; - } - return this; - } - - /** - * Builds an instance of {@link CommitInfo} configured with this - * builder's values - * - * @return new instance of {@link CommitInfo} - */ - public CommitInfo build() { - return new CommitInfo(path, mode, autorename, clientModified, mute); - } - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - path, - mode, - autorename, - clientModified, - mute - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - CommitInfo other = (CommitInfo) obj; - return ((this.path == other.path) || (this.path.equals(other.path))) - && ((this.mode == other.mode) || (this.mode.equals(other.mode))) - && (this.autorename == other.autorename) - && ((this.clientModified == other.clientModified) || (this.clientModified != null && this.clientModified.equals(other.clientModified))) - && (this.mute == other.mute) - ; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(CommitInfo value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("path"); - StoneSerializers.string().serialize(value.path, g); - g.writeFieldName("mode"); - WriteMode.Serializer.INSTANCE.serialize(value.mode, g); - g.writeFieldName("autorename"); - StoneSerializers.boolean_().serialize(value.autorename, g); - if (value.clientModified != null) { - g.writeFieldName("client_modified"); - StoneSerializers.nullable(StoneSerializers.timestamp()).serialize(value.clientModified, g); - } - g.writeFieldName("mute"); - StoneSerializers.boolean_().serialize(value.mute, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public CommitInfo deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - CommitInfo value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - String f_path = null; - WriteMode f_mode = WriteMode.ADD; - Boolean f_autorename = false; - Date f_clientModified = null; - Boolean f_mute = false; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("path".equals(field)) { - f_path = StoneSerializers.string().deserialize(p); - } - else if ("mode".equals(field)) { - f_mode = WriteMode.Serializer.INSTANCE.deserialize(p); - } - else if ("autorename".equals(field)) { - f_autorename = StoneSerializers.boolean_().deserialize(p); - } - else if ("client_modified".equals(field)) { - f_clientModified = StoneSerializers.nullable(StoneSerializers.timestamp()).deserialize(p); - } - else if ("mute".equals(field)) { - f_mute = StoneSerializers.boolean_().deserialize(p); - } - else { - skipValue(p); - } - } - if (f_path == null) { - throw new JsonParseException(p, "Required field \"path\" missing."); - } - value = new CommitInfo(f_path, f_mode, f_autorename, f_clientModified, f_mute); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/CreateFolderArg.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/CreateFolderArg.java deleted file mode 100644 index d5699e77..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/CreateFolderArg.java +++ /dev/null @@ -1,181 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; -import java.util.regex.Pattern; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -class CreateFolderArg { - // struct files.CreateFolderArg (files.stone) - - protected final String path; - protected final boolean autorename; - - /** - * - * @param path Path in the user's Dropbox to create. Must match pattern - * "{@code (/(.|[\\r\\n])*)|(ns:[0-9]+(/.*)?)}" and not be {@code null}. - * @param autorename If there's a conflict, have the Dropbox server try to - * autorename the folder to avoid the conflict. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public CreateFolderArg(String path, boolean autorename) { - if (path == null) { - throw new IllegalArgumentException("Required value for 'path' is null"); - } - if (!Pattern.matches("(/(.|[\\r\\n])*)|(ns:[0-9]+(/.*)?)", path)) { - throw new IllegalArgumentException("String 'path' does not match pattern"); - } - this.path = path; - this.autorename = autorename; - } - - /** - * None - * - *

The default values for unset fields will be used.

- * - * @param path Path in the user's Dropbox to create. Must match pattern - * "{@code (/(.|[\\r\\n])*)|(ns:[0-9]+(/.*)?)}" and not be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public CreateFolderArg(String path) { - this(path, false); - } - - /** - * Path in the user's Dropbox to create. - * - * @return value for this field, never {@code null}. - */ - public String getPath() { - return path; - } - - /** - * If there's a conflict, have the Dropbox server try to autorename the - * folder to avoid the conflict. - * - * @return value for this field, or {@code null} if not present. Defaults to - * false. - */ - public boolean getAutorename() { - return autorename; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - path, - autorename - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - CreateFolderArg other = (CreateFolderArg) obj; - return ((this.path == other.path) || (this.path.equals(other.path))) - && (this.autorename == other.autorename) - ; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(CreateFolderArg value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("path"); - StoneSerializers.string().serialize(value.path, g); - g.writeFieldName("autorename"); - StoneSerializers.boolean_().serialize(value.autorename, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public CreateFolderArg deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - CreateFolderArg value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - String f_path = null; - Boolean f_autorename = false; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("path".equals(field)) { - f_path = StoneSerializers.string().deserialize(p); - } - else if ("autorename".equals(field)) { - f_autorename = StoneSerializers.boolean_().deserialize(p); - } - else { - skipValue(p); - } - } - if (f_path == null) { - throw new JsonParseException(p, "Required field \"path\" missing."); - } - value = new CreateFolderArg(f_path, f_autorename); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/CreateFolderError.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/CreateFolderError.java deleted file mode 100644 index 5f90b98a..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/CreateFolderError.java +++ /dev/null @@ -1,213 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.UnionSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * This class is a tagged union. Tagged unions instances are always associated - * to a specific tag. This means only one of the {@code isAbc()} methods will - * return {@code true}. You can use {@link #tag()} to determine the tag - * associated with this instance. - */ -public final class CreateFolderError { - // union files.CreateFolderError (files.stone) - - /** - * Discriminating tag type for {@link CreateFolderError}. - */ - public enum Tag { - PATH; // WriteError - } - - private final Tag _tag; - private final WriteError pathValue; - - /** - * - * @param pathValue Must not be {@code null}. - * @param _tag Discriminating tag for this instance. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - private CreateFolderError(Tag _tag, WriteError pathValue) { - this._tag = _tag; - this.pathValue = pathValue; - } - - /** - * Returns the tag for this instance. - * - *

This class is a tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isXyz()} - * methods will return {@code true}. Callers are recommended to use the tag - * value in a {@code switch} statement to properly handle the different - * values for this {@code CreateFolderError}.

- * - * @return the tag for this instance. - */ - public Tag tag() { - return _tag; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#PATH}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#PATH}, - * {@code false} otherwise. - */ - public boolean isPath() { - return this._tag == Tag.PATH; - } - - /** - * Returns an instance of {@code CreateFolderError} that has its tag set to - * {@link Tag#PATH}. - * - *

None

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code CreateFolderError} with its tag set to {@link - * Tag#PATH}. - * - * @throws IllegalArgumentException if {@code value} is {@code null}. - */ - public static CreateFolderError path(WriteError value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - return new CreateFolderError(Tag.PATH, value); - } - - /** - * This instance must be tagged as {@link Tag#PATH}. - * - * @return The {@link WriteError} value associated with this instance if - * {@link #isPath} is {@code true}. - * - * @throws IllegalStateException If {@link #isPath} is {@code false}. - */ - public WriteError getPathValue() { - if (this._tag != Tag.PATH) { - throw new IllegalStateException("Invalid tag: required Tag.PATH, but was Tag." + this._tag.name()); - } - return pathValue; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - _tag, - pathValue - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - else if (obj instanceof CreateFolderError) { - CreateFolderError other = (CreateFolderError) obj; - if (this._tag != other._tag) { - return false; - } - switch (_tag) { - case PATH: - return (this.pathValue == other.pathValue) || (this.pathValue.equals(other.pathValue)); - default: - return false; - } - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends UnionSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(CreateFolderError value, JsonGenerator g) throws IOException, JsonGenerationException { - switch (value.tag()) { - case PATH: { - g.writeStartObject(); - writeTag("path", g); - g.writeFieldName("path"); - WriteError.Serializer.INSTANCE.serialize(value.pathValue, g); - g.writeEndObject(); - break; - } - default: { - throw new IllegalArgumentException("Unrecognized tag: " + value.tag()); - } - } - } - - @Override - public CreateFolderError deserialize(JsonParser p) throws IOException, JsonParseException { - CreateFolderError value; - boolean collapsed; - String tag; - if (p.getCurrentToken() == JsonToken.VALUE_STRING) { - collapsed = true; - tag = getStringValue(p); - p.nextToken(); - } - else { - collapsed = false; - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); - } - else if ("path".equals(tag)) { - WriteError fieldValue = null; - expectField("path", p); - fieldValue = WriteError.Serializer.INSTANCE.deserialize(p); - value = CreateFolderError.path(fieldValue); - } - else { - throw new JsonParseException(p, "Unknown tag: " + tag); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/CreateFolderErrorException.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/CreateFolderErrorException.java deleted file mode 100644 index 8efbbe44..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/CreateFolderErrorException.java +++ /dev/null @@ -1,35 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated by Stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import autosaveworld.zlibs.com.dropbox.core.DbxApiException; -import autosaveworld.zlibs.com.dropbox.core.LocalizedText; - -/** - * Exception thrown when the server responds with a {@link CreateFolderError} - * error. - * - *

This exception is raised by {@link - * DbxUserFilesRequests#createFolder(String,boolean)}.

- */ -public class CreateFolderErrorException extends DbxApiException { - // exception for routes: - // 2/files/create_folder - - private static final long serialVersionUID = 0L; - - /** - * The error reported by {@link - * DbxUserFilesRequests#createFolder(String,boolean)}. - */ - public final CreateFolderError errorValue; - - public CreateFolderErrorException(String routeName, String requestId, LocalizedText userMessage, CreateFolderError errorValue) { - super(requestId, userMessage, buildMessage(routeName, userMessage, errorValue)); - if (errorValue == null) { - throw new NullPointerException("errorValue"); - } - this.errorValue = errorValue; - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DbxUserFilesRequests.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DbxUserFilesRequests.java deleted file mode 100644 index 59d2d430..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DbxUserFilesRequests.java +++ /dev/null @@ -1,809 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files_properties.stone, files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.util.List; - -import autosaveworld.zlibs.com.dropbox.core.DbxApiException; -import autosaveworld.zlibs.com.dropbox.core.DbxException; -import autosaveworld.zlibs.com.dropbox.core.DbxWrappedException; -import autosaveworld.zlibs.com.dropbox.core.http.HttpRequestor; -import autosaveworld.zlibs.com.dropbox.core.v2.DbxRawClientV2; -import autosaveworld.zlibs.com.dropbox.core.v2.async.LaunchEmptyResult; -import autosaveworld.zlibs.com.dropbox.core.v2.async.PollArg; -import autosaveworld.zlibs.com.dropbox.core.v2.async.PollError; -import autosaveworld.zlibs.com.dropbox.core.v2.async.PollErrorException; - -/** - * Routes in namespace "files". - */ -public class DbxUserFilesRequests { - // namespace files (files_properties.stone, files.stone) - - private final DbxRawClientV2 client; - - public DbxUserFilesRequests(DbxRawClientV2 client) { - this.client = client; - } - - // - // route 2/files/create_folder - // - - /** - * Create a folder at a given path. - * - */ - FolderMetadata createFolder(CreateFolderArg arg) throws CreateFolderErrorException, DbxException { - try { - return this.client.rpcStyle(this.client.getHost().getApi(), - "2/files/create_folder", - arg, - false, - CreateFolderArg.Serializer.INSTANCE, - FolderMetadata.Serializer.INSTANCE, - CreateFolderError.Serializer.INSTANCE); - } - catch (DbxWrappedException ex) { - throw new CreateFolderErrorException("2/files/create_folder", ex.getRequestId(), ex.getUserMessage(), (CreateFolderError) ex.getErrorValue()); - } - } - - /** - * Create a folder at a given path. - * - *

The {@code autorename} request parameter will default to {@code - * false} (see {@link #createFolder(String,boolean)}).

- * - * @param path Path in the user's Dropbox to create. Must match pattern - * "{@code (/(.|[\\r\\n])*)|(ns:[0-9]+(/.*)?)}" and not be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public FolderMetadata createFolder(String path) throws CreateFolderErrorException, DbxException { - CreateFolderArg _arg = new CreateFolderArg(path); - return createFolder(_arg); - } - - /** - * Create a folder at a given path. - * - * @param path Path in the user's Dropbox to create. Must match pattern - * "{@code (/(.|[\\r\\n])*)|(ns:[0-9]+(/.*)?)}" and not be {@code null}. - * @param autorename If there's a conflict, have the Dropbox server try to - * autorename the folder to avoid the conflict. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public FolderMetadata createFolder(String path, boolean autorename) throws CreateFolderErrorException, DbxException { - CreateFolderArg _arg = new CreateFolderArg(path, autorename); - return createFolder(_arg); - } - - // - // route 2/files/delete - // - - /** - * Delete the file or folder at a given path. If the path is a folder, all - * its contents will be deleted too. A successful response indicates that - * the file or folder was deleted. The returned metadata will be the - * corresponding {@link FileMetadata} or {@link FolderMetadata} for the item - * at time of deletion, and not a {@link DeletedMetadata} object. - * - * - * @return Metadata for a file or folder. - */ - Metadata delete(DeleteArg arg) throws DeleteErrorException, DbxException { - try { - return this.client.rpcStyle(this.client.getHost().getApi(), - "2/files/delete", - arg, - false, - DeleteArg.Serializer.INSTANCE, - Metadata.Serializer.INSTANCE, - DeleteError.Serializer.INSTANCE); - } - catch (DbxWrappedException ex) { - throw new DeleteErrorException("2/files/delete", ex.getRequestId(), ex.getUserMessage(), (DeleteError) ex.getErrorValue()); - } - } - - /** - * Delete the file or folder at a given path. If the path is a folder, all - * its contents will be deleted too. A successful response indicates that - * the file or folder was deleted. The returned metadata will be the - * corresponding {@link FileMetadata} or {@link FolderMetadata} for the item - * at time of deletion, and not a {@link DeletedMetadata} object. - * - * @param path Path in the user's Dropbox to delete. Must match pattern - * "{@code (/(.|[\\r\\n])*)|(ns:[0-9]+(/.*)?)}" and not be {@code null}. - * - * @return Metadata for a file or folder. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public Metadata delete(String path) throws DeleteErrorException, DbxException { - DeleteArg _arg = new DeleteArg(path); - return delete(_arg); - } - - // - // route 2/files/delete_batch - // - - /** - * Delete multiple files/folders at once. This route is asynchronous, which - * returns a job ID immediately and runs the delete batch asynchronously. - * Use {@link DbxUserFilesRequests#deleteBatchCheck(String)} to check the - * job status. - * - * - * @return Result returned by methods that may either launch an asynchronous - * job or complete synchronously. Upon synchronous completion of the - * job, no additional information is returned. - */ - LaunchEmptyResult deleteBatch(DeleteBatchArg arg) throws DbxApiException, DbxException { - try { - return this.client.rpcStyle(this.client.getHost().getApi(), - "2/files/delete_batch", - arg, - false, - DeleteBatchArg.Serializer.INSTANCE, - LaunchEmptyResult.Serializer.INSTANCE, - autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers.void_()); - } - catch (DbxWrappedException ex) { - throw new DbxApiException(ex.getRequestId(), ex.getUserMessage(), "Unexpected error response for \"delete_batch\":" + ex.getErrorValue()); - } - } - - /** - * Delete multiple files/folders at once. This route is asynchronous, which - * returns a job ID immediately and runs the delete batch asynchronously. - * Use {@link DbxUserFilesRequests#deleteBatchCheck(String)} to check the - * job status. - * - * @param entries Must not contain a {@code null} item and not be {@code - * null}. - * - * @return Result returned by methods that may either launch an asynchronous - * job or complete synchronously. Upon synchronous completion of the - * job, no additional information is returned. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public LaunchEmptyResult deleteBatch(List entries) throws DbxApiException, DbxException { - DeleteBatchArg _arg = new DeleteBatchArg(entries); - return deleteBatch(_arg); - } - - // - // route 2/files/delete_batch/check - // - - /** - * Returns the status of an asynchronous job for {@link - * DbxUserFilesRequests#deleteBatch(List)}. If success, it returns list of - * result for each entry. - * - * @param arg Arguments for methods that poll the status of an asynchronous - * job. - */ - DeleteBatchJobStatus deleteBatchCheck(PollArg arg) throws PollErrorException, DbxException { - try { - return this.client.rpcStyle(this.client.getHost().getApi(), - "2/files/delete_batch/check", - arg, - false, - PollArg.Serializer.INSTANCE, - DeleteBatchJobStatus.Serializer.INSTANCE, - PollError.Serializer.INSTANCE); - } - catch (DbxWrappedException ex) { - throw new PollErrorException("2/files/delete_batch/check", ex.getRequestId(), ex.getUserMessage(), (PollError) ex.getErrorValue()); - } - } - - /** - * Returns the status of an asynchronous job for {@link - * DbxUserFilesRequests#deleteBatch(List)}. If success, it returns list of - * result for each entry. - * - * @param asyncJobId Id of the asynchronous job. This is the value of a - * response returned from the method that launched the job. Must have - * length of at least 1 and not be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public DeleteBatchJobStatus deleteBatchCheck(String asyncJobId) throws PollErrorException, DbxException { - PollArg _arg = new PollArg(asyncJobId); - return deleteBatchCheck(_arg); - } - - // - // route 2/files/get_metadata - // - - /** - * Returns the metadata for a file or folder. Note: Metadata for the root - * folder is unsupported. - * - * - * @return Metadata for a file or folder. - */ - Metadata getMetadata(GetMetadataArg arg) throws GetMetadataErrorException, DbxException { - try { - return this.client.rpcStyle(this.client.getHost().getApi(), - "2/files/get_metadata", - arg, - false, - GetMetadataArg.Serializer.INSTANCE, - Metadata.Serializer.INSTANCE, - GetMetadataError.Serializer.INSTANCE); - } - catch (DbxWrappedException ex) { - throw new GetMetadataErrorException("2/files/get_metadata", ex.getRequestId(), ex.getUserMessage(), (GetMetadataError) ex.getErrorValue()); - } - } - - /** - * Returns the metadata for a file or folder. Note: Metadata for the root - * folder is unsupported. - * - *

The default values for the optional request parameters will be used. - * See {@link GetMetadataBuilder} for more details.

- * - * @param path The path of a file or folder on Dropbox. Must match pattern - * "{@code (/(.|[\\r\\n])*|id:.*)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)}" - * and not be {@code null}. - * - * @return Metadata for a file or folder. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public Metadata getMetadata(String path) throws GetMetadataErrorException, DbxException { - GetMetadataArg _arg = new GetMetadataArg(path); - return getMetadata(_arg); - } - - /** - * Returns the metadata for a file or folder. Note: Metadata for the root - * folder is unsupported. - * - * @param path The path of a file or folder on Dropbox. Must match pattern - * "{@code (/(.|[\\r\\n])*|id:.*)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)}" - * and not be {@code null}. - * - * @return Request builder for configuring request parameters and completing - * the request. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public GetMetadataBuilder getMetadataBuilder(String path) { - GetMetadataArg.Builder argBuilder_ = GetMetadataArg.newBuilder(path); - return new GetMetadataBuilder(this, argBuilder_); - } - - // - // route 2/files/list_folder - // - - /** - * Starts returning the contents of a folder. If the result's {@link - * ListFolderResult#getHasMore} field is {@code true}, call {@link - * DbxUserFilesRequests#listFolderContinue(String)} with the returned {@link - * ListFolderResult#getCursor} to retrieve more entries. If you're using - * {@link ListFolderArg#getRecursive} set to {@code true} to keep a local - * cache of the contents of a Dropbox account, iterate through each entry in - * order and process them as follows to keep your local state in sync: For - * each {@link FileMetadata}, store the new entry at the given path in your - * local state. If the required parent folders don't exist yet, create them. - * If there's already something else at the given path, replace it and - * remove all its children. For each {@link FolderMetadata}, store the new - * entry at the given path in your local state. If the required parent - * folders don't exist yet, create them. If there's already something else - * at the given path, replace it but leave the children as they are. Check - * the new entry's {@link FolderSharingInfo#getReadOnly} and set all its - * children's read-only statuses to match. For each {@link DeletedMetadata}, - * if your local state has something at the given path, remove it and all - * its children. If there's nothing at the given path, ignore this entry. - * - */ - ListFolderResult listFolder(ListFolderArg arg) throws ListFolderErrorException, DbxException { - try { - return this.client.rpcStyle(this.client.getHost().getApi(), - "2/files/list_folder", - arg, - false, - ListFolderArg.Serializer.INSTANCE, - ListFolderResult.Serializer.INSTANCE, - ListFolderError.Serializer.INSTANCE); - } - catch (DbxWrappedException ex) { - throw new ListFolderErrorException("2/files/list_folder", ex.getRequestId(), ex.getUserMessage(), (ListFolderError) ex.getErrorValue()); - } - } - - /** - * Starts returning the contents of a folder. If the result's {@link - * ListFolderResult#getHasMore} field is {@code true}, call {@link - * DbxUserFilesRequests#listFolderContinue(String)} with the returned {@link - * ListFolderResult#getCursor} to retrieve more entries. If you're using - * {@link ListFolderArg#getRecursive} set to {@code true} to keep a local - * cache of the contents of a Dropbox account, iterate through each entry in - * order and process them as follows to keep your local state in sync: For - * each {@link FileMetadata}, store the new entry at the given path in your - * local state. If the required parent folders don't exist yet, create them. - * If there's already something else at the given path, replace it and - * remove all its children. For each {@link FolderMetadata}, store the new - * entry at the given path in your local state. If the required parent - * folders don't exist yet, create them. If there's already something else - * at the given path, replace it but leave the children as they are. Check - * the new entry's {@link FolderSharingInfo#getReadOnly} and set all its - * children's read-only statuses to match. For each {@link DeletedMetadata}, - * if your local state has something at the given path, remove it and all - * its children. If there's nothing at the given path, ignore this entry. - * - *

The default values for the optional request parameters will be used. - * See {@link ListFolderBuilder} for more details.

- * - * @param path The path to the folder you want to see the contents of. Must - * match pattern "{@code (/(.|[\\r\\n])*)?|(ns:[0-9]+(/.*)?)}" and not - * be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public ListFolderResult listFolder(String path) throws ListFolderErrorException, DbxException { - ListFolderArg _arg = new ListFolderArg(path); - return listFolder(_arg); - } - - /** - * Starts returning the contents of a folder. If the result's {@link - * ListFolderResult#getHasMore} field is {@code true}, call {@link - * DbxUserFilesRequests#listFolderContinue(String)} with the returned {@link - * ListFolderResult#getCursor} to retrieve more entries. If you're using - * {@link ListFolderArg#getRecursive} set to {@code true} to keep a local - * cache of the contents of a Dropbox account, iterate through each entry in - * order and process them as follows to keep your local state in sync: For - * each {@link FileMetadata}, store the new entry at the given path in your - * local state. If the required parent folders don't exist yet, create them. - * If there's already something else at the given path, replace it and - * remove all its children. For each {@link FolderMetadata}, store the new - * entry at the given path in your local state. If the required parent - * folders don't exist yet, create them. If there's already something else - * at the given path, replace it but leave the children as they are. Check - * the new entry's {@link FolderSharingInfo#getReadOnly} and set all its - * children's read-only statuses to match. For each {@link DeletedMetadata}, - * if your local state has something at the given path, remove it and all - * its children. If there's nothing at the given path, ignore this entry. - * - * @param path The path to the folder you want to see the contents of. Must - * match pattern "{@code (/(.|[\\r\\n])*)?|(ns:[0-9]+(/.*)?)}" and not - * be {@code null}. - * - * @return Request builder for configuring request parameters and completing - * the request. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public ListFolderBuilder listFolderBuilder(String path) { - ListFolderArg.Builder argBuilder_ = ListFolderArg.newBuilder(path); - return new ListFolderBuilder(this, argBuilder_); - } - - // - // route 2/files/list_folder/continue - // - - /** - * Once a cursor has been retrieved from {@link - * DbxUserFilesRequests#listFolder(String)}, use this to paginate through - * all files and retrieve updates to the folder, following the same rules as - * documented for {@link DbxUserFilesRequests#listFolder(String)}. - * - */ - ListFolderResult listFolderContinue(ListFolderContinueArg arg) throws ListFolderContinueErrorException, DbxException { - try { - return this.client.rpcStyle(this.client.getHost().getApi(), - "2/files/list_folder/continue", - arg, - false, - ListFolderContinueArg.Serializer.INSTANCE, - ListFolderResult.Serializer.INSTANCE, - ListFolderContinueError.Serializer.INSTANCE); - } - catch (DbxWrappedException ex) { - throw new ListFolderContinueErrorException("2/files/list_folder/continue", ex.getRequestId(), ex.getUserMessage(), (ListFolderContinueError) ex.getErrorValue()); - } - } - - /** - * Once a cursor has been retrieved from {@link - * DbxUserFilesRequests#listFolder(String)}, use this to paginate through - * all files and retrieve updates to the folder, following the same rules as - * documented for {@link DbxUserFilesRequests#listFolder(String)}. - * - * @param cursor The cursor returned by your last call to {@link - * DbxUserFilesRequests#listFolder(String)} or {@link - * DbxUserFilesRequests#listFolderContinue(String)}. Must have length of - * at least 1 and not be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public ListFolderResult listFolderContinue(String cursor) throws ListFolderContinueErrorException, DbxException { - ListFolderContinueArg _arg = new ListFolderContinueArg(cursor); - return listFolderContinue(_arg); - } - - // - // route 2/files/list_folder/get_latest_cursor - // - - /** - * A way to quickly get a cursor for the folder's state. Unlike {@link - * DbxUserFilesRequests#listFolder(String)}, {@link - * DbxUserFilesRequests#listFolderGetLatestCursor(String)} doesn't return - * any entries. This endpoint is for app which only needs to know about new - * files and modifications and doesn't need to know about files that already - * exist in Dropbox. - * - */ - ListFolderGetLatestCursorResult listFolderGetLatestCursor(ListFolderArg arg) throws ListFolderErrorException, DbxException { - try { - return this.client.rpcStyle(this.client.getHost().getApi(), - "2/files/list_folder/get_latest_cursor", - arg, - false, - ListFolderArg.Serializer.INSTANCE, - ListFolderGetLatestCursorResult.Serializer.INSTANCE, - ListFolderError.Serializer.INSTANCE); - } - catch (DbxWrappedException ex) { - throw new ListFolderErrorException("2/files/list_folder/get_latest_cursor", ex.getRequestId(), ex.getUserMessage(), (ListFolderError) ex.getErrorValue()); - } - } - - /** - * A way to quickly get a cursor for the folder's state. Unlike {@link - * DbxUserFilesRequests#listFolder(String)}, {@link - * DbxUserFilesRequests#listFolderGetLatestCursor(String)} doesn't return - * any entries. This endpoint is for app which only needs to know about new - * files and modifications and doesn't need to know about files that already - * exist in Dropbox. - * - *

The default values for the optional request parameters will be used. - * See {@link ListFolderGetLatestCursorBuilder} for more details.

- * - * @param path The path to the folder you want to see the contents of. Must - * match pattern "{@code (/(.|[\\r\\n])*)?|(ns:[0-9]+(/.*)?)}" and not - * be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public ListFolderGetLatestCursorResult listFolderGetLatestCursor(String path) throws ListFolderErrorException, DbxException { - ListFolderArg _arg = new ListFolderArg(path); - return listFolderGetLatestCursor(_arg); - } - - /** - * A way to quickly get a cursor for the folder's state. Unlike {@link - * DbxUserFilesRequests#listFolder(String)}, {@link - * DbxUserFilesRequests#listFolderGetLatestCursor(String)} doesn't return - * any entries. This endpoint is for app which only needs to know about new - * files and modifications and doesn't need to know about files that already - * exist in Dropbox. - * - * @param path The path to the folder you want to see the contents of. Must - * match pattern "{@code (/(.|[\\r\\n])*)?|(ns:[0-9]+(/.*)?)}" and not - * be {@code null}. - * - * @return Request builder for configuring request parameters and completing - * the request. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public ListFolderGetLatestCursorBuilder listFolderGetLatestCursorBuilder(String path) { - ListFolderArg.Builder argBuilder_ = ListFolderArg.newBuilder(path); - return new ListFolderGetLatestCursorBuilder(this, argBuilder_); - } - - // - // route 2/files/upload - // - - /** - * Create a new file with the contents provided in the request. Do not use - * this to upload a file larger than 150 MB. Instead, create an upload - * session with {@link DbxUserFilesRequests#uploadSessionStart(boolean)}. - * - * - * @return Uploader used to upload the request body and finish request. - */ - UploadUploader upload(CommitInfo arg) throws DbxException { - HttpRequestor.Uploader _uploader = this.client.uploadStyle(this.client.getHost().getContent(), - "2/files/upload", - arg, - false, - CommitInfo.Serializer.INSTANCE); - return new UploadUploader(_uploader); - } - - /** - * Create a new file with the contents provided in the request. Do not use - * this to upload a file larger than 150 MB. Instead, create an upload - * session with {@link DbxUserFilesRequests#uploadSessionStart(boolean)}. - * - *

The default values for the optional request parameters will be used. - * See {@link UploadBuilder} for more details.

- * - * @param path Path in the user's Dropbox to save the file. Must match - * pattern "{@code (/(.|[\\r\\n])*)|(ns:[0-9]+(/.*)?)}" and not be - * {@code null}. - * - * @return Uploader used to upload the request body and finish request. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public UploadUploader upload(String path) throws DbxException { - CommitInfo _arg = new CommitInfo(path); - return upload(_arg); - } - - /** - * Create a new file with the contents provided in the request. Do not use - * this to upload a file larger than 150 MB. Instead, create an upload - * session with {@link DbxUserFilesRequests#uploadSessionStart(boolean)}. - * - * @param path Path in the user's Dropbox to save the file. Must match - * pattern "{@code (/(.|[\\r\\n])*)|(ns:[0-9]+(/.*)?)}" and not be - * {@code null}. - * - * @return Uploader builder for configuring request parameters and - * instantiating an uploader. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public UploadBuilder uploadBuilder(String path) { - CommitInfo.Builder argBuilder_ = CommitInfo.newBuilder(path); - return new UploadBuilder(this, argBuilder_); - } - - // - // route 2/files/upload_session/append - // - - /** - * Append more data to an upload session. A single request should not upload - * more than 150 MB of file contents. - * - * - * @return Uploader used to upload the request body and finish request. - */ - UploadSessionAppendUploader uploadSessionAppend(UploadSessionCursor arg) throws DbxException { - HttpRequestor.Uploader _uploader = this.client.uploadStyle(this.client.getHost().getContent(), - "2/files/upload_session/append", - arg, - false, - UploadSessionCursor.Serializer.INSTANCE); - return new UploadSessionAppendUploader(_uploader); - } - - /** - * Append more data to an upload session. A single request should not upload - * more than 150 MB of file contents. - * - * @param sessionId The upload session ID (returned by {@link - * DbxUserFilesRequests#uploadSessionStart(boolean)}). Must not be - * {@code null}. - * @param offset The amount of data that has been uploaded so far. We use - * this to make sure upload data isn't lost or duplicated in the event - * of a network error. - * - * @return Uploader used to upload the request body and finish request. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - * - * @deprecated use {@link - * DbxUserFilesRequests#uploadSessionAppendV2(UploadSessionCursor,boolean)} - * instead. - */ - @Deprecated - public UploadSessionAppendUploader uploadSessionAppend(String sessionId, long offset) throws DbxException { - UploadSessionCursor _arg = new UploadSessionCursor(sessionId, offset); - return uploadSessionAppend(_arg); - } - - // - // route 2/files/upload_session/append_v2 - // - - /** - * Append more data to an upload session. When the parameter close is set, - * this call will close the session. A single request should not upload more - * than 150 MB of file contents. - * - * - * @return Uploader used to upload the request body and finish request. - */ - UploadSessionAppendV2Uploader uploadSessionAppendV2(UploadSessionAppendArg arg) throws DbxException { - HttpRequestor.Uploader _uploader = this.client.uploadStyle(this.client.getHost().getContent(), - "2/files/upload_session/append_v2", - arg, - false, - UploadSessionAppendArg.Serializer.INSTANCE); - return new UploadSessionAppendV2Uploader(_uploader); - } - - /** - * Append more data to an upload session. When the parameter close is set, - * this call will close the session. A single request should not upload more - * than 150 MB of file contents. - * - *

The {@code close} request parameter will default to {@code false} - * (see {@link #uploadSessionAppendV2(UploadSessionCursor,boolean)}).

- * - * @param cursor Contains the upload session ID and the offset. Must not be - * {@code null}. - * - * @return Uploader used to upload the request body and finish request. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public UploadSessionAppendV2Uploader uploadSessionAppendV2(UploadSessionCursor cursor) throws DbxException { - UploadSessionAppendArg _arg = new UploadSessionAppendArg(cursor); - return uploadSessionAppendV2(_arg); - } - - /** - * Append more data to an upload session. When the parameter close is set, - * this call will close the session. A single request should not upload more - * than 150 MB of file contents. - * - * @param cursor Contains the upload session ID and the offset. Must not be - * {@code null}. - * @param close If true, the current session will be closed, at which point - * you won't be able to call {@link - * DbxUserFilesRequests#uploadSessionAppendV2(UploadSessionCursor,boolean)} - * anymore with the current session. - * - * @return Uploader used to upload the request body and finish request. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public UploadSessionAppendV2Uploader uploadSessionAppendV2(UploadSessionCursor cursor, boolean close) throws DbxException { - UploadSessionAppendArg _arg = new UploadSessionAppendArg(cursor, close); - return uploadSessionAppendV2(_arg); - } - - // - // route 2/files/upload_session/finish - // - - /** - * Finish an upload session and save the uploaded data to the given file - * path. A single request should not upload more than 150 MB of file - * contents. - * - * - * @return Uploader used to upload the request body and finish request. - */ - UploadSessionFinishUploader uploadSessionFinish(UploadSessionFinishArg arg) throws DbxException { - HttpRequestor.Uploader _uploader = this.client.uploadStyle(this.client.getHost().getContent(), - "2/files/upload_session/finish", - arg, - false, - UploadSessionFinishArg.Serializer.INSTANCE); - return new UploadSessionFinishUploader(_uploader); - } - - /** - * Finish an upload session and save the uploaded data to the given file - * path. A single request should not upload more than 150 MB of file - * contents. - * - * @param cursor Contains the upload session ID and the offset. Must not be - * {@code null}. - * @param commit Contains the path and other optional modifiers for the - * commit. Must not be {@code null}. - * - * @return Uploader used to upload the request body and finish request. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public UploadSessionFinishUploader uploadSessionFinish(UploadSessionCursor cursor, CommitInfo commit) throws DbxException { - UploadSessionFinishArg _arg = new UploadSessionFinishArg(cursor, commit); - return uploadSessionFinish(_arg); - } - - // - // route 2/files/upload_session/start - // - - /** - * Upload sessions allow you to upload a single file in one or more - * requests, for example where the size of the file is greater than 150 MB. - * This call starts a new upload session with the given data. You can then - * use {@link - * DbxUserFilesRequests#uploadSessionAppendV2(UploadSessionCursor,boolean)} - * to add more data and {@link - * DbxUserFilesRequests#uploadSessionFinish(UploadSessionCursor,CommitInfo)} - * to save all the data to a file in Dropbox. A single request should not - * upload more than 150 MB of file contents. - * - * - * @return Uploader used to upload the request body and finish request. - */ - UploadSessionStartUploader uploadSessionStart(UploadSessionStartArg arg) throws DbxException { - HttpRequestor.Uploader _uploader = this.client.uploadStyle(this.client.getHost().getContent(), - "2/files/upload_session/start", - arg, - false, - UploadSessionStartArg.Serializer.INSTANCE); - return new UploadSessionStartUploader(_uploader); - } - - /** - * Upload sessions allow you to upload a single file in one or more - * requests, for example where the size of the file is greater than 150 MB. - * This call starts a new upload session with the given data. You can then - * use {@link - * DbxUserFilesRequests#uploadSessionAppendV2(UploadSessionCursor,boolean)} - * to add more data and {@link - * DbxUserFilesRequests#uploadSessionFinish(UploadSessionCursor,CommitInfo)} - * to save all the data to a file in Dropbox. A single request should not - * upload more than 150 MB of file contents. - * - *

The {@code close} request parameter will default to {@code false} - * (see {@link #uploadSessionStart(boolean)}).

- * - * @return Uploader used to upload the request body and finish request. - */ - public UploadSessionStartUploader uploadSessionStart() throws DbxException { - UploadSessionStartArg _arg = new UploadSessionStartArg(); - return uploadSessionStart(_arg); - } - - /** - * Upload sessions allow you to upload a single file in one or more - * requests, for example where the size of the file is greater than 150 MB. - * This call starts a new upload session with the given data. You can then - * use {@link - * DbxUserFilesRequests#uploadSessionAppendV2(UploadSessionCursor,boolean)} - * to add more data and {@link - * DbxUserFilesRequests#uploadSessionFinish(UploadSessionCursor,CommitInfo)} - * to save all the data to a file in Dropbox. A single request should not - * upload more than 150 MB of file contents. - * - * @param close If true, the current session will be closed, at which point - * you won't be able to call {@link - * DbxUserFilesRequests#uploadSessionAppendV2(UploadSessionCursor,boolean)} - * anymore with the current session. - * - * @return Uploader used to upload the request body and finish request. - */ - public UploadSessionStartUploader uploadSessionStart(boolean close) throws DbxException { - UploadSessionStartArg _arg = new UploadSessionStartArg(close); - return uploadSessionStart(_arg); - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteArg.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteArg.java deleted file mode 100644 index 1619d2e2..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteArg.java +++ /dev/null @@ -1,142 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; -import java.util.regex.Pattern; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -public class DeleteArg { - // struct files.DeleteArg (files.stone) - - protected final String path; - - /** - * - * @param path Path in the user's Dropbox to delete. Must match pattern - * "{@code (/(.|[\\r\\n])*)|(ns:[0-9]+(/.*)?)}" and not be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public DeleteArg(String path) { - if (path == null) { - throw new IllegalArgumentException("Required value for 'path' is null"); - } - if (!Pattern.matches("(/(.|[\\r\\n])*)|(ns:[0-9]+(/.*)?)", path)) { - throw new IllegalArgumentException("String 'path' does not match pattern"); - } - this.path = path; - } - - /** - * Path in the user's Dropbox to delete. - * - * @return value for this field, never {@code null}. - */ - public String getPath() { - return path; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - path - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - DeleteArg other = (DeleteArg) obj; - return (this.path == other.path) || (this.path.equals(other.path)); - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(DeleteArg value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("path"); - StoneSerializers.string().serialize(value.path, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public DeleteArg deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - DeleteArg value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - String f_path = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("path".equals(field)) { - f_path = StoneSerializers.string().deserialize(p); - } - else { - skipValue(p); - } - } - if (f_path == null) { - throw new JsonParseException(p, "Required field \"path\" missing."); - } - value = new DeleteArg(f_path); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteBatchArg.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteBatchArg.java deleted file mode 100644 index 9972ae3f..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteBatchArg.java +++ /dev/null @@ -1,143 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -class DeleteBatchArg { - // struct files.DeleteBatchArg (files.stone) - - protected final List entries; - - /** - * - * @param entries Must not contain a {@code null} item and not be {@code - * null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public DeleteBatchArg(List entries) { - if (entries == null) { - throw new IllegalArgumentException("Required value for 'entries' is null"); - } - for (DeleteArg x : entries) { - if (x == null) { - throw new IllegalArgumentException("An item in list 'entries' is null"); - } - } - this.entries = entries; - } - - /** - * - * @return value for this field, never {@code null}. - */ - public List getEntries() { - return entries; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - entries - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - DeleteBatchArg other = (DeleteBatchArg) obj; - return (this.entries == other.entries) || (this.entries.equals(other.entries)); - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(DeleteBatchArg value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("entries"); - StoneSerializers.list(DeleteArg.Serializer.INSTANCE).serialize(value.entries, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public DeleteBatchArg deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - DeleteBatchArg value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - List f_entries = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("entries".equals(field)) { - f_entries = StoneSerializers.list(DeleteArg.Serializer.INSTANCE).deserialize(p); - } - else { - skipValue(p); - } - } - if (f_entries == null) { - throw new JsonParseException(p, "Required field \"entries\" missing."); - } - value = new DeleteBatchArg(f_entries); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteBatchError.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteBatchError.java deleted file mode 100644 index 32556551..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteBatchError.java +++ /dev/null @@ -1,81 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; - -import autosaveworld.zlibs.com.dropbox.core.stone.UnionSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -public enum DeleteBatchError { - // union files.DeleteBatchError (files.stone) - /** - * There are too many write operations in user's Dropbox. Please retry this - * request. - */ - TOO_MANY_WRITE_OPERATIONS, - /** - * Catch-all used for unknown tag values returned by the Dropbox servers. - * - *

Receiving a catch-all value typically indicates this SDK version is - * not up to date. Consider updating your SDK version to handle the new - * tags.

- */ - OTHER; // *catch_all - - /** - * For internal use only. - */ - static class Serializer extends UnionSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(DeleteBatchError value, JsonGenerator g) throws IOException, JsonGenerationException { - switch (value) { - case TOO_MANY_WRITE_OPERATIONS: { - g.writeString("too_many_write_operations"); - break; - } - default: { - g.writeString("other"); - } - } - } - - @Override - public DeleteBatchError deserialize(JsonParser p) throws IOException, JsonParseException { - DeleteBatchError value; - boolean collapsed; - String tag; - if (p.getCurrentToken() == JsonToken.VALUE_STRING) { - collapsed = true; - tag = getStringValue(p); - p.nextToken(); - } - else { - collapsed = false; - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); - } - else if ("too_many_write_operations".equals(tag)) { - value = DeleteBatchError.TOO_MANY_WRITE_OPERATIONS; - } - else { - value = DeleteBatchError.OTHER; - skipFields(p); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteBatchJobStatus.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteBatchJobStatus.java deleted file mode 100644 index d0bda07f..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteBatchJobStatus.java +++ /dev/null @@ -1,358 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.UnionSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * This class is an open tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isAbc()} - * methods will return {@code true}. You can use {@link #tag()} to determine the - * tag associated with this instance. - * - *

Open unions may be extended in the future with additional tags. If a new - * tag is introduced that this SDK does not recognized, the {@link #OTHER} value - * will be used.

- */ -public final class DeleteBatchJobStatus { - // union files.DeleteBatchJobStatus (files.stone) - - /** - * Discriminating tag type for {@link DeleteBatchJobStatus}. - */ - public enum Tag { - /** - * The asynchronous job is still in progress. - */ - IN_PROGRESS, - /** - * The batch delete has finished. - */ - COMPLETE, // DeleteBatchResult - /** - * The batch delete has failed. - */ - FAILED, // DeleteBatchError - /** - * Catch-all used for unknown tag values returned by the Dropbox - * servers. - * - *

Receiving a catch-all value typically indicates this SDK version - * is not up to date. Consider updating your SDK version to handle the - * new tags.

- */ - OTHER; // *catch_all - } - - /** - * The asynchronous job is still in progress. - */ - public static final DeleteBatchJobStatus IN_PROGRESS = new DeleteBatchJobStatus(Tag.IN_PROGRESS, null, null); - /** - * Catch-all used for unknown tag values returned by the Dropbox servers. - * - *

Receiving a catch-all value typically indicates this SDK version is - * not up to date. Consider updating your SDK version to handle the new - * tags.

- */ - public static final DeleteBatchJobStatus OTHER = new DeleteBatchJobStatus(Tag.OTHER, null, null); - - private final Tag _tag; - private final DeleteBatchResult completeValue; - private final DeleteBatchError failedValue; - - /** - * - * @param completeValue The batch delete has finished. Must not be {@code - * null}. - * @param failedValue The batch delete has failed. Must not be {@code - * null}. - * @param _tag Discriminating tag for this instance. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - private DeleteBatchJobStatus(Tag _tag, DeleteBatchResult completeValue, DeleteBatchError failedValue) { - this._tag = _tag; - this.completeValue = completeValue; - this.failedValue = failedValue; - } - - /** - * Returns the tag for this instance. - * - *

This class is a tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isXyz()} - * methods will return {@code true}. Callers are recommended to use the tag - * value in a {@code switch} statement to properly handle the different - * values for this {@code DeleteBatchJobStatus}.

- * - *

If a tag returned by the server is unrecognized by this SDK, the - * {@link Tag#OTHER} value will be used.

- * - * @return the tag for this instance. - */ - public Tag tag() { - return _tag; - } - - /** - * Returns {@code true} if this instance has the tag {@link - * Tag#IN_PROGRESS}, {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link - * Tag#IN_PROGRESS}, {@code false} otherwise. - */ - public boolean isInProgress() { - return this._tag == Tag.IN_PROGRESS; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#COMPLETE}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#COMPLETE}, - * {@code false} otherwise. - */ - public boolean isComplete() { - return this._tag == Tag.COMPLETE; - } - - /** - * Returns an instance of {@code DeleteBatchJobStatus} that has its tag set - * to {@link Tag#COMPLETE}. - * - *

The batch delete has finished.

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code DeleteBatchJobStatus} with its tag set to - * {@link Tag#COMPLETE}. - * - * @throws IllegalArgumentException if {@code value} is {@code null}. - */ - public static DeleteBatchJobStatus complete(DeleteBatchResult value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - return new DeleteBatchJobStatus(Tag.COMPLETE, value, null); - } - - /** - * The batch delete has finished. - * - *

This instance must be tagged as {@link Tag#COMPLETE}.

- * - * @return The {@link DeleteBatchResult} value associated with this instance - * if {@link #isComplete} is {@code true}. - * - * @throws IllegalStateException If {@link #isComplete} is {@code false}. - */ - public DeleteBatchResult getCompleteValue() { - if (this._tag != Tag.COMPLETE) { - throw new IllegalStateException("Invalid tag: required Tag.COMPLETE, but was Tag." + this._tag.name()); - } - return completeValue; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#FAILED}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#FAILED}, - * {@code false} otherwise. - */ - public boolean isFailed() { - return this._tag == Tag.FAILED; - } - - /** - * Returns an instance of {@code DeleteBatchJobStatus} that has its tag set - * to {@link Tag#FAILED}. - * - *

The batch delete has failed.

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code DeleteBatchJobStatus} with its tag set to - * {@link Tag#FAILED}. - * - * @throws IllegalArgumentException if {@code value} is {@code null}. - */ - public static DeleteBatchJobStatus failed(DeleteBatchError value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - return new DeleteBatchJobStatus(Tag.FAILED, null, value); - } - - /** - * The batch delete has failed. - * - *

This instance must be tagged as {@link Tag#FAILED}.

- * - * @return The {@link DeleteBatchError} value associated with this instance - * if {@link #isFailed} is {@code true}. - * - * @throws IllegalStateException If {@link #isFailed} is {@code false}. - */ - public DeleteBatchError getFailedValue() { - if (this._tag != Tag.FAILED) { - throw new IllegalStateException("Invalid tag: required Tag.FAILED, but was Tag." + this._tag.name()); - } - return failedValue; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#OTHER}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#OTHER}, - * {@code false} otherwise. - */ - public boolean isOther() { - return this._tag == Tag.OTHER; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - _tag, - completeValue, - failedValue - }); - hash = (31 * super.hashCode()) + hash; - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - else if (obj instanceof DeleteBatchJobStatus) { - DeleteBatchJobStatus other = (DeleteBatchJobStatus) obj; - if (this._tag != other._tag) { - return false; - } - switch (_tag) { - case IN_PROGRESS: - return true; - case COMPLETE: - return (this.completeValue == other.completeValue) || (this.completeValue.equals(other.completeValue)); - case FAILED: - return (this.failedValue == other.failedValue) || (this.failedValue.equals(other.failedValue)); - case OTHER: - return true; - default: - return false; - } - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends UnionSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(DeleteBatchJobStatus value, JsonGenerator g) throws IOException, JsonGenerationException { - switch (value.tag()) { - case IN_PROGRESS: { - g.writeString("in_progress"); - break; - } - case COMPLETE: { - g.writeStartObject(); - writeTag("complete", g); - DeleteBatchResult.Serializer.INSTANCE.serialize(value.completeValue, g, true); - g.writeEndObject(); - break; - } - case FAILED: { - g.writeStartObject(); - writeTag("failed", g); - g.writeFieldName("failed"); - DeleteBatchError.Serializer.INSTANCE.serialize(value.failedValue, g); - g.writeEndObject(); - break; - } - default: { - g.writeString("other"); - } - } - } - - @Override - public DeleteBatchJobStatus deserialize(JsonParser p) throws IOException, JsonParseException { - DeleteBatchJobStatus value; - boolean collapsed; - String tag; - if (p.getCurrentToken() == JsonToken.VALUE_STRING) { - collapsed = true; - tag = getStringValue(p); - p.nextToken(); - } - else { - collapsed = false; - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); - } - else if ("in_progress".equals(tag)) { - value = DeleteBatchJobStatus.IN_PROGRESS; - } - else if ("complete".equals(tag)) { - DeleteBatchResult fieldValue = null; - fieldValue = DeleteBatchResult.Serializer.INSTANCE.deserialize(p, true); - value = DeleteBatchJobStatus.complete(fieldValue); - } - else if ("failed".equals(tag)) { - DeleteBatchError fieldValue = null; - expectField("failed", p); - fieldValue = DeleteBatchError.Serializer.INSTANCE.deserialize(p); - value = DeleteBatchJobStatus.failed(fieldValue); - } - else { - value = DeleteBatchJobStatus.OTHER; - skipFields(p); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteBatchResult.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteBatchResult.java deleted file mode 100644 index 708ff354..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteBatchResult.java +++ /dev/null @@ -1,143 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -public class DeleteBatchResult { - // struct files.DeleteBatchResult (files.stone) - - protected final List entries; - - /** - * - * @param entries Must not contain a {@code null} item and not be {@code - * null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public DeleteBatchResult(List entries) { - if (entries == null) { - throw new IllegalArgumentException("Required value for 'entries' is null"); - } - for (DeleteBatchResultEntry x : entries) { - if (x == null) { - throw new IllegalArgumentException("An item in list 'entries' is null"); - } - } - this.entries = entries; - } - - /** - * - * @return value for this field, never {@code null}. - */ - public List getEntries() { - return entries; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - entries - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - DeleteBatchResult other = (DeleteBatchResult) obj; - return (this.entries == other.entries) || (this.entries.equals(other.entries)); - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(DeleteBatchResult value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("entries"); - StoneSerializers.list(DeleteBatchResultEntry.Serializer.INSTANCE).serialize(value.entries, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public DeleteBatchResult deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - DeleteBatchResult value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - List f_entries = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("entries".equals(field)) { - f_entries = StoneSerializers.list(DeleteBatchResultEntry.Serializer.INSTANCE).deserialize(p); - } - else { - skipValue(p); - } - } - if (f_entries == null) { - throw new JsonParseException(p, "Required field \"entries\" missing."); - } - value = new DeleteBatchResult(f_entries); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteBatchResultEntry.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteBatchResultEntry.java deleted file mode 100644 index 66e226c2..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteBatchResultEntry.java +++ /dev/null @@ -1,278 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.UnionSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * This class is a tagged union. Tagged unions instances are always associated - * to a specific tag. This means only one of the {@code isAbc()} methods will - * return {@code true}. You can use {@link #tag()} to determine the tag - * associated with this instance. - */ -public final class DeleteBatchResultEntry { - // union files.DeleteBatchResultEntry (files.stone) - - /** - * Discriminating tag type for {@link DeleteBatchResultEntry}. - */ - public enum Tag { - SUCCESS, // DeleteResult - FAILURE; // DeleteError - } - - private final Tag _tag; - private final DeleteResult successValue; - private final DeleteError failureValue; - - /** - * - * @param successValue Must not be {@code null}. - * @param failureValue Must not be {@code null}. - * @param _tag Discriminating tag for this instance. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - private DeleteBatchResultEntry(Tag _tag, DeleteResult successValue, DeleteError failureValue) { - this._tag = _tag; - this.successValue = successValue; - this.failureValue = failureValue; - } - - /** - * Returns the tag for this instance. - * - *

This class is a tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isXyz()} - * methods will return {@code true}. Callers are recommended to use the tag - * value in a {@code switch} statement to properly handle the different - * values for this {@code DeleteBatchResultEntry}.

- * - * @return the tag for this instance. - */ - public Tag tag() { - return _tag; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#SUCCESS}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#SUCCESS}, - * {@code false} otherwise. - */ - public boolean isSuccess() { - return this._tag == Tag.SUCCESS; - } - - /** - * Returns an instance of {@code DeleteBatchResultEntry} that has its tag - * set to {@link Tag#SUCCESS}. - * - *

None

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code DeleteBatchResultEntry} with its tag set to - * {@link Tag#SUCCESS}. - * - * @throws IllegalArgumentException if {@code value} is {@code null}. - */ - public static DeleteBatchResultEntry success(DeleteResult value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - return new DeleteBatchResultEntry(Tag.SUCCESS, value, null); - } - - /** - * This instance must be tagged as {@link Tag#SUCCESS}. - * - * @return The {@link DeleteResult} value associated with this instance if - * {@link #isSuccess} is {@code true}. - * - * @throws IllegalStateException If {@link #isSuccess} is {@code false}. - */ - public DeleteResult getSuccessValue() { - if (this._tag != Tag.SUCCESS) { - throw new IllegalStateException("Invalid tag: required Tag.SUCCESS, but was Tag." + this._tag.name()); - } - return successValue; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#FAILURE}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#FAILURE}, - * {@code false} otherwise. - */ - public boolean isFailure() { - return this._tag == Tag.FAILURE; - } - - /** - * Returns an instance of {@code DeleteBatchResultEntry} that has its tag - * set to {@link Tag#FAILURE}. - * - *

None

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code DeleteBatchResultEntry} with its tag set to - * {@link Tag#FAILURE}. - * - * @throws IllegalArgumentException if {@code value} is {@code null}. - */ - public static DeleteBatchResultEntry failure(DeleteError value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - return new DeleteBatchResultEntry(Tag.FAILURE, null, value); - } - - /** - * This instance must be tagged as {@link Tag#FAILURE}. - * - * @return The {@link DeleteError} value associated with this instance if - * {@link #isFailure} is {@code true}. - * - * @throws IllegalStateException If {@link #isFailure} is {@code false}. - */ - public DeleteError getFailureValue() { - if (this._tag != Tag.FAILURE) { - throw new IllegalStateException("Invalid tag: required Tag.FAILURE, but was Tag." + this._tag.name()); - } - return failureValue; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - _tag, - successValue, - failureValue - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - else if (obj instanceof DeleteBatchResultEntry) { - DeleteBatchResultEntry other = (DeleteBatchResultEntry) obj; - if (this._tag != other._tag) { - return false; - } - switch (_tag) { - case SUCCESS: - return (this.successValue == other.successValue) || (this.successValue.equals(other.successValue)); - case FAILURE: - return (this.failureValue == other.failureValue) || (this.failureValue.equals(other.failureValue)); - default: - return false; - } - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends UnionSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(DeleteBatchResultEntry value, JsonGenerator g) throws IOException, JsonGenerationException { - switch (value.tag()) { - case SUCCESS: { - g.writeStartObject(); - writeTag("success", g); - DeleteResult.Serializer.INSTANCE.serialize(value.successValue, g, true); - g.writeEndObject(); - break; - } - case FAILURE: { - g.writeStartObject(); - writeTag("failure", g); - g.writeFieldName("failure"); - DeleteError.Serializer.INSTANCE.serialize(value.failureValue, g); - g.writeEndObject(); - break; - } - default: { - throw new IllegalArgumentException("Unrecognized tag: " + value.tag()); - } - } - } - - @Override - public DeleteBatchResultEntry deserialize(JsonParser p) throws IOException, JsonParseException { - DeleteBatchResultEntry value; - boolean collapsed; - String tag; - if (p.getCurrentToken() == JsonToken.VALUE_STRING) { - collapsed = true; - tag = getStringValue(p); - p.nextToken(); - } - else { - collapsed = false; - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); - } - else if ("success".equals(tag)) { - DeleteResult fieldValue = null; - fieldValue = DeleteResult.Serializer.INSTANCE.deserialize(p, true); - value = DeleteBatchResultEntry.success(fieldValue); - } - else if ("failure".equals(tag)) { - DeleteError fieldValue = null; - expectField("failure", p); - fieldValue = DeleteError.Serializer.INSTANCE.deserialize(p); - value = DeleteBatchResultEntry.failure(fieldValue); - } - else { - throw new JsonParseException(p, "Unknown tag: " + tag); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteError.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteError.java deleted file mode 100644 index c8854523..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteError.java +++ /dev/null @@ -1,319 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.UnionSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * This class is an open tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isAbc()} - * methods will return {@code true}. You can use {@link #tag()} to determine the - * tag associated with this instance. - * - *

Open unions may be extended in the future with additional tags. If a new - * tag is introduced that this SDK does not recognized, the {@link #OTHER} value - * will be used.

- */ -public final class DeleteError { - // union files.DeleteError (files.stone) - - /** - * Discriminating tag type for {@link DeleteError}. - */ - public enum Tag { - PATH_LOOKUP, // LookupError - PATH_WRITE, // WriteError - /** - * Catch-all used for unknown tag values returned by the Dropbox - * servers. - * - *

Receiving a catch-all value typically indicates this SDK version - * is not up to date. Consider updating your SDK version to handle the - * new tags.

- */ - OTHER; // *catch_all - } - - /** - * Catch-all used for unknown tag values returned by the Dropbox servers. - * - *

Receiving a catch-all value typically indicates this SDK version is - * not up to date. Consider updating your SDK version to handle the new - * tags.

- */ - public static final DeleteError OTHER = new DeleteError(Tag.OTHER, null, null); - - private final Tag _tag; - private final LookupError pathLookupValue; - private final WriteError pathWriteValue; - - /** - * - * @param pathLookupValue Must not be {@code null}. - * @param pathWriteValue Must not be {@code null}. - * @param _tag Discriminating tag for this instance. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - private DeleteError(Tag _tag, LookupError pathLookupValue, WriteError pathWriteValue) { - this._tag = _tag; - this.pathLookupValue = pathLookupValue; - this.pathWriteValue = pathWriteValue; - } - - /** - * Returns the tag for this instance. - * - *

This class is a tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isXyz()} - * methods will return {@code true}. Callers are recommended to use the tag - * value in a {@code switch} statement to properly handle the different - * values for this {@code DeleteError}.

- * - *

If a tag returned by the server is unrecognized by this SDK, the - * {@link Tag#OTHER} value will be used.

- * - * @return the tag for this instance. - */ - public Tag tag() { - return _tag; - } - - /** - * Returns {@code true} if this instance has the tag {@link - * Tag#PATH_LOOKUP}, {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link - * Tag#PATH_LOOKUP}, {@code false} otherwise. - */ - public boolean isPathLookup() { - return this._tag == Tag.PATH_LOOKUP; - } - - /** - * Returns an instance of {@code DeleteError} that has its tag set to {@link - * Tag#PATH_LOOKUP}. - * - *

None

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code DeleteError} with its tag set to {@link - * Tag#PATH_LOOKUP}. - * - * @throws IllegalArgumentException if {@code value} is {@code null}. - */ - public static DeleteError pathLookup(LookupError value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - return new DeleteError(Tag.PATH_LOOKUP, value, null); - } - - /** - * This instance must be tagged as {@link Tag#PATH_LOOKUP}. - * - * @return The {@link LookupError} value associated with this instance if - * {@link #isPathLookup} is {@code true}. - * - * @throws IllegalStateException If {@link #isPathLookup} is {@code false}. - */ - public LookupError getPathLookupValue() { - if (this._tag != Tag.PATH_LOOKUP) { - throw new IllegalStateException("Invalid tag: required Tag.PATH_LOOKUP, but was Tag." + this._tag.name()); - } - return pathLookupValue; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#PATH_WRITE}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link - * Tag#PATH_WRITE}, {@code false} otherwise. - */ - public boolean isPathWrite() { - return this._tag == Tag.PATH_WRITE; - } - - /** - * Returns an instance of {@code DeleteError} that has its tag set to {@link - * Tag#PATH_WRITE}. - * - *

None

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code DeleteError} with its tag set to {@link - * Tag#PATH_WRITE}. - * - * @throws IllegalArgumentException if {@code value} is {@code null}. - */ - public static DeleteError pathWrite(WriteError value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - return new DeleteError(Tag.PATH_WRITE, null, value); - } - - /** - * This instance must be tagged as {@link Tag#PATH_WRITE}. - * - * @return The {@link WriteError} value associated with this instance if - * {@link #isPathWrite} is {@code true}. - * - * @throws IllegalStateException If {@link #isPathWrite} is {@code false}. - */ - public WriteError getPathWriteValue() { - if (this._tag != Tag.PATH_WRITE) { - throw new IllegalStateException("Invalid tag: required Tag.PATH_WRITE, but was Tag." + this._tag.name()); - } - return pathWriteValue; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#OTHER}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#OTHER}, - * {@code false} otherwise. - */ - public boolean isOther() { - return this._tag == Tag.OTHER; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - _tag, - pathLookupValue, - pathWriteValue - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - else if (obj instanceof DeleteError) { - DeleteError other = (DeleteError) obj; - if (this._tag != other._tag) { - return false; - } - switch (_tag) { - case PATH_LOOKUP: - return (this.pathLookupValue == other.pathLookupValue) || (this.pathLookupValue.equals(other.pathLookupValue)); - case PATH_WRITE: - return (this.pathWriteValue == other.pathWriteValue) || (this.pathWriteValue.equals(other.pathWriteValue)); - case OTHER: - return true; - default: - return false; - } - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends UnionSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(DeleteError value, JsonGenerator g) throws IOException, JsonGenerationException { - switch (value.tag()) { - case PATH_LOOKUP: { - g.writeStartObject(); - writeTag("path_lookup", g); - g.writeFieldName("path_lookup"); - LookupError.Serializer.INSTANCE.serialize(value.pathLookupValue, g); - g.writeEndObject(); - break; - } - case PATH_WRITE: { - g.writeStartObject(); - writeTag("path_write", g); - g.writeFieldName("path_write"); - WriteError.Serializer.INSTANCE.serialize(value.pathWriteValue, g); - g.writeEndObject(); - break; - } - default: { - g.writeString("other"); - } - } - } - - @Override - public DeleteError deserialize(JsonParser p) throws IOException, JsonParseException { - DeleteError value; - boolean collapsed; - String tag; - if (p.getCurrentToken() == JsonToken.VALUE_STRING) { - collapsed = true; - tag = getStringValue(p); - p.nextToken(); - } - else { - collapsed = false; - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); - } - else if ("path_lookup".equals(tag)) { - LookupError fieldValue = null; - expectField("path_lookup", p); - fieldValue = LookupError.Serializer.INSTANCE.deserialize(p); - value = DeleteError.pathLookup(fieldValue); - } - else if ("path_write".equals(tag)) { - WriteError fieldValue = null; - expectField("path_write", p); - fieldValue = WriteError.Serializer.INSTANCE.deserialize(p); - value = DeleteError.pathWrite(fieldValue); - } - else { - value = DeleteError.OTHER; - skipFields(p); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteErrorException.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteErrorException.java deleted file mode 100644 index 360485b4..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteErrorException.java +++ /dev/null @@ -1,35 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated by Stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import autosaveworld.zlibs.com.dropbox.core.DbxApiException; -import autosaveworld.zlibs.com.dropbox.core.LocalizedText; - -/** - * Exception thrown when the server responds with a {@link DeleteError} error. - * - *

This exception is raised by {@link DbxUserFilesRequests#delete(String)} - * and {@link DbxUserFilesRequests#permanentlyDelete(String)}.

- */ -public class DeleteErrorException extends DbxApiException { - // exception for routes: - // 2/files/delete - // 2/files/permanently_delete - - private static final long serialVersionUID = 0L; - - /** - * The error reported by {@link DbxUserFilesRequests#delete(String)} and - * {@link DbxUserFilesRequests#permanentlyDelete(String)}. - */ - public final DeleteError errorValue; - - public DeleteErrorException(String routeName, String requestId, LocalizedText userMessage, DeleteError errorValue) { - super(requestId, userMessage, buildMessage(routeName, userMessage, errorValue)); - if (errorValue == null) { - throw new NullPointerException("errorValue"); - } - this.errorValue = errorValue; - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteResult.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteResult.java deleted file mode 100644 index b49094bd..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeleteResult.java +++ /dev/null @@ -1,135 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -public class DeleteResult { - // struct files.DeleteResult (files.stone) - - protected final Metadata metadata; - - /** - * - * @param metadata Must not be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public DeleteResult(Metadata metadata) { - if (metadata == null) { - throw new IllegalArgumentException("Required value for 'metadata' is null"); - } - this.metadata = metadata; - } - - /** - * - * @return value for this field, never {@code null}. - */ - public Metadata getMetadata() { - return metadata; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - metadata - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - DeleteResult other = (DeleteResult) obj; - return (this.metadata == other.metadata) || (this.metadata.equals(other.metadata)); - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(DeleteResult value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("metadata"); - Metadata.Serializer.INSTANCE.serialize(value.metadata, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public DeleteResult deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - DeleteResult value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - Metadata f_metadata = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("metadata".equals(field)) { - f_metadata = Metadata.Serializer.INSTANCE.deserialize(p); - } - else { - skipValue(p); - } - } - if (f_metadata == null) { - throw new JsonParseException(p, "Required field \"metadata\" missing."); - } - value = new DeleteResult(f_metadata); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeletedMetadata.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeletedMetadata.java deleted file mode 100644 index 1f937064..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/DeletedMetadata.java +++ /dev/null @@ -1,321 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * Indicates that there used to be a file or folder at this path, but it no - * longer exists. - */ -public class DeletedMetadata extends Metadata { - // struct files.DeletedMetadata (files.stone) - - - /** - * Indicates that there used to be a file or folder at this path, but it no - * longer exists. - * - *

Use {@link newBuilder} to create instances of this class without - * specifying values for all optional fields.

- * - * @param name The last component of the path (including extension). This - * never contains a slash. Must not be {@code null}. - * @param pathLower The lowercased full path in the user's Dropbox. This - * always starts with a slash. This field will be null if the file or - * folder is not mounted. - * @param pathDisplay The cased path to be used for display purposes only. - * In rare instances the casing will not correctly match the user's - * filesystem, but this behavior will match the path provided in the - * Core API v1. Changes to the casing of paths won't be returned by - * {@link DbxUserFilesRequests#listFolderContinue(String)}. This field - * will be null if the file or folder is not mounted. - * @param parentSharedFolderId Deprecated. Please use {@link - * FileSharingInfo#getParentSharedFolderId} or {@link - * FolderSharingInfo#getParentSharedFolderId} instead. Must match - * pattern "{@code [-_0-9a-zA-Z:]+}". - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public DeletedMetadata(String name, String pathLower, String pathDisplay, String parentSharedFolderId) { - super(name, pathLower, pathDisplay, parentSharedFolderId); - } - - /** - * Indicates that there used to be a file or folder at this path, but it no - * longer exists. - * - *

The default values for unset fields will be used.

- * - * @param name The last component of the path (including extension). This - * never contains a slash. Must not be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public DeletedMetadata(String name) { - this(name, null, null, null); - } - - /** - * The last component of the path (including extension). This never contains - * a slash. - * - * @return value for this field, never {@code null}. - */ - public String getName() { - return name; - } - - /** - * The lowercased full path in the user's Dropbox. This always starts with a - * slash. This field will be null if the file or folder is not mounted. - * - * @return value for this field, or {@code null} if not present. - */ - public String getPathLower() { - return pathLower; - } - - /** - * The cased path to be used for display purposes only. In rare instances - * the casing will not correctly match the user's filesystem, but this - * behavior will match the path provided in the Core API v1. Changes to the - * casing of paths won't be returned by {@link - * DbxUserFilesRequests#listFolderContinue(String)}. This field will be null - * if the file or folder is not mounted. - * - * @return value for this field, or {@code null} if not present. - */ - public String getPathDisplay() { - return pathDisplay; - } - - /** - * Deprecated. Please use {@link FileSharingInfo#getParentSharedFolderId} or - * {@link FolderSharingInfo#getParentSharedFolderId} instead. - * - * @return value for this field, or {@code null} if not present. - */ - public String getParentSharedFolderId() { - return parentSharedFolderId; - } - - /** - * Returns a new builder for creating an instance of this class. - * - * @param name The last component of the path (including extension). This - * never contains a slash. Must not be {@code null}. - * - * @return builder for this class. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public static Builder newBuilder(String name) { - return new Builder(name); - } - - /** - * Builder for {@link DeletedMetadata}. - */ - public static class Builder extends Metadata.Builder { - - protected Builder(String name) { - super(name); - } - - /** - * Set value for optional field. - * - * @param pathLower The lowercased full path in the user's Dropbox. - * This always starts with a slash. This field will be null if the - * file or folder is not mounted. - * - * @return this builder - */ - public Builder withPathLower(String pathLower) { - super.withPathLower(pathLower); - return this; - } - - /** - * Set value for optional field. - * - * @param pathDisplay The cased path to be used for display purposes - * only. In rare instances the casing will not correctly match the - * user's filesystem, but this behavior will match the path provided - * in the Core API v1. Changes to the casing of paths won't be - * returned by {@link - * DbxUserFilesRequests#listFolderContinue(String)}. This field will - * be null if the file or folder is not mounted. - * - * @return this builder - */ - public Builder withPathDisplay(String pathDisplay) { - super.withPathDisplay(pathDisplay); - return this; - } - - /** - * Set value for optional field. - * - * @param parentSharedFolderId Deprecated. Please use {@link - * FileSharingInfo#getParentSharedFolderId} or {@link - * FolderSharingInfo#getParentSharedFolderId} instead. Must match - * pattern "{@code [-_0-9a-zA-Z:]+}". - * - * @return this builder - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public Builder withParentSharedFolderId(String parentSharedFolderId) { - super.withParentSharedFolderId(parentSharedFolderId); - return this; - } - - /** - * Builds an instance of {@link DeletedMetadata} configured with this - * builder's values - * - * @return new instance of {@link DeletedMetadata} - */ - public DeletedMetadata build() { - return new DeletedMetadata(name, pathLower, pathDisplay, parentSharedFolderId); - } - } - - @Override - public int hashCode() { - // attempt to deal with inheritance - return getClass().toString().hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - DeletedMetadata other = (DeletedMetadata) obj; - return ((this.name == other.name) || (this.name.equals(other.name))) - && ((this.pathLower == other.pathLower) || (this.pathLower != null && this.pathLower.equals(other.pathLower))) - && ((this.pathDisplay == other.pathDisplay) || (this.pathDisplay != null && this.pathDisplay.equals(other.pathDisplay))) - && ((this.parentSharedFolderId == other.parentSharedFolderId) || (this.parentSharedFolderId != null && this.parentSharedFolderId.equals(other.parentSharedFolderId))) - ; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(DeletedMetadata value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - writeTag("deleted", g); - g.writeFieldName("name"); - StoneSerializers.string().serialize(value.name, g); - if (value.pathLower != null) { - g.writeFieldName("path_lower"); - StoneSerializers.nullable(StoneSerializers.string()).serialize(value.pathLower, g); - } - if (value.pathDisplay != null) { - g.writeFieldName("path_display"); - StoneSerializers.nullable(StoneSerializers.string()).serialize(value.pathDisplay, g); - } - if (value.parentSharedFolderId != null) { - g.writeFieldName("parent_shared_folder_id"); - StoneSerializers.nullable(StoneSerializers.string()).serialize(value.parentSharedFolderId, g); - } - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public DeletedMetadata deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - DeletedMetadata value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - if ("deleted".equals(tag)) { - tag = null; - } - } - if (tag == null) { - String f_name = null; - String f_pathLower = null; - String f_pathDisplay = null; - String f_parentSharedFolderId = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("name".equals(field)) { - f_name = StoneSerializers.string().deserialize(p); - } - else if ("path_lower".equals(field)) { - f_pathLower = StoneSerializers.nullable(StoneSerializers.string()).deserialize(p); - } - else if ("path_display".equals(field)) { - f_pathDisplay = StoneSerializers.nullable(StoneSerializers.string()).deserialize(p); - } - else if ("parent_shared_folder_id".equals(field)) { - f_parentSharedFolderId = StoneSerializers.nullable(StoneSerializers.string()).deserialize(p); - } - else { - skipValue(p); - } - } - if (f_name == null) { - throw new JsonParseException(p, "Required field \"name\" missing."); - } - value = new DeletedMetadata(f_name, f_pathLower, f_pathDisplay, f_parentSharedFolderId); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/Dimensions.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/Dimensions.java deleted file mode 100644 index ad19dbe9..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/Dimensions.java +++ /dev/null @@ -1,159 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * Dimensions for a photo or video. - */ -public class Dimensions { - // struct files.Dimensions (files.stone) - - protected final long height; - protected final long width; - - /** - * Dimensions for a photo or video. - * - * @param height Height of the photo/video. - * @param width Width of the photo/video. - */ - public Dimensions(long height, long width) { - this.height = height; - this.width = width; - } - - /** - * Height of the photo/video. - * - * @return value for this field. - */ - public long getHeight() { - return height; - } - - /** - * Width of the photo/video. - * - * @return value for this field. - */ - public long getWidth() { - return width; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - height, - width - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - Dimensions other = (Dimensions) obj; - return (this.height == other.height) - && (this.width == other.width) - ; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(Dimensions value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("height"); - StoneSerializers.uInt64().serialize(value.height, g); - g.writeFieldName("width"); - StoneSerializers.uInt64().serialize(value.width, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public Dimensions deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - Dimensions value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - Long f_height = null; - Long f_width = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("height".equals(field)) { - f_height = StoneSerializers.uInt64().deserialize(p); - } - else if ("width".equals(field)) { - f_width = StoneSerializers.uInt64().deserialize(p); - } - else { - skipValue(p); - } - } - if (f_height == null) { - throw new JsonParseException(p, "Required field \"height\" missing."); - } - if (f_width == null) { - throw new JsonParseException(p, "Required field \"width\" missing."); - } - value = new Dimensions(f_height, f_width); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/FileMetadata.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/FileMetadata.java deleted file mode 100644 index d0c63fbb..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/FileMetadata.java +++ /dev/null @@ -1,721 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.regex.Pattern; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.dropbox.core.util.LangUtil; -import autosaveworld.zlibs.com.dropbox.core.v2.properties.PropertyGroup; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -public class FileMetadata extends Metadata { - // struct files.FileMetadata (files.stone) - - protected final String id; - protected final Date clientModified; - protected final Date serverModified; - protected final String rev; - protected final long size; - protected final MediaInfo mediaInfo; - protected final FileSharingInfo sharingInfo; - protected final List propertyGroups; - protected final Boolean hasExplicitSharedMembers; - - /** - * Use {@link newBuilder} to create instances of this class without - * specifying values for all optional fields. - * - * @param name The last component of the path (including extension). This - * never contains a slash. Must not be {@code null}. - * @param id A unique identifier for the file. Must have length of at least - * 1 and not be {@code null}. - * @param clientModified For files, this is the modification time set by - * the desktop client when the file was added to Dropbox. Since this - * time is not verified (the Dropbox server stores whatever the desktop - * client sends up), this should only be used for display purposes (such - * as sorting) and not, for example, to determine if a file has changed - * or not. Must not be {@code null}. - * @param serverModified The last time the file was modified on Dropbox. - * Must not be {@code null}. - * @param rev A unique identifier for the current revision of a file. This - * field is the same rev as elsewhere in the API and can be used to - * detect changes and avoid conflicts. Must have length of at least 9, - * match pattern "{@code [0-9a-f]+}", and not be {@code null}. - * @param size The file size in bytes. - * @param pathLower The lowercased full path in the user's Dropbox. This - * always starts with a slash. This field will be null if the file or - * folder is not mounted. - * @param pathDisplay The cased path to be used for display purposes only. - * In rare instances the casing will not correctly match the user's - * filesystem, but this behavior will match the path provided in the - * Core API v1. Changes to the casing of paths won't be returned by - * {@link DbxUserFilesRequests#listFolderContinue(String)}. This field - * will be null if the file or folder is not mounted. - * @param parentSharedFolderId Deprecated. Please use {@link - * FileSharingInfo#getParentSharedFolderId} or {@link - * FolderSharingInfo#getParentSharedFolderId} instead. Must match - * pattern "{@code [-_0-9a-zA-Z:]+}". - * @param mediaInfo Additional information if the file is a photo or video. - * @param sharingInfo Set if this file is contained in a shared folder. - * @param propertyGroups Additional information if the file has custom - * properties with the property template specified. Must not contain a - * {@code null} item. - * @param hasExplicitSharedMembers This flag will only be present if - * include_has_explicit_shared_members is true in {@link - * DbxUserFilesRequests#listFolder(String)} or {@link - * DbxUserFilesRequests#getMetadata(String)}. If this flag is present, - * it will be true if this file has any explicit shared members. This - * is different from sharing_info in that this could be true in the - * case where a file has explicit members but is not contained within a - * shared folder. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public FileMetadata(String name, String id, Date clientModified, Date serverModified, String rev, long size, String pathLower, String pathDisplay, String parentSharedFolderId, MediaInfo mediaInfo, FileSharingInfo sharingInfo, List propertyGroups, Boolean hasExplicitSharedMembers) { - super(name, pathLower, pathDisplay, parentSharedFolderId); - if (id == null) { - throw new IllegalArgumentException("Required value for 'id' is null"); - } - if (id.length() < 1) { - throw new IllegalArgumentException("String 'id' is shorter than 1"); - } - this.id = id; - if (clientModified == null) { - throw new IllegalArgumentException("Required value for 'clientModified' is null"); - } - this.clientModified = LangUtil.truncateMillis(clientModified); - if (serverModified == null) { - throw new IllegalArgumentException("Required value for 'serverModified' is null"); - } - this.serverModified = LangUtil.truncateMillis(serverModified); - if (rev == null) { - throw new IllegalArgumentException("Required value for 'rev' is null"); - } - if (rev.length() < 9) { - throw new IllegalArgumentException("String 'rev' is shorter than 9"); - } - if (!Pattern.matches("[0-9a-f]+", rev)) { - throw new IllegalArgumentException("String 'rev' does not match pattern"); - } - this.rev = rev; - this.size = size; - this.mediaInfo = mediaInfo; - this.sharingInfo = sharingInfo; - if (propertyGroups != null) { - for (PropertyGroup x : propertyGroups) { - if (x == null) { - throw new IllegalArgumentException("An item in list 'propertyGroups' is null"); - } - } - } - this.propertyGroups = propertyGroups; - this.hasExplicitSharedMembers = hasExplicitSharedMembers; - } - - /** - * None - * - *

The default values for unset fields will be used.

- * - * @param name The last component of the path (including extension). This - * never contains a slash. Must not be {@code null}. - * @param id A unique identifier for the file. Must have length of at least - * 1 and not be {@code null}. - * @param clientModified For files, this is the modification time set by - * the desktop client when the file was added to Dropbox. Since this - * time is not verified (the Dropbox server stores whatever the desktop - * client sends up), this should only be used for display purposes (such - * as sorting) and not, for example, to determine if a file has changed - * or not. Must not be {@code null}. - * @param serverModified The last time the file was modified on Dropbox. - * Must not be {@code null}. - * @param rev A unique identifier for the current revision of a file. This - * field is the same rev as elsewhere in the API and can be used to - * detect changes and avoid conflicts. Must have length of at least 9, - * match pattern "{@code [0-9a-f]+}", and not be {@code null}. - * @param size The file size in bytes. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public FileMetadata(String name, String id, Date clientModified, Date serverModified, String rev, long size) { - this(name, id, clientModified, serverModified, rev, size, null, null, null, null, null, null, null); - } - - /** - * The last component of the path (including extension). This never contains - * a slash. - * - * @return value for this field, never {@code null}. - */ - public String getName() { - return name; - } - - /** - * A unique identifier for the file. - * - * @return value for this field, never {@code null}. - */ - public String getId() { - return id; - } - - /** - * For files, this is the modification time set by the desktop client when - * the file was added to Dropbox. Since this time is not verified (the - * Dropbox server stores whatever the desktop client sends up), this should - * only be used for display purposes (such as sorting) and not, for example, - * to determine if a file has changed or not. - * - * @return value for this field, never {@code null}. - */ - public Date getClientModified() { - return clientModified; - } - - /** - * The last time the file was modified on Dropbox. - * - * @return value for this field, never {@code null}. - */ - public Date getServerModified() { - return serverModified; - } - - /** - * A unique identifier for the current revision of a file. This field is the - * same rev as elsewhere in the API and can be used to detect changes and - * avoid conflicts. - * - * @return value for this field, never {@code null}. - */ - public String getRev() { - return rev; - } - - /** - * The file size in bytes. - * - * @return value for this field. - */ - public long getSize() { - return size; - } - - /** - * The lowercased full path in the user's Dropbox. This always starts with a - * slash. This field will be null if the file or folder is not mounted. - * - * @return value for this field, or {@code null} if not present. - */ - public String getPathLower() { - return pathLower; - } - - /** - * The cased path to be used for display purposes only. In rare instances - * the casing will not correctly match the user's filesystem, but this - * behavior will match the path provided in the Core API v1. Changes to the - * casing of paths won't be returned by {@link - * DbxUserFilesRequests#listFolderContinue(String)}. This field will be null - * if the file or folder is not mounted. - * - * @return value for this field, or {@code null} if not present. - */ - public String getPathDisplay() { - return pathDisplay; - } - - /** - * Deprecated. Please use {@link FileSharingInfo#getParentSharedFolderId} or - * {@link FolderSharingInfo#getParentSharedFolderId} instead. - * - * @return value for this field, or {@code null} if not present. - */ - public String getParentSharedFolderId() { - return parentSharedFolderId; - } - - /** - * Additional information if the file is a photo or video. - * - * @return value for this field, or {@code null} if not present. - */ - public MediaInfo getMediaInfo() { - return mediaInfo; - } - - /** - * Set if this file is contained in a shared folder. - * - * @return value for this field, or {@code null} if not present. - */ - public FileSharingInfo getSharingInfo() { - return sharingInfo; - } - - /** - * Additional information if the file has custom properties with the - * property template specified. - * - * @return value for this field, or {@code null} if not present. - */ - public List getPropertyGroups() { - return propertyGroups; - } - - /** - * This flag will only be present if include_has_explicit_shared_members is - * true in {@link DbxUserFilesRequests#listFolder(String)} or {@link - * DbxUserFilesRequests#getMetadata(String)}. If this flag is present, it - * will be true if this file has any explicit shared members. This is - * different from sharing_info in that this could be true in the case where - * a file has explicit members but is not contained within a shared folder. - * - * @return value for this field, or {@code null} if not present. - */ - public Boolean getHasExplicitSharedMembers() { - return hasExplicitSharedMembers; - } - - /** - * Returns a new builder for creating an instance of this class. - * - * @param name The last component of the path (including extension). This - * never contains a slash. Must not be {@code null}. - * @param id A unique identifier for the file. Must have length of at least - * 1 and not be {@code null}. - * @param clientModified For files, this is the modification time set by - * the desktop client when the file was added to Dropbox. Since this - * time is not verified (the Dropbox server stores whatever the desktop - * client sends up), this should only be used for display purposes (such - * as sorting) and not, for example, to determine if a file has changed - * or not. Must not be {@code null}. - * @param serverModified The last time the file was modified on Dropbox. - * Must not be {@code null}. - * @param rev A unique identifier for the current revision of a file. This - * field is the same rev as elsewhere in the API and can be used to - * detect changes and avoid conflicts. Must have length of at least 9, - * match pattern "{@code [0-9a-f]+}", and not be {@code null}. - * @param size The file size in bytes. - * - * @return builder for this class. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public static Builder newBuilder(String name, String id, Date clientModified, Date serverModified, String rev, long size) { - return new Builder(name, id, clientModified, serverModified, rev, size); - } - - /** - * Builder for {@link FileMetadata}. - */ - public static class Builder extends Metadata.Builder { - protected final String id; - protected final Date clientModified; - protected final Date serverModified; - protected final String rev; - protected final long size; - - protected MediaInfo mediaInfo; - protected FileSharingInfo sharingInfo; - protected List propertyGroups; - protected Boolean hasExplicitSharedMembers; - - protected Builder(String name, String id, Date clientModified, Date serverModified, String rev, long size) { - super(name); - if (id == null) { - throw new IllegalArgumentException("Required value for 'id' is null"); - } - if (id.length() < 1) { - throw new IllegalArgumentException("String 'id' is shorter than 1"); - } - this.id = id; - if (clientModified == null) { - throw new IllegalArgumentException("Required value for 'clientModified' is null"); - } - this.clientModified = LangUtil.truncateMillis(clientModified); - if (serverModified == null) { - throw new IllegalArgumentException("Required value for 'serverModified' is null"); - } - this.serverModified = LangUtil.truncateMillis(serverModified); - if (rev == null) { - throw new IllegalArgumentException("Required value for 'rev' is null"); - } - if (rev.length() < 9) { - throw new IllegalArgumentException("String 'rev' is shorter than 9"); - } - if (!Pattern.matches("[0-9a-f]+", rev)) { - throw new IllegalArgumentException("String 'rev' does not match pattern"); - } - this.rev = rev; - this.size = size; - this.mediaInfo = null; - this.sharingInfo = null; - this.propertyGroups = null; - this.hasExplicitSharedMembers = null; - } - - /** - * Set value for optional field. - * - * @param mediaInfo Additional information if the file is a photo or - * video. - * - * @return this builder - */ - public Builder withMediaInfo(MediaInfo mediaInfo) { - this.mediaInfo = mediaInfo; - return this; - } - - /** - * Set value for optional field. - * - * @param sharingInfo Set if this file is contained in a shared folder. - * - * @return this builder - */ - public Builder withSharingInfo(FileSharingInfo sharingInfo) { - this.sharingInfo = sharingInfo; - return this; - } - - /** - * Set value for optional field. - * - * @param propertyGroups Additional information if the file has custom - * properties with the property template specified. Must not contain - * a {@code null} item. - * - * @return this builder - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public Builder withPropertyGroups(List propertyGroups) { - if (propertyGroups != null) { - for (PropertyGroup x : propertyGroups) { - if (x == null) { - throw new IllegalArgumentException("An item in list 'propertyGroups' is null"); - } - } - } - this.propertyGroups = propertyGroups; - return this; - } - - /** - * Set value for optional field. - * - * @param hasExplicitSharedMembers This flag will only be present if - * include_has_explicit_shared_members is true in {@link - * DbxUserFilesRequests#listFolder(String)} or {@link - * DbxUserFilesRequests#getMetadata(String)}. If this flag is - * present, it will be true if this file has any explicit shared - * members. This is different from sharing_info in that this could - * be true in the case where a file has explicit members but is not - * contained within a shared folder. - * - * @return this builder - */ - public Builder withHasExplicitSharedMembers(Boolean hasExplicitSharedMembers) { - this.hasExplicitSharedMembers = hasExplicitSharedMembers; - return this; - } - - /** - * Set value for optional field. - * - * @param pathLower The lowercased full path in the user's Dropbox. - * This always starts with a slash. This field will be null if the - * file or folder is not mounted. - * - * @return this builder - */ - public Builder withPathLower(String pathLower) { - super.withPathLower(pathLower); - return this; - } - - /** - * Set value for optional field. - * - * @param pathDisplay The cased path to be used for display purposes - * only. In rare instances the casing will not correctly match the - * user's filesystem, but this behavior will match the path provided - * in the Core API v1. Changes to the casing of paths won't be - * returned by {@link - * DbxUserFilesRequests#listFolderContinue(String)}. This field will - * be null if the file or folder is not mounted. - * - * @return this builder - */ - public Builder withPathDisplay(String pathDisplay) { - super.withPathDisplay(pathDisplay); - return this; - } - - /** - * Set value for optional field. - * - * @param parentSharedFolderId Deprecated. Please use {@link - * FileSharingInfo#getParentSharedFolderId} or {@link - * FolderSharingInfo#getParentSharedFolderId} instead. Must match - * pattern "{@code [-_0-9a-zA-Z:]+}". - * - * @return this builder - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public Builder withParentSharedFolderId(String parentSharedFolderId) { - super.withParentSharedFolderId(parentSharedFolderId); - return this; - } - - /** - * Builds an instance of {@link FileMetadata} configured with this - * builder's values - * - * @return new instance of {@link FileMetadata} - */ - public FileMetadata build() { - return new FileMetadata(name, id, clientModified, serverModified, rev, size, pathLower, pathDisplay, parentSharedFolderId, mediaInfo, sharingInfo, propertyGroups, hasExplicitSharedMembers); - } - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - id, - clientModified, - serverModified, - rev, - size, - mediaInfo, - sharingInfo, - propertyGroups, - hasExplicitSharedMembers - }); - hash = (31 * super.hashCode()) + hash; - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - FileMetadata other = (FileMetadata) obj; - return ((this.name == other.name) || (this.name.equals(other.name))) - && ((this.id == other.id) || (this.id.equals(other.id))) - && ((this.clientModified == other.clientModified) || (this.clientModified.equals(other.clientModified))) - && ((this.serverModified == other.serverModified) || (this.serverModified.equals(other.serverModified))) - && ((this.rev == other.rev) || (this.rev.equals(other.rev))) - && (this.size == other.size) - && ((this.pathLower == other.pathLower) || (this.pathLower != null && this.pathLower.equals(other.pathLower))) - && ((this.pathDisplay == other.pathDisplay) || (this.pathDisplay != null && this.pathDisplay.equals(other.pathDisplay))) - && ((this.parentSharedFolderId == other.parentSharedFolderId) || (this.parentSharedFolderId != null && this.parentSharedFolderId.equals(other.parentSharedFolderId))) - && ((this.mediaInfo == other.mediaInfo) || (this.mediaInfo != null && this.mediaInfo.equals(other.mediaInfo))) - && ((this.sharingInfo == other.sharingInfo) || (this.sharingInfo != null && this.sharingInfo.equals(other.sharingInfo))) - && ((this.propertyGroups == other.propertyGroups) || (this.propertyGroups != null && this.propertyGroups.equals(other.propertyGroups))) - && ((this.hasExplicitSharedMembers == other.hasExplicitSharedMembers) || (this.hasExplicitSharedMembers != null && this.hasExplicitSharedMembers.equals(other.hasExplicitSharedMembers))) - ; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(FileMetadata value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - writeTag("file", g); - g.writeFieldName("name"); - StoneSerializers.string().serialize(value.name, g); - g.writeFieldName("id"); - StoneSerializers.string().serialize(value.id, g); - g.writeFieldName("client_modified"); - StoneSerializers.timestamp().serialize(value.clientModified, g); - g.writeFieldName("server_modified"); - StoneSerializers.timestamp().serialize(value.serverModified, g); - g.writeFieldName("rev"); - StoneSerializers.string().serialize(value.rev, g); - g.writeFieldName("size"); - StoneSerializers.uInt64().serialize(value.size, g); - if (value.pathLower != null) { - g.writeFieldName("path_lower"); - StoneSerializers.nullable(StoneSerializers.string()).serialize(value.pathLower, g); - } - if (value.pathDisplay != null) { - g.writeFieldName("path_display"); - StoneSerializers.nullable(StoneSerializers.string()).serialize(value.pathDisplay, g); - } - if (value.parentSharedFolderId != null) { - g.writeFieldName("parent_shared_folder_id"); - StoneSerializers.nullable(StoneSerializers.string()).serialize(value.parentSharedFolderId, g); - } - if (value.mediaInfo != null) { - g.writeFieldName("media_info"); - StoneSerializers.nullable(MediaInfo.Serializer.INSTANCE).serialize(value.mediaInfo, g); - } - if (value.sharingInfo != null) { - g.writeFieldName("sharing_info"); - StoneSerializers.nullable(FileSharingInfo.Serializer.INSTANCE).serialize(value.sharingInfo, g); - } - if (value.propertyGroups != null) { - g.writeFieldName("property_groups"); - StoneSerializers.nullable(StoneSerializers.list(PropertyGroup.Serializer.INSTANCE)).serialize(value.propertyGroups, g); - } - if (value.hasExplicitSharedMembers != null) { - g.writeFieldName("has_explicit_shared_members"); - StoneSerializers.nullable(StoneSerializers.boolean_()).serialize(value.hasExplicitSharedMembers, g); - } - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public FileMetadata deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - FileMetadata value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - if ("file".equals(tag)) { - tag = null; - } - } - if (tag == null) { - String f_name = null; - String f_id = null; - Date f_clientModified = null; - Date f_serverModified = null; - String f_rev = null; - Long f_size = null; - String f_pathLower = null; - String f_pathDisplay = null; - String f_parentSharedFolderId = null; - MediaInfo f_mediaInfo = null; - FileSharingInfo f_sharingInfo = null; - List f_propertyGroups = null; - Boolean f_hasExplicitSharedMembers = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("name".equals(field)) { - f_name = StoneSerializers.string().deserialize(p); - } - else if ("id".equals(field)) { - f_id = StoneSerializers.string().deserialize(p); - } - else if ("client_modified".equals(field)) { - f_clientModified = StoneSerializers.timestamp().deserialize(p); - } - else if ("server_modified".equals(field)) { - f_serverModified = StoneSerializers.timestamp().deserialize(p); - } - else if ("rev".equals(field)) { - f_rev = StoneSerializers.string().deserialize(p); - } - else if ("size".equals(field)) { - f_size = StoneSerializers.uInt64().deserialize(p); - } - else if ("path_lower".equals(field)) { - f_pathLower = StoneSerializers.nullable(StoneSerializers.string()).deserialize(p); - } - else if ("path_display".equals(field)) { - f_pathDisplay = StoneSerializers.nullable(StoneSerializers.string()).deserialize(p); - } - else if ("parent_shared_folder_id".equals(field)) { - f_parentSharedFolderId = StoneSerializers.nullable(StoneSerializers.string()).deserialize(p); - } - else if ("media_info".equals(field)) { - f_mediaInfo = StoneSerializers.nullable(MediaInfo.Serializer.INSTANCE).deserialize(p); - } - else if ("sharing_info".equals(field)) { - f_sharingInfo = StoneSerializers.nullable(FileSharingInfo.Serializer.INSTANCE).deserialize(p); - } - else if ("property_groups".equals(field)) { - f_propertyGroups = StoneSerializers.nullable(StoneSerializers.list(PropertyGroup.Serializer.INSTANCE)).deserialize(p); - } - else if ("has_explicit_shared_members".equals(field)) { - f_hasExplicitSharedMembers = StoneSerializers.nullable(StoneSerializers.boolean_()).deserialize(p); - } - else { - skipValue(p); - } - } - if (f_name == null) { - throw new JsonParseException(p, "Required field \"name\" missing."); - } - if (f_id == null) { - throw new JsonParseException(p, "Required field \"id\" missing."); - } - if (f_clientModified == null) { - throw new JsonParseException(p, "Required field \"client_modified\" missing."); - } - if (f_serverModified == null) { - throw new JsonParseException(p, "Required field \"server_modified\" missing."); - } - if (f_rev == null) { - throw new JsonParseException(p, "Required field \"rev\" missing."); - } - if (f_size == null) { - throw new JsonParseException(p, "Required field \"size\" missing."); - } - value = new FileMetadata(f_name, f_id, f_clientModified, f_serverModified, f_rev, f_size, f_pathLower, f_pathDisplay, f_parentSharedFolderId, f_mediaInfo, f_sharingInfo, f_propertyGroups, f_hasExplicitSharedMembers); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/FileSharingInfo.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/FileSharingInfo.java deleted file mode 100644 index 3b279399..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/FileSharingInfo.java +++ /dev/null @@ -1,220 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; -import java.util.regex.Pattern; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * Sharing info for a file which is contained by a shared folder. - */ -public class FileSharingInfo extends SharingInfo { - // struct files.FileSharingInfo (files.stone) - - protected final String parentSharedFolderId; - protected final String modifiedBy; - - /** - * Sharing info for a file which is contained by a shared folder. - * - * @param readOnly True if the file or folder is inside a read-only shared - * folder. - * @param parentSharedFolderId ID of shared folder that holds this file. - * Must match pattern "{@code [-_0-9a-zA-Z:]+}" and not be {@code null}. - * @param modifiedBy The last user who modified the file. This field will - * be null if the user's account has been deleted. Must have length of - * at least 40 and have length of at most 40. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public FileSharingInfo(boolean readOnly, String parentSharedFolderId, String modifiedBy) { - super(readOnly); - if (parentSharedFolderId == null) { - throw new IllegalArgumentException("Required value for 'parentSharedFolderId' is null"); - } - if (!Pattern.matches("[-_0-9a-zA-Z:]+", parentSharedFolderId)) { - throw new IllegalArgumentException("String 'parentSharedFolderId' does not match pattern"); - } - this.parentSharedFolderId = parentSharedFolderId; - if (modifiedBy != null) { - if (modifiedBy.length() < 40) { - throw new IllegalArgumentException("String 'modifiedBy' is shorter than 40"); - } - if (modifiedBy.length() > 40) { - throw new IllegalArgumentException("String 'modifiedBy' is longer than 40"); - } - } - this.modifiedBy = modifiedBy; - } - - /** - * Sharing info for a file which is contained by a shared folder. - * - *

The default values for unset fields will be used.

- * - * @param readOnly True if the file or folder is inside a read-only shared - * folder. - * @param parentSharedFolderId ID of shared folder that holds this file. - * Must match pattern "{@code [-_0-9a-zA-Z:]+}" and not be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public FileSharingInfo(boolean readOnly, String parentSharedFolderId) { - this(readOnly, parentSharedFolderId, null); - } - - /** - * True if the file or folder is inside a read-only shared folder. - * - * @return value for this field. - */ - public boolean getReadOnly() { - return readOnly; - } - - /** - * ID of shared folder that holds this file. - * - * @return value for this field, never {@code null}. - */ - public String getParentSharedFolderId() { - return parentSharedFolderId; - } - - /** - * The last user who modified the file. This field will be null if the - * user's account has been deleted. - * - * @return value for this field, or {@code null} if not present. - */ - public String getModifiedBy() { - return modifiedBy; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - parentSharedFolderId, - modifiedBy - }); - hash = (31 * super.hashCode()) + hash; - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - FileSharingInfo other = (FileSharingInfo) obj; - return (this.readOnly == other.readOnly) - && ((this.parentSharedFolderId == other.parentSharedFolderId) || (this.parentSharedFolderId.equals(other.parentSharedFolderId))) - && ((this.modifiedBy == other.modifiedBy) || (this.modifiedBy != null && this.modifiedBy.equals(other.modifiedBy))) - ; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(FileSharingInfo value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("read_only"); - StoneSerializers.boolean_().serialize(value.readOnly, g); - g.writeFieldName("parent_shared_folder_id"); - StoneSerializers.string().serialize(value.parentSharedFolderId, g); - if (value.modifiedBy != null) { - g.writeFieldName("modified_by"); - StoneSerializers.nullable(StoneSerializers.string()).serialize(value.modifiedBy, g); - } - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public FileSharingInfo deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - FileSharingInfo value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - Boolean f_readOnly = null; - String f_parentSharedFolderId = null; - String f_modifiedBy = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("read_only".equals(field)) { - f_readOnly = StoneSerializers.boolean_().deserialize(p); - } - else if ("parent_shared_folder_id".equals(field)) { - f_parentSharedFolderId = StoneSerializers.string().deserialize(p); - } - else if ("modified_by".equals(field)) { - f_modifiedBy = StoneSerializers.nullable(StoneSerializers.string()).deserialize(p); - } - else { - skipValue(p); - } - } - if (f_readOnly == null) { - throw new JsonParseException(p, "Required field \"read_only\" missing."); - } - if (f_parentSharedFolderId == null) { - throw new JsonParseException(p, "Required field \"parent_shared_folder_id\" missing."); - } - value = new FileSharingInfo(f_readOnly, f_parentSharedFolderId, f_modifiedBy); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/FolderMetadata.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/FolderMetadata.java deleted file mode 100644 index 76553ba9..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/FolderMetadata.java +++ /dev/null @@ -1,511 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.dropbox.core.v2.properties.PropertyGroup; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -public class FolderMetadata extends Metadata { - // struct files.FolderMetadata (files.stone) - - protected final String id; - protected final String sharedFolderId; - protected final FolderSharingInfo sharingInfo; - protected final List propertyGroups; - - /** - * Use {@link newBuilder} to create instances of this class without - * specifying values for all optional fields. - * - * @param name The last component of the path (including extension). This - * never contains a slash. Must not be {@code null}. - * @param id A unique identifier for the folder. Must have length of at - * least 1 and not be {@code null}. - * @param pathLower The lowercased full path in the user's Dropbox. This - * always starts with a slash. This field will be null if the file or - * folder is not mounted. - * @param pathDisplay The cased path to be used for display purposes only. - * In rare instances the casing will not correctly match the user's - * filesystem, but this behavior will match the path provided in the - * Core API v1. Changes to the casing of paths won't be returned by - * {@link DbxUserFilesRequests#listFolderContinue(String)}. This field - * will be null if the file or folder is not mounted. - * @param parentSharedFolderId Deprecated. Please use {@link - * FileSharingInfo#getParentSharedFolderId} or {@link - * FolderSharingInfo#getParentSharedFolderId} instead. Must match - * pattern "{@code [-_0-9a-zA-Z:]+}". - * @param sharedFolderId Deprecated. Please use {@link - * FolderMetadata#getSharingInfo} instead. Must match pattern "{@code - * [-_0-9a-zA-Z:]+}". - * @param sharingInfo Set if the folder is contained in a shared folder or - * is a shared folder mount point. - * @param propertyGroups Additional information if the file has custom - * properties with the property template specified. Must not contain a - * {@code null} item. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public FolderMetadata(String name, String id, String pathLower, String pathDisplay, String parentSharedFolderId, String sharedFolderId, FolderSharingInfo sharingInfo, List propertyGroups) { - super(name, pathLower, pathDisplay, parentSharedFolderId); - if (id == null) { - throw new IllegalArgumentException("Required value for 'id' is null"); - } - if (id.length() < 1) { - throw new IllegalArgumentException("String 'id' is shorter than 1"); - } - this.id = id; - if (sharedFolderId != null) { - if (!java.util.regex.Pattern.matches("[-_0-9a-zA-Z:]+", sharedFolderId)) { - throw new IllegalArgumentException("String 'sharedFolderId' does not match pattern"); - } - } - this.sharedFolderId = sharedFolderId; - this.sharingInfo = sharingInfo; - if (propertyGroups != null) { - for (PropertyGroup x : propertyGroups) { - if (x == null) { - throw new IllegalArgumentException("An item in list 'propertyGroups' is null"); - } - } - } - this.propertyGroups = propertyGroups; - } - - /** - * None - * - *

The default values for unset fields will be used.

- * - * @param name The last component of the path (including extension). This - * never contains a slash. Must not be {@code null}. - * @param id A unique identifier for the folder. Must have length of at - * least 1 and not be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public FolderMetadata(String name, String id) { - this(name, id, null, null, null, null, null, null); - } - - /** - * The last component of the path (including extension). This never contains - * a slash. - * - * @return value for this field, never {@code null}. - */ - public String getName() { - return name; - } - - /** - * A unique identifier for the folder. - * - * @return value for this field, never {@code null}. - */ - public String getId() { - return id; - } - - /** - * The lowercased full path in the user's Dropbox. This always starts with a - * slash. This field will be null if the file or folder is not mounted. - * - * @return value for this field, or {@code null} if not present. - */ - public String getPathLower() { - return pathLower; - } - - /** - * The cased path to be used for display purposes only. In rare instances - * the casing will not correctly match the user's filesystem, but this - * behavior will match the path provided in the Core API v1. Changes to the - * casing of paths won't be returned by {@link - * DbxUserFilesRequests#listFolderContinue(String)}. This field will be null - * if the file or folder is not mounted. - * - * @return value for this field, or {@code null} if not present. - */ - public String getPathDisplay() { - return pathDisplay; - } - - /** - * Deprecated. Please use {@link FileSharingInfo#getParentSharedFolderId} or - * {@link FolderSharingInfo#getParentSharedFolderId} instead. - * - * @return value for this field, or {@code null} if not present. - */ - public String getParentSharedFolderId() { - return parentSharedFolderId; - } - - /** - * Deprecated. Please use {@link FolderMetadata#getSharingInfo} instead. - * - * @return value for this field, or {@code null} if not present. - */ - public String getSharedFolderId() { - return sharedFolderId; - } - - /** - * Set if the folder is contained in a shared folder or is a shared folder - * mount point. - * - * @return value for this field, or {@code null} if not present. - */ - public FolderSharingInfo getSharingInfo() { - return sharingInfo; - } - - /** - * Additional information if the file has custom properties with the - * property template specified. - * - * @return value for this field, or {@code null} if not present. - */ - public List getPropertyGroups() { - return propertyGroups; - } - - /** - * Returns a new builder for creating an instance of this class. - * - * @param name The last component of the path (including extension). This - * never contains a slash. Must not be {@code null}. - * @param id A unique identifier for the folder. Must have length of at - * least 1 and not be {@code null}. - * - * @return builder for this class. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public static Builder newBuilder(String name, String id) { - return new Builder(name, id); - } - - /** - * Builder for {@link FolderMetadata}. - */ - public static class Builder extends Metadata.Builder { - protected final String id; - - protected String sharedFolderId; - protected FolderSharingInfo sharingInfo; - protected List propertyGroups; - - protected Builder(String name, String id) { - super(name); - if (id == null) { - throw new IllegalArgumentException("Required value for 'id' is null"); - } - if (id.length() < 1) { - throw new IllegalArgumentException("String 'id' is shorter than 1"); - } - this.id = id; - this.sharedFolderId = null; - this.sharingInfo = null; - this.propertyGroups = null; - } - - /** - * Set value for optional field. - * - * @param sharedFolderId Deprecated. Please use {@link - * FolderMetadata#getSharingInfo} instead. Must match pattern - * "{@code [-_0-9a-zA-Z:]+}". - * - * @return this builder - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public Builder withSharedFolderId(String sharedFolderId) { - if (sharedFolderId != null) { - if (!java.util.regex.Pattern.matches("[-_0-9a-zA-Z:]+", sharedFolderId)) { - throw new IllegalArgumentException("String 'sharedFolderId' does not match pattern"); - } - } - this.sharedFolderId = sharedFolderId; - return this; - } - - /** - * Set value for optional field. - * - * @param sharingInfo Set if the folder is contained in a shared folder - * or is a shared folder mount point. - * - * @return this builder - */ - public Builder withSharingInfo(FolderSharingInfo sharingInfo) { - this.sharingInfo = sharingInfo; - return this; - } - - /** - * Set value for optional field. - * - * @param propertyGroups Additional information if the file has custom - * properties with the property template specified. Must not contain - * a {@code null} item. - * - * @return this builder - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public Builder withPropertyGroups(List propertyGroups) { - if (propertyGroups != null) { - for (PropertyGroup x : propertyGroups) { - if (x == null) { - throw new IllegalArgumentException("An item in list 'propertyGroups' is null"); - } - } - } - this.propertyGroups = propertyGroups; - return this; - } - - /** - * Set value for optional field. - * - * @param pathLower The lowercased full path in the user's Dropbox. - * This always starts with a slash. This field will be null if the - * file or folder is not mounted. - * - * @return this builder - */ - public Builder withPathLower(String pathLower) { - super.withPathLower(pathLower); - return this; - } - - /** - * Set value for optional field. - * - * @param pathDisplay The cased path to be used for display purposes - * only. In rare instances the casing will not correctly match the - * user's filesystem, but this behavior will match the path provided - * in the Core API v1. Changes to the casing of paths won't be - * returned by {@link - * DbxUserFilesRequests#listFolderContinue(String)}. This field will - * be null if the file or folder is not mounted. - * - * @return this builder - */ - public Builder withPathDisplay(String pathDisplay) { - super.withPathDisplay(pathDisplay); - return this; - } - - /** - * Set value for optional field. - * - * @param parentSharedFolderId Deprecated. Please use {@link - * FileSharingInfo#getParentSharedFolderId} or {@link - * FolderSharingInfo#getParentSharedFolderId} instead. Must match - * pattern "{@code [-_0-9a-zA-Z:]+}". - * - * @return this builder - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public Builder withParentSharedFolderId(String parentSharedFolderId) { - super.withParentSharedFolderId(parentSharedFolderId); - return this; - } - - /** - * Builds an instance of {@link FolderMetadata} configured with this - * builder's values - * - * @return new instance of {@link FolderMetadata} - */ - public FolderMetadata build() { - return new FolderMetadata(name, id, pathLower, pathDisplay, parentSharedFolderId, sharedFolderId, sharingInfo, propertyGroups); - } - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - id, - sharedFolderId, - sharingInfo, - propertyGroups - }); - hash = (31 * super.hashCode()) + hash; - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - FolderMetadata other = (FolderMetadata) obj; - return ((this.name == other.name) || (this.name.equals(other.name))) - && ((this.id == other.id) || (this.id.equals(other.id))) - && ((this.pathLower == other.pathLower) || (this.pathLower != null && this.pathLower.equals(other.pathLower))) - && ((this.pathDisplay == other.pathDisplay) || (this.pathDisplay != null && this.pathDisplay.equals(other.pathDisplay))) - && ((this.parentSharedFolderId == other.parentSharedFolderId) || (this.parentSharedFolderId != null && this.parentSharedFolderId.equals(other.parentSharedFolderId))) - && ((this.sharedFolderId == other.sharedFolderId) || (this.sharedFolderId != null && this.sharedFolderId.equals(other.sharedFolderId))) - && ((this.sharingInfo == other.sharingInfo) || (this.sharingInfo != null && this.sharingInfo.equals(other.sharingInfo))) - && ((this.propertyGroups == other.propertyGroups) || (this.propertyGroups != null && this.propertyGroups.equals(other.propertyGroups))) - ; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(FolderMetadata value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - writeTag("folder", g); - g.writeFieldName("name"); - StoneSerializers.string().serialize(value.name, g); - g.writeFieldName("id"); - StoneSerializers.string().serialize(value.id, g); - if (value.pathLower != null) { - g.writeFieldName("path_lower"); - StoneSerializers.nullable(StoneSerializers.string()).serialize(value.pathLower, g); - } - if (value.pathDisplay != null) { - g.writeFieldName("path_display"); - StoneSerializers.nullable(StoneSerializers.string()).serialize(value.pathDisplay, g); - } - if (value.parentSharedFolderId != null) { - g.writeFieldName("parent_shared_folder_id"); - StoneSerializers.nullable(StoneSerializers.string()).serialize(value.parentSharedFolderId, g); - } - if (value.sharedFolderId != null) { - g.writeFieldName("shared_folder_id"); - StoneSerializers.nullable(StoneSerializers.string()).serialize(value.sharedFolderId, g); - } - if (value.sharingInfo != null) { - g.writeFieldName("sharing_info"); - StoneSerializers.nullable(FolderSharingInfo.Serializer.INSTANCE).serialize(value.sharingInfo, g); - } - if (value.propertyGroups != null) { - g.writeFieldName("property_groups"); - StoneSerializers.nullable(StoneSerializers.list(PropertyGroup.Serializer.INSTANCE)).serialize(value.propertyGroups, g); - } - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public FolderMetadata deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - FolderMetadata value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - if ("folder".equals(tag)) { - tag = null; - } - } - if (tag == null) { - String f_name = null; - String f_id = null; - String f_pathLower = null; - String f_pathDisplay = null; - String f_parentSharedFolderId = null; - String f_sharedFolderId = null; - FolderSharingInfo f_sharingInfo = null; - List f_propertyGroups = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("name".equals(field)) { - f_name = StoneSerializers.string().deserialize(p); - } - else if ("id".equals(field)) { - f_id = StoneSerializers.string().deserialize(p); - } - else if ("path_lower".equals(field)) { - f_pathLower = StoneSerializers.nullable(StoneSerializers.string()).deserialize(p); - } - else if ("path_display".equals(field)) { - f_pathDisplay = StoneSerializers.nullable(StoneSerializers.string()).deserialize(p); - } - else if ("parent_shared_folder_id".equals(field)) { - f_parentSharedFolderId = StoneSerializers.nullable(StoneSerializers.string()).deserialize(p); - } - else if ("shared_folder_id".equals(field)) { - f_sharedFolderId = StoneSerializers.nullable(StoneSerializers.string()).deserialize(p); - } - else if ("sharing_info".equals(field)) { - f_sharingInfo = StoneSerializers.nullable(FolderSharingInfo.Serializer.INSTANCE).deserialize(p); - } - else if ("property_groups".equals(field)) { - f_propertyGroups = StoneSerializers.nullable(StoneSerializers.list(PropertyGroup.Serializer.INSTANCE)).deserialize(p); - } - else { - skipValue(p); - } - } - if (f_name == null) { - throw new JsonParseException(p, "Required field \"name\" missing."); - } - if (f_id == null) { - throw new JsonParseException(p, "Required field \"id\" missing."); - } - value = new FolderMetadata(f_name, f_id, f_pathLower, f_pathDisplay, f_parentSharedFolderId, f_sharedFolderId, f_sharingInfo, f_propertyGroups); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/FolderSharingInfo.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/FolderSharingInfo.java deleted file mode 100644 index c18668c6..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/FolderSharingInfo.java +++ /dev/null @@ -1,394 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * Sharing info for a folder which is contained in a shared folder or is a - * shared folder mount point. - */ -public class FolderSharingInfo extends SharingInfo { - // struct files.FolderSharingInfo (files.stone) - - protected final String parentSharedFolderId; - protected final String sharedFolderId; - protected final boolean traverseOnly; - protected final boolean noAccess; - - /** - * Sharing info for a folder which is contained in a shared folder or is a - * shared folder mount point. - * - *

Use {@link newBuilder} to create instances of this class without - * specifying values for all optional fields.

- * - * @param readOnly True if the file or folder is inside a read-only shared - * folder. - * @param parentSharedFolderId Set if the folder is contained by a shared - * folder. Must match pattern "{@code [-_0-9a-zA-Z:]+}". - * @param sharedFolderId If this folder is a shared folder mount point, the - * ID of the shared folder mounted at this location. Must match pattern - * "{@code [-_0-9a-zA-Z:]+}". - * @param traverseOnly Specifies that the folder can only be traversed and - * the user can only see a limited subset of the contents of this folder - * because they don't have read access to this folder. They do, however, - * have access to some sub folder. - * @param noAccess Specifies that the folder cannot be accessed by the - * user. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public FolderSharingInfo(boolean readOnly, String parentSharedFolderId, String sharedFolderId, boolean traverseOnly, boolean noAccess) { - super(readOnly); - if (parentSharedFolderId != null) { - if (!java.util.regex.Pattern.matches("[-_0-9a-zA-Z:]+", parentSharedFolderId)) { - throw new IllegalArgumentException("String 'parentSharedFolderId' does not match pattern"); - } - } - this.parentSharedFolderId = parentSharedFolderId; - if (sharedFolderId != null) { - if (!java.util.regex.Pattern.matches("[-_0-9a-zA-Z:]+", sharedFolderId)) { - throw new IllegalArgumentException("String 'sharedFolderId' does not match pattern"); - } - } - this.sharedFolderId = sharedFolderId; - this.traverseOnly = traverseOnly; - this.noAccess = noAccess; - } - - /** - * Sharing info for a folder which is contained in a shared folder or is a - * shared folder mount point. - * - *

The default values for unset fields will be used.

- * - * @param readOnly True if the file or folder is inside a read-only shared - * folder. - */ - public FolderSharingInfo(boolean readOnly) { - this(readOnly, null, null, false, false); - } - - /** - * True if the file or folder is inside a read-only shared folder. - * - * @return value for this field. - */ - public boolean getReadOnly() { - return readOnly; - } - - /** - * Set if the folder is contained by a shared folder. - * - * @return value for this field, or {@code null} if not present. - */ - public String getParentSharedFolderId() { - return parentSharedFolderId; - } - - /** - * If this folder is a shared folder mount point, the ID of the shared - * folder mounted at this location. - * - * @return value for this field, or {@code null} if not present. - */ - public String getSharedFolderId() { - return sharedFolderId; - } - - /** - * Specifies that the folder can only be traversed and the user can only see - * a limited subset of the contents of this folder because they don't have - * read access to this folder. They do, however, have access to some sub - * folder. - * - * @return value for this field, or {@code null} if not present. Defaults to - * false. - */ - public boolean getTraverseOnly() { - return traverseOnly; - } - - /** - * Specifies that the folder cannot be accessed by the user. - * - * @return value for this field, or {@code null} if not present. Defaults to - * false. - */ - public boolean getNoAccess() { - return noAccess; - } - - /** - * Returns a new builder for creating an instance of this class. - * - * @param readOnly True if the file or folder is inside a read-only shared - * folder. - * - * @return builder for this class. - */ - public static Builder newBuilder(boolean readOnly) { - return new Builder(readOnly); - } - - /** - * Builder for {@link FolderSharingInfo}. - */ - public static class Builder { - protected final boolean readOnly; - - protected String parentSharedFolderId; - protected String sharedFolderId; - protected boolean traverseOnly; - protected boolean noAccess; - - protected Builder(boolean readOnly) { - this.readOnly = readOnly; - this.parentSharedFolderId = null; - this.sharedFolderId = null; - this.traverseOnly = false; - this.noAccess = false; - } - - /** - * Set value for optional field. - * - * @param parentSharedFolderId Set if the folder is contained by a - * shared folder. Must match pattern "{@code [-_0-9a-zA-Z:]+}". - * - * @return this builder - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public Builder withParentSharedFolderId(String parentSharedFolderId) { - if (parentSharedFolderId != null) { - if (!java.util.regex.Pattern.matches("[-_0-9a-zA-Z:]+", parentSharedFolderId)) { - throw new IllegalArgumentException("String 'parentSharedFolderId' does not match pattern"); - } - } - this.parentSharedFolderId = parentSharedFolderId; - return this; - } - - /** - * Set value for optional field. - * - * @param sharedFolderId If this folder is a shared folder mount point, - * the ID of the shared folder mounted at this location. Must match - * pattern "{@code [-_0-9a-zA-Z:]+}". - * - * @return this builder - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public Builder withSharedFolderId(String sharedFolderId) { - if (sharedFolderId != null) { - if (!java.util.regex.Pattern.matches("[-_0-9a-zA-Z:]+", sharedFolderId)) { - throw new IllegalArgumentException("String 'sharedFolderId' does not match pattern"); - } - } - this.sharedFolderId = sharedFolderId; - return this; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}. - *

- * - * @param traverseOnly Specifies that the folder can only be traversed - * and the user can only see a limited subset of the contents of - * this folder because they don't have read access to this folder. - * They do, however, have access to some sub folder. Defaults to - * {@code false} when set to {@code null}. - * - * @return this builder - */ - public Builder withTraverseOnly(Boolean traverseOnly) { - if (traverseOnly != null) { - this.traverseOnly = traverseOnly; - } - else { - this.traverseOnly = false; - } - return this; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}. - *

- * - * @param noAccess Specifies that the folder cannot be accessed by the - * user. Defaults to {@code false} when set to {@code null}. - * - * @return this builder - */ - public Builder withNoAccess(Boolean noAccess) { - if (noAccess != null) { - this.noAccess = noAccess; - } - else { - this.noAccess = false; - } - return this; - } - - /** - * Builds an instance of {@link FolderSharingInfo} configured with this - * builder's values - * - * @return new instance of {@link FolderSharingInfo} - */ - public FolderSharingInfo build() { - return new FolderSharingInfo(readOnly, parentSharedFolderId, sharedFolderId, traverseOnly, noAccess); - } - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - parentSharedFolderId, - sharedFolderId, - traverseOnly, - noAccess - }); - hash = (31 * super.hashCode()) + hash; - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - FolderSharingInfo other = (FolderSharingInfo) obj; - return (this.readOnly == other.readOnly) - && ((this.parentSharedFolderId == other.parentSharedFolderId) || (this.parentSharedFolderId != null && this.parentSharedFolderId.equals(other.parentSharedFolderId))) - && ((this.sharedFolderId == other.sharedFolderId) || (this.sharedFolderId != null && this.sharedFolderId.equals(other.sharedFolderId))) - && (this.traverseOnly == other.traverseOnly) - && (this.noAccess == other.noAccess) - ; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(FolderSharingInfo value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("read_only"); - StoneSerializers.boolean_().serialize(value.readOnly, g); - if (value.parentSharedFolderId != null) { - g.writeFieldName("parent_shared_folder_id"); - StoneSerializers.nullable(StoneSerializers.string()).serialize(value.parentSharedFolderId, g); - } - if (value.sharedFolderId != null) { - g.writeFieldName("shared_folder_id"); - StoneSerializers.nullable(StoneSerializers.string()).serialize(value.sharedFolderId, g); - } - g.writeFieldName("traverse_only"); - StoneSerializers.boolean_().serialize(value.traverseOnly, g); - g.writeFieldName("no_access"); - StoneSerializers.boolean_().serialize(value.noAccess, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public FolderSharingInfo deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - FolderSharingInfo value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - Boolean f_readOnly = null; - String f_parentSharedFolderId = null; - String f_sharedFolderId = null; - Boolean f_traverseOnly = false; - Boolean f_noAccess = false; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("read_only".equals(field)) { - f_readOnly = StoneSerializers.boolean_().deserialize(p); - } - else if ("parent_shared_folder_id".equals(field)) { - f_parentSharedFolderId = StoneSerializers.nullable(StoneSerializers.string()).deserialize(p); - } - else if ("shared_folder_id".equals(field)) { - f_sharedFolderId = StoneSerializers.nullable(StoneSerializers.string()).deserialize(p); - } - else if ("traverse_only".equals(field)) { - f_traverseOnly = StoneSerializers.boolean_().deserialize(p); - } - else if ("no_access".equals(field)) { - f_noAccess = StoneSerializers.boolean_().deserialize(p); - } - else { - skipValue(p); - } - } - if (f_readOnly == null) { - throw new JsonParseException(p, "Required field \"read_only\" missing."); - } - value = new FolderSharingInfo(f_readOnly, f_parentSharedFolderId, f_sharedFolderId, f_traverseOnly, f_noAccess); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/GetMetadataArg.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/GetMetadataArg.java deleted file mode 100644 index 6df2e3fc..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/GetMetadataArg.java +++ /dev/null @@ -1,350 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; -import java.util.regex.Pattern; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -class GetMetadataArg { - // struct files.GetMetadataArg (files.stone) - - protected final String path; - protected final boolean includeMediaInfo; - protected final boolean includeDeleted; - protected final boolean includeHasExplicitSharedMembers; - - /** - * Use {@link newBuilder} to create instances of this class without - * specifying values for all optional fields. - * - * @param path The path of a file or folder on Dropbox. Must match pattern - * "{@code (/(.|[\\r\\n])*|id:.*)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)}" - * and not be {@code null}. - * @param includeMediaInfo If true, {@link FileMetadata#getMediaInfo} is - * set for photo and video. - * @param includeDeleted If true, {@link DeletedMetadata} will be returned - * for deleted file or folder, otherwise {@link LookupError#NOT_FOUND} - * will be returned. - * @param includeHasExplicitSharedMembers If true, the results will include - * a flag for each file indicating whether or not that file has any - * explicit members. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public GetMetadataArg(String path, boolean includeMediaInfo, boolean includeDeleted, boolean includeHasExplicitSharedMembers) { - if (path == null) { - throw new IllegalArgumentException("Required value for 'path' is null"); - } - if (!Pattern.matches("(/(.|[\\r\\n])*|id:.*)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)", path)) { - throw new IllegalArgumentException("String 'path' does not match pattern"); - } - this.path = path; - this.includeMediaInfo = includeMediaInfo; - this.includeDeleted = includeDeleted; - this.includeHasExplicitSharedMembers = includeHasExplicitSharedMembers; - } - - /** - * None - * - *

The default values for unset fields will be used.

- * - * @param path The path of a file or folder on Dropbox. Must match pattern - * "{@code (/(.|[\\r\\n])*|id:.*)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)}" - * and not be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public GetMetadataArg(String path) { - this(path, false, false, false); - } - - /** - * The path of a file or folder on Dropbox. - * - * @return value for this field, never {@code null}. - */ - public String getPath() { - return path; - } - - /** - * If true, {@link FileMetadata#getMediaInfo} is set for photo and video. - * - * @return value for this field, or {@code null} if not present. Defaults to - * false. - */ - public boolean getIncludeMediaInfo() { - return includeMediaInfo; - } - - /** - * If true, {@link DeletedMetadata} will be returned for deleted file or - * folder, otherwise {@link LookupError#NOT_FOUND} will be returned. - * - * @return value for this field, or {@code null} if not present. Defaults to - * false. - */ - public boolean getIncludeDeleted() { - return includeDeleted; - } - - /** - * If true, the results will include a flag for each file indicating whether - * or not that file has any explicit members. - * - * @return value for this field, or {@code null} if not present. Defaults to - * false. - */ - public boolean getIncludeHasExplicitSharedMembers() { - return includeHasExplicitSharedMembers; - } - - /** - * Returns a new builder for creating an instance of this class. - * - * @param path The path of a file or folder on Dropbox. Must match pattern - * "{@code (/(.|[\\r\\n])*|id:.*)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)}" - * and not be {@code null}. - * - * @return builder for this class. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public static Builder newBuilder(String path) { - return new Builder(path); - } - - /** - * Builder for {@link GetMetadataArg}. - */ - public static class Builder { - protected final String path; - - protected boolean includeMediaInfo; - protected boolean includeDeleted; - protected boolean includeHasExplicitSharedMembers; - - protected Builder(String path) { - if (path == null) { - throw new IllegalArgumentException("Required value for 'path' is null"); - } - if (!Pattern.matches("(/(.|[\\r\\n])*|id:.*)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)", path)) { - throw new IllegalArgumentException("String 'path' does not match pattern"); - } - this.path = path; - this.includeMediaInfo = false; - this.includeDeleted = false; - this.includeHasExplicitSharedMembers = false; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}. - *

- * - * @param includeMediaInfo If true, {@link FileMetadata#getMediaInfo} - * is set for photo and video. Defaults to {@code false} when set to - * {@code null}. - * - * @return this builder - */ - public Builder withIncludeMediaInfo(Boolean includeMediaInfo) { - if (includeMediaInfo != null) { - this.includeMediaInfo = includeMediaInfo; - } - else { - this.includeMediaInfo = false; - } - return this; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}. - *

- * - * @param includeDeleted If true, {@link DeletedMetadata} will be - * returned for deleted file or folder, otherwise {@link - * LookupError#NOT_FOUND} will be returned. Defaults to {@code - * false} when set to {@code null}. - * - * @return this builder - */ - public Builder withIncludeDeleted(Boolean includeDeleted) { - if (includeDeleted != null) { - this.includeDeleted = includeDeleted; - } - else { - this.includeDeleted = false; - } - return this; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}. - *

- * - * @param includeHasExplicitSharedMembers If true, the results will - * include a flag for each file indicating whether or not that file - * has any explicit members. Defaults to {@code false} when set to - * {@code null}. - * - * @return this builder - */ - public Builder withIncludeHasExplicitSharedMembers(Boolean includeHasExplicitSharedMembers) { - if (includeHasExplicitSharedMembers != null) { - this.includeHasExplicitSharedMembers = includeHasExplicitSharedMembers; - } - else { - this.includeHasExplicitSharedMembers = false; - } - return this; - } - - /** - * Builds an instance of {@link GetMetadataArg} configured with this - * builder's values - * - * @return new instance of {@link GetMetadataArg} - */ - public GetMetadataArg build() { - return new GetMetadataArg(path, includeMediaInfo, includeDeleted, includeHasExplicitSharedMembers); - } - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - path, - includeMediaInfo, - includeDeleted, - includeHasExplicitSharedMembers - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - GetMetadataArg other = (GetMetadataArg) obj; - return ((this.path == other.path) || (this.path.equals(other.path))) - && (this.includeMediaInfo == other.includeMediaInfo) - && (this.includeDeleted == other.includeDeleted) - && (this.includeHasExplicitSharedMembers == other.includeHasExplicitSharedMembers) - ; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(GetMetadataArg value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("path"); - StoneSerializers.string().serialize(value.path, g); - g.writeFieldName("include_media_info"); - StoneSerializers.boolean_().serialize(value.includeMediaInfo, g); - g.writeFieldName("include_deleted"); - StoneSerializers.boolean_().serialize(value.includeDeleted, g); - g.writeFieldName("include_has_explicit_shared_members"); - StoneSerializers.boolean_().serialize(value.includeHasExplicitSharedMembers, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public GetMetadataArg deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - GetMetadataArg value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - String f_path = null; - Boolean f_includeMediaInfo = false; - Boolean f_includeDeleted = false; - Boolean f_includeHasExplicitSharedMembers = false; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("path".equals(field)) { - f_path = StoneSerializers.string().deserialize(p); - } - else if ("include_media_info".equals(field)) { - f_includeMediaInfo = StoneSerializers.boolean_().deserialize(p); - } - else if ("include_deleted".equals(field)) { - f_includeDeleted = StoneSerializers.boolean_().deserialize(p); - } - else if ("include_has_explicit_shared_members".equals(field)) { - f_includeHasExplicitSharedMembers = StoneSerializers.boolean_().deserialize(p); - } - else { - skipValue(p); - } - } - if (f_path == null) { - throw new JsonParseException(p, "Required field \"path\" missing."); - } - value = new GetMetadataArg(f_path, f_includeMediaInfo, f_includeDeleted, f_includeHasExplicitSharedMembers); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/GetMetadataBuilder.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/GetMetadataBuilder.java deleted file mode 100644 index d571ab9f..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/GetMetadataBuilder.java +++ /dev/null @@ -1,94 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated by Stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import autosaveworld.zlibs.com.dropbox.core.DbxException; - -/** - * The request builder returned by {@link - * DbxUserFilesRequests#getMetadataBuilder}. - * - *

Use this class to set optional request parameters and complete the - * request.

- */ -public class GetMetadataBuilder { - private final DbxUserFilesRequests _client; - private final GetMetadataArg.Builder _builder; - - /** - * Creates a new instance of this builder. - * - * @param _client Dropbox namespace-specific client used to issue files - * requests. - * @param _builder Request argument builder. - * - * @return instsance of this builder - */ - GetMetadataBuilder(DbxUserFilesRequests _client, GetMetadataArg.Builder _builder) { - if (_client == null) { - throw new NullPointerException("_client"); - } - this._client = _client; - if (_builder == null) { - throw new NullPointerException("_builder"); - } - this._builder = _builder; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}.

- * - * @param includeMediaInfo If true, {@link FileMetadata#getMediaInfo} is - * set for photo and video. Defaults to {@code false} when set to {@code - * null}. - * - * @return this builder - */ - public GetMetadataBuilder withIncludeMediaInfo(Boolean includeMediaInfo) { - this._builder.withIncludeMediaInfo(includeMediaInfo); - return this; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}.

- * - * @param includeDeleted If true, {@link DeletedMetadata} will be returned - * for deleted file or folder, otherwise {@link LookupError#NOT_FOUND} - * will be returned. Defaults to {@code false} when set to {@code null}. - * - * @return this builder - */ - public GetMetadataBuilder withIncludeDeleted(Boolean includeDeleted) { - this._builder.withIncludeDeleted(includeDeleted); - return this; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}.

- * - * @param includeHasExplicitSharedMembers If true, the results will include - * a flag for each file indicating whether or not that file has any - * explicit members. Defaults to {@code false} when set to {@code null}. - * - * @return this builder - */ - public GetMetadataBuilder withIncludeHasExplicitSharedMembers(Boolean includeHasExplicitSharedMembers) { - this._builder.withIncludeHasExplicitSharedMembers(includeHasExplicitSharedMembers); - return this; - } - - /** - * Issues the request. - */ - public Metadata start() throws GetMetadataErrorException, DbxException { - GetMetadataArg arg_ = this._builder.build(); - return _client.getMetadata(arg_); - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/GetMetadataError.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/GetMetadataError.java deleted file mode 100644 index 5f444af9..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/GetMetadataError.java +++ /dev/null @@ -1,213 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.UnionSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * This class is a tagged union. Tagged unions instances are always associated - * to a specific tag. This means only one of the {@code isAbc()} methods will - * return {@code true}. You can use {@link #tag()} to determine the tag - * associated with this instance. - */ -public final class GetMetadataError { - // union files.GetMetadataError (files.stone) - - /** - * Discriminating tag type for {@link GetMetadataError}. - */ - public enum Tag { - PATH; // LookupError - } - - private final Tag _tag; - private final LookupError pathValue; - - /** - * - * @param pathValue Must not be {@code null}. - * @param _tag Discriminating tag for this instance. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - private GetMetadataError(Tag _tag, LookupError pathValue) { - this._tag = _tag; - this.pathValue = pathValue; - } - - /** - * Returns the tag for this instance. - * - *

This class is a tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isXyz()} - * methods will return {@code true}. Callers are recommended to use the tag - * value in a {@code switch} statement to properly handle the different - * values for this {@code GetMetadataError}.

- * - * @return the tag for this instance. - */ - public Tag tag() { - return _tag; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#PATH}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#PATH}, - * {@code false} otherwise. - */ - public boolean isPath() { - return this._tag == Tag.PATH; - } - - /** - * Returns an instance of {@code GetMetadataError} that has its tag set to - * {@link Tag#PATH}. - * - *

None

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code GetMetadataError} with its tag set to {@link - * Tag#PATH}. - * - * @throws IllegalArgumentException if {@code value} is {@code null}. - */ - public static GetMetadataError path(LookupError value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - return new GetMetadataError(Tag.PATH, value); - } - - /** - * This instance must be tagged as {@link Tag#PATH}. - * - * @return The {@link LookupError} value associated with this instance if - * {@link #isPath} is {@code true}. - * - * @throws IllegalStateException If {@link #isPath} is {@code false}. - */ - public LookupError getPathValue() { - if (this._tag != Tag.PATH) { - throw new IllegalStateException("Invalid tag: required Tag.PATH, but was Tag." + this._tag.name()); - } - return pathValue; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - _tag, - pathValue - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - else if (obj instanceof GetMetadataError) { - GetMetadataError other = (GetMetadataError) obj; - if (this._tag != other._tag) { - return false; - } - switch (_tag) { - case PATH: - return (this.pathValue == other.pathValue) || (this.pathValue.equals(other.pathValue)); - default: - return false; - } - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends UnionSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(GetMetadataError value, JsonGenerator g) throws IOException, JsonGenerationException { - switch (value.tag()) { - case PATH: { - g.writeStartObject(); - writeTag("path", g); - g.writeFieldName("path"); - LookupError.Serializer.INSTANCE.serialize(value.pathValue, g); - g.writeEndObject(); - break; - } - default: { - throw new IllegalArgumentException("Unrecognized tag: " + value.tag()); - } - } - } - - @Override - public GetMetadataError deserialize(JsonParser p) throws IOException, JsonParseException { - GetMetadataError value; - boolean collapsed; - String tag; - if (p.getCurrentToken() == JsonToken.VALUE_STRING) { - collapsed = true; - tag = getStringValue(p); - p.nextToken(); - } - else { - collapsed = false; - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); - } - else if ("path".equals(tag)) { - LookupError fieldValue = null; - expectField("path", p); - fieldValue = LookupError.Serializer.INSTANCE.deserialize(p); - value = GetMetadataError.path(fieldValue); - } - else { - throw new JsonParseException(p, "Unknown tag: " + tag); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/GetMetadataErrorException.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/GetMetadataErrorException.java deleted file mode 100644 index d6146aee..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/GetMetadataErrorException.java +++ /dev/null @@ -1,34 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated by Stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import autosaveworld.zlibs.com.dropbox.core.DbxApiException; -import autosaveworld.zlibs.com.dropbox.core.LocalizedText; - -/** - * Exception thrown when the server responds with a {@link GetMetadataError} - * error. - * - *

This exception is raised by {@link - * DbxUserFilesRequests#getMetadata(String)}.

- */ -public class GetMetadataErrorException extends DbxApiException { - // exception for routes: - // 2/files/get_metadata - - private static final long serialVersionUID = 0L; - - /** - * The error reported by {@link DbxUserFilesRequests#getMetadata(String)}. - */ - public final GetMetadataError errorValue; - - public GetMetadataErrorException(String routeName, String requestId, LocalizedText userMessage, GetMetadataError errorValue) { - super(requestId, userMessage, buildMessage(routeName, userMessage, errorValue)); - if (errorValue == null) { - throw new NullPointerException("errorValue"); - } - this.errorValue = errorValue; - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/GpsCoordinates.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/GpsCoordinates.java deleted file mode 100644 index 16ab080e..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/GpsCoordinates.java +++ /dev/null @@ -1,159 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * GPS coordinates for a photo or video. - */ -public class GpsCoordinates { - // struct files.GpsCoordinates (files.stone) - - protected final double latitude; - protected final double longitude; - - /** - * GPS coordinates for a photo or video. - * - * @param latitude Latitude of the GPS coordinates. - * @param longitude Longitude of the GPS coordinates. - */ - public GpsCoordinates(double latitude, double longitude) { - this.latitude = latitude; - this.longitude = longitude; - } - - /** - * Latitude of the GPS coordinates. - * - * @return value for this field. - */ - public double getLatitude() { - return latitude; - } - - /** - * Longitude of the GPS coordinates. - * - * @return value for this field. - */ - public double getLongitude() { - return longitude; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - latitude, - longitude - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - GpsCoordinates other = (GpsCoordinates) obj; - return (this.latitude == other.latitude) - && (this.longitude == other.longitude) - ; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(GpsCoordinates value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("latitude"); - StoneSerializers.float64().serialize(value.latitude, g); - g.writeFieldName("longitude"); - StoneSerializers.float64().serialize(value.longitude, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public GpsCoordinates deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - GpsCoordinates value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - Double f_latitude = null; - Double f_longitude = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("latitude".equals(field)) { - f_latitude = StoneSerializers.float64().deserialize(p); - } - else if ("longitude".equals(field)) { - f_longitude = StoneSerializers.float64().deserialize(p); - } - else { - skipValue(p); - } - } - if (f_latitude == null) { - throw new JsonParseException(p, "Required field \"latitude\" missing."); - } - if (f_longitude == null) { - throw new JsonParseException(p, "Required field \"longitude\" missing."); - } - value = new GpsCoordinates(f_latitude, f_longitude); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderArg.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderArg.java deleted file mode 100644 index cf599cfd..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderArg.java +++ /dev/null @@ -1,397 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; -import java.util.regex.Pattern; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -class ListFolderArg { - // struct files.ListFolderArg (files.stone) - - protected final String path; - protected final boolean recursive; - protected final boolean includeMediaInfo; - protected final boolean includeDeleted; - protected final boolean includeHasExplicitSharedMembers; - - /** - * Use {@link newBuilder} to create instances of this class without - * specifying values for all optional fields. - * - * @param path The path to the folder you want to see the contents of. Must - * match pattern "{@code (/(.|[\\r\\n])*)?|(ns:[0-9]+(/.*)?)}" and not - * be {@code null}. - * @param recursive If true, the list folder operation will be applied - * recursively to all subfolders and the response will contain contents - * of all subfolders. - * @param includeMediaInfo If true, {@link FileMetadata#getMediaInfo} is - * set for photo and video. - * @param includeDeleted If true, the results will include entries for - * files and folders that used to exist but were deleted. - * @param includeHasExplicitSharedMembers If true, the results will include - * a flag for each file indicating whether or not that file has any - * explicit members. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public ListFolderArg(String path, boolean recursive, boolean includeMediaInfo, boolean includeDeleted, boolean includeHasExplicitSharedMembers) { - if (path == null) { - throw new IllegalArgumentException("Required value for 'path' is null"); - } - if (!Pattern.matches("(/(.|[\\r\\n])*)?|(ns:[0-9]+(/.*)?)", path)) { - throw new IllegalArgumentException("String 'path' does not match pattern"); - } - this.path = path; - this.recursive = recursive; - this.includeMediaInfo = includeMediaInfo; - this.includeDeleted = includeDeleted; - this.includeHasExplicitSharedMembers = includeHasExplicitSharedMembers; - } - - /** - * None - * - *

The default values for unset fields will be used.

- * - * @param path The path to the folder you want to see the contents of. Must - * match pattern "{@code (/(.|[\\r\\n])*)?|(ns:[0-9]+(/.*)?)}" and not - * be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public ListFolderArg(String path) { - this(path, false, false, false, false); - } - - /** - * The path to the folder you want to see the contents of. - * - * @return value for this field, never {@code null}. - */ - public String getPath() { - return path; - } - - /** - * If true, the list folder operation will be applied recursively to all - * subfolders and the response will contain contents of all subfolders. - * - * @return value for this field, or {@code null} if not present. Defaults to - * false. - */ - public boolean getRecursive() { - return recursive; - } - - /** - * If true, {@link FileMetadata#getMediaInfo} is set for photo and video. - * - * @return value for this field, or {@code null} if not present. Defaults to - * false. - */ - public boolean getIncludeMediaInfo() { - return includeMediaInfo; - } - - /** - * If true, the results will include entries for files and folders that used - * to exist but were deleted. - * - * @return value for this field, or {@code null} if not present. Defaults to - * false. - */ - public boolean getIncludeDeleted() { - return includeDeleted; - } - - /** - * If true, the results will include a flag for each file indicating whether - * or not that file has any explicit members. - * - * @return value for this field, or {@code null} if not present. Defaults to - * false. - */ - public boolean getIncludeHasExplicitSharedMembers() { - return includeHasExplicitSharedMembers; - } - - /** - * Returns a new builder for creating an instance of this class. - * - * @param path The path to the folder you want to see the contents of. Must - * match pattern "{@code (/(.|[\\r\\n])*)?|(ns:[0-9]+(/.*)?)}" and not - * be {@code null}. - * - * @return builder for this class. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public static Builder newBuilder(String path) { - return new Builder(path); - } - - /** - * Builder for {@link ListFolderArg}. - */ - public static class Builder { - protected final String path; - - protected boolean recursive; - protected boolean includeMediaInfo; - protected boolean includeDeleted; - protected boolean includeHasExplicitSharedMembers; - - protected Builder(String path) { - if (path == null) { - throw new IllegalArgumentException("Required value for 'path' is null"); - } - if (!Pattern.matches("(/(.|[\\r\\n])*)?|(ns:[0-9]+(/.*)?)", path)) { - throw new IllegalArgumentException("String 'path' does not match pattern"); - } - this.path = path; - this.recursive = false; - this.includeMediaInfo = false; - this.includeDeleted = false; - this.includeHasExplicitSharedMembers = false; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}. - *

- * - * @param recursive If true, the list folder operation will be applied - * recursively to all subfolders and the response will contain - * contents of all subfolders. Defaults to {@code false} when set to - * {@code null}. - * - * @return this builder - */ - public Builder withRecursive(Boolean recursive) { - if (recursive != null) { - this.recursive = recursive; - } - else { - this.recursive = false; - } - return this; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}. - *

- * - * @param includeMediaInfo If true, {@link FileMetadata#getMediaInfo} - * is set for photo and video. Defaults to {@code false} when set to - * {@code null}. - * - * @return this builder - */ - public Builder withIncludeMediaInfo(Boolean includeMediaInfo) { - if (includeMediaInfo != null) { - this.includeMediaInfo = includeMediaInfo; - } - else { - this.includeMediaInfo = false; - } - return this; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}. - *

- * - * @param includeDeleted If true, the results will include entries for - * files and folders that used to exist but were deleted. Defaults - * to {@code false} when set to {@code null}. - * - * @return this builder - */ - public Builder withIncludeDeleted(Boolean includeDeleted) { - if (includeDeleted != null) { - this.includeDeleted = includeDeleted; - } - else { - this.includeDeleted = false; - } - return this; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}. - *

- * - * @param includeHasExplicitSharedMembers If true, the results will - * include a flag for each file indicating whether or not that file - * has any explicit members. Defaults to {@code false} when set to - * {@code null}. - * - * @return this builder - */ - public Builder withIncludeHasExplicitSharedMembers(Boolean includeHasExplicitSharedMembers) { - if (includeHasExplicitSharedMembers != null) { - this.includeHasExplicitSharedMembers = includeHasExplicitSharedMembers; - } - else { - this.includeHasExplicitSharedMembers = false; - } - return this; - } - - /** - * Builds an instance of {@link ListFolderArg} configured with this - * builder's values - * - * @return new instance of {@link ListFolderArg} - */ - public ListFolderArg build() { - return new ListFolderArg(path, recursive, includeMediaInfo, includeDeleted, includeHasExplicitSharedMembers); - } - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - path, - recursive, - includeMediaInfo, - includeDeleted, - includeHasExplicitSharedMembers - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - ListFolderArg other = (ListFolderArg) obj; - return ((this.path == other.path) || (this.path.equals(other.path))) - && (this.recursive == other.recursive) - && (this.includeMediaInfo == other.includeMediaInfo) - && (this.includeDeleted == other.includeDeleted) - && (this.includeHasExplicitSharedMembers == other.includeHasExplicitSharedMembers) - ; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(ListFolderArg value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("path"); - StoneSerializers.string().serialize(value.path, g); - g.writeFieldName("recursive"); - StoneSerializers.boolean_().serialize(value.recursive, g); - g.writeFieldName("include_media_info"); - StoneSerializers.boolean_().serialize(value.includeMediaInfo, g); - g.writeFieldName("include_deleted"); - StoneSerializers.boolean_().serialize(value.includeDeleted, g); - g.writeFieldName("include_has_explicit_shared_members"); - StoneSerializers.boolean_().serialize(value.includeHasExplicitSharedMembers, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public ListFolderArg deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - ListFolderArg value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - String f_path = null; - Boolean f_recursive = false; - Boolean f_includeMediaInfo = false; - Boolean f_includeDeleted = false; - Boolean f_includeHasExplicitSharedMembers = false; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("path".equals(field)) { - f_path = StoneSerializers.string().deserialize(p); - } - else if ("recursive".equals(field)) { - f_recursive = StoneSerializers.boolean_().deserialize(p); - } - else if ("include_media_info".equals(field)) { - f_includeMediaInfo = StoneSerializers.boolean_().deserialize(p); - } - else if ("include_deleted".equals(field)) { - f_includeDeleted = StoneSerializers.boolean_().deserialize(p); - } - else if ("include_has_explicit_shared_members".equals(field)) { - f_includeHasExplicitSharedMembers = StoneSerializers.boolean_().deserialize(p); - } - else { - skipValue(p); - } - } - if (f_path == null) { - throw new JsonParseException(p, "Required field \"path\" missing."); - } - value = new ListFolderArg(f_path, f_recursive, f_includeMediaInfo, f_includeDeleted, f_includeHasExplicitSharedMembers); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderBuilder.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderBuilder.java deleted file mode 100644 index 4e0075a3..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderBuilder.java +++ /dev/null @@ -1,111 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated by Stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import autosaveworld.zlibs.com.dropbox.core.DbxException; - -/** - * The request builder returned by {@link - * DbxUserFilesRequests#listFolderBuilder}. - * - *

Use this class to set optional request parameters and complete the - * request.

- */ -public class ListFolderBuilder { - private final DbxUserFilesRequests _client; - private final ListFolderArg.Builder _builder; - - /** - * Creates a new instance of this builder. - * - * @param _client Dropbox namespace-specific client used to issue files - * requests. - * @param _builder Request argument builder. - * - * @return instsance of this builder - */ - ListFolderBuilder(DbxUserFilesRequests _client, ListFolderArg.Builder _builder) { - if (_client == null) { - throw new NullPointerException("_client"); - } - this._client = _client; - if (_builder == null) { - throw new NullPointerException("_builder"); - } - this._builder = _builder; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}.

- * - * @param recursive If true, the list folder operation will be applied - * recursively to all subfolders and the response will contain contents - * of all subfolders. Defaults to {@code false} when set to {@code - * null}. - * - * @return this builder - */ - public ListFolderBuilder withRecursive(Boolean recursive) { - this._builder.withRecursive(recursive); - return this; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}.

- * - * @param includeMediaInfo If true, {@link FileMetadata#getMediaInfo} is - * set for photo and video. Defaults to {@code false} when set to {@code - * null}. - * - * @return this builder - */ - public ListFolderBuilder withIncludeMediaInfo(Boolean includeMediaInfo) { - this._builder.withIncludeMediaInfo(includeMediaInfo); - return this; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}.

- * - * @param includeDeleted If true, the results will include entries for - * files and folders that used to exist but were deleted. Defaults to - * {@code false} when set to {@code null}. - * - * @return this builder - */ - public ListFolderBuilder withIncludeDeleted(Boolean includeDeleted) { - this._builder.withIncludeDeleted(includeDeleted); - return this; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}.

- * - * @param includeHasExplicitSharedMembers If true, the results will include - * a flag for each file indicating whether or not that file has any - * explicit members. Defaults to {@code false} when set to {@code null}. - * - * @return this builder - */ - public ListFolderBuilder withIncludeHasExplicitSharedMembers(Boolean includeHasExplicitSharedMembers) { - this._builder.withIncludeHasExplicitSharedMembers(includeHasExplicitSharedMembers); - return this; - } - - /** - * Issues the request. - */ - public ListFolderResult start() throws ListFolderErrorException, DbxException { - ListFolderArg arg_ = this._builder.build(); - return _client.listFolder(arg_); - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderContinueArg.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderContinueArg.java deleted file mode 100644 index 478bc511..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderContinueArg.java +++ /dev/null @@ -1,145 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -class ListFolderContinueArg { - // struct files.ListFolderContinueArg (files.stone) - - protected final String cursor; - - /** - * - * @param cursor The cursor returned by your last call to {@link - * DbxUserFilesRequests#listFolder(String)} or {@link - * DbxUserFilesRequests#listFolderContinue(String)}. Must have length of - * at least 1 and not be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public ListFolderContinueArg(String cursor) { - if (cursor == null) { - throw new IllegalArgumentException("Required value for 'cursor' is null"); - } - if (cursor.length() < 1) { - throw new IllegalArgumentException("String 'cursor' is shorter than 1"); - } - this.cursor = cursor; - } - - /** - * The cursor returned by your last call to {@link - * DbxUserFilesRequests#listFolder(String)} or {@link - * DbxUserFilesRequests#listFolderContinue(String)}. - * - * @return value for this field, never {@code null}. - */ - public String getCursor() { - return cursor; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - cursor - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - ListFolderContinueArg other = (ListFolderContinueArg) obj; - return (this.cursor == other.cursor) || (this.cursor.equals(other.cursor)); - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(ListFolderContinueArg value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("cursor"); - StoneSerializers.string().serialize(value.cursor, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public ListFolderContinueArg deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - ListFolderContinueArg value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - String f_cursor = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("cursor".equals(field)) { - f_cursor = StoneSerializers.string().deserialize(p); - } - else { - skipValue(p); - } - } - if (f_cursor == null) { - throw new JsonParseException(p, "Required field \"cursor\" missing."); - } - value = new ListFolderContinueArg(f_cursor); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderContinueError.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderContinueError.java deleted file mode 100644 index 03fd8940..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderContinueError.java +++ /dev/null @@ -1,282 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.UnionSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * This class is an open tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isAbc()} - * methods will return {@code true}. You can use {@link #tag()} to determine the - * tag associated with this instance. - * - *

Open unions may be extended in the future with additional tags. If a new - * tag is introduced that this SDK does not recognized, the {@link #OTHER} value - * will be used.

- */ -public final class ListFolderContinueError { - // union files.ListFolderContinueError (files.stone) - - /** - * Discriminating tag type for {@link ListFolderContinueError}. - */ - public enum Tag { - PATH, // LookupError - /** - * Indicates that the cursor has been invalidated. Call {@link - * DbxUserFilesRequests#listFolder(String)} to obtain a new cursor. - */ - RESET, - /** - * Catch-all used for unknown tag values returned by the Dropbox - * servers. - * - *

Receiving a catch-all value typically indicates this SDK version - * is not up to date. Consider updating your SDK version to handle the - * new tags.

- */ - OTHER; // *catch_all - } - - /** - * Indicates that the cursor has been invalidated. Call {@link - * DbxUserFilesRequests#listFolder(String)} to obtain a new cursor. - */ - public static final ListFolderContinueError RESET = new ListFolderContinueError(Tag.RESET, null); - /** - * Catch-all used for unknown tag values returned by the Dropbox servers. - * - *

Receiving a catch-all value typically indicates this SDK version is - * not up to date. Consider updating your SDK version to handle the new - * tags.

- */ - public static final ListFolderContinueError OTHER = new ListFolderContinueError(Tag.OTHER, null); - - private final Tag _tag; - private final LookupError pathValue; - - /** - * - * @param pathValue Must not be {@code null}. - * @param _tag Discriminating tag for this instance. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - private ListFolderContinueError(Tag _tag, LookupError pathValue) { - this._tag = _tag; - this.pathValue = pathValue; - } - - /** - * Returns the tag for this instance. - * - *

This class is a tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isXyz()} - * methods will return {@code true}. Callers are recommended to use the tag - * value in a {@code switch} statement to properly handle the different - * values for this {@code ListFolderContinueError}.

- * - *

If a tag returned by the server is unrecognized by this SDK, the - * {@link Tag#OTHER} value will be used.

- * - * @return the tag for this instance. - */ - public Tag tag() { - return _tag; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#PATH}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#PATH}, - * {@code false} otherwise. - */ - public boolean isPath() { - return this._tag == Tag.PATH; - } - - /** - * Returns an instance of {@code ListFolderContinueError} that has its tag - * set to {@link Tag#PATH}. - * - *

None

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code ListFolderContinueError} with its tag set to - * {@link Tag#PATH}. - * - * @throws IllegalArgumentException if {@code value} is {@code null}. - */ - public static ListFolderContinueError path(LookupError value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - return new ListFolderContinueError(Tag.PATH, value); - } - - /** - * This instance must be tagged as {@link Tag#PATH}. - * - * @return The {@link LookupError} value associated with this instance if - * {@link #isPath} is {@code true}. - * - * @throws IllegalStateException If {@link #isPath} is {@code false}. - */ - public LookupError getPathValue() { - if (this._tag != Tag.PATH) { - throw new IllegalStateException("Invalid tag: required Tag.PATH, but was Tag." + this._tag.name()); - } - return pathValue; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#RESET}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#RESET}, - * {@code false} otherwise. - */ - public boolean isReset() { - return this._tag == Tag.RESET; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#OTHER}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#OTHER}, - * {@code false} otherwise. - */ - public boolean isOther() { - return this._tag == Tag.OTHER; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - _tag, - pathValue - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - else if (obj instanceof ListFolderContinueError) { - ListFolderContinueError other = (ListFolderContinueError) obj; - if (this._tag != other._tag) { - return false; - } - switch (_tag) { - case PATH: - return (this.pathValue == other.pathValue) || (this.pathValue.equals(other.pathValue)); - case RESET: - return true; - case OTHER: - return true; - default: - return false; - } - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends UnionSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(ListFolderContinueError value, JsonGenerator g) throws IOException, JsonGenerationException { - switch (value.tag()) { - case PATH: { - g.writeStartObject(); - writeTag("path", g); - g.writeFieldName("path"); - LookupError.Serializer.INSTANCE.serialize(value.pathValue, g); - g.writeEndObject(); - break; - } - case RESET: { - g.writeString("reset"); - break; - } - default: { - g.writeString("other"); - } - } - } - - @Override - public ListFolderContinueError deserialize(JsonParser p) throws IOException, JsonParseException { - ListFolderContinueError value; - boolean collapsed; - String tag; - if (p.getCurrentToken() == JsonToken.VALUE_STRING) { - collapsed = true; - tag = getStringValue(p); - p.nextToken(); - } - else { - collapsed = false; - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); - } - else if ("path".equals(tag)) { - LookupError fieldValue = null; - expectField("path", p); - fieldValue = LookupError.Serializer.INSTANCE.deserialize(p); - value = ListFolderContinueError.path(fieldValue); - } - else if ("reset".equals(tag)) { - value = ListFolderContinueError.RESET; - } - else { - value = ListFolderContinueError.OTHER; - skipFields(p); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderContinueErrorException.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderContinueErrorException.java deleted file mode 100644 index 96061e96..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderContinueErrorException.java +++ /dev/null @@ -1,35 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated by Stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import autosaveworld.zlibs.com.dropbox.core.DbxApiException; -import autosaveworld.zlibs.com.dropbox.core.LocalizedText; - -/** - * Exception thrown when the server responds with a {@link - * ListFolderContinueError} error. - * - *

This exception is raised by {@link - * DbxUserFilesRequests#listFolderContinue(String)}.

- */ -public class ListFolderContinueErrorException extends DbxApiException { - // exception for routes: - // 2/files/list_folder/continue - - private static final long serialVersionUID = 0L; - - /** - * The error reported by {@link - * DbxUserFilesRequests#listFolderContinue(String)}. - */ - public final ListFolderContinueError errorValue; - - public ListFolderContinueErrorException(String routeName, String requestId, LocalizedText userMessage, ListFolderContinueError errorValue) { - super(requestId, userMessage, buildMessage(routeName, userMessage, errorValue)); - if (errorValue == null) { - throw new NullPointerException("errorValue"); - } - this.errorValue = errorValue; - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderError.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderError.java deleted file mode 100644 index 86ad4e99..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderError.java +++ /dev/null @@ -1,252 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.UnionSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * This class is an open tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isAbc()} - * methods will return {@code true}. You can use {@link #tag()} to determine the - * tag associated with this instance. - * - *

Open unions may be extended in the future with additional tags. If a new - * tag is introduced that this SDK does not recognized, the {@link #OTHER} value - * will be used.

- */ -public final class ListFolderError { - // union files.ListFolderError (files.stone) - - /** - * Discriminating tag type for {@link ListFolderError}. - */ - public enum Tag { - PATH, // LookupError - /** - * Catch-all used for unknown tag values returned by the Dropbox - * servers. - * - *

Receiving a catch-all value typically indicates this SDK version - * is not up to date. Consider updating your SDK version to handle the - * new tags.

- */ - OTHER; // *catch_all - } - - /** - * Catch-all used for unknown tag values returned by the Dropbox servers. - * - *

Receiving a catch-all value typically indicates this SDK version is - * not up to date. Consider updating your SDK version to handle the new - * tags.

- */ - public static final ListFolderError OTHER = new ListFolderError(Tag.OTHER, null); - - private final Tag _tag; - private final LookupError pathValue; - - /** - * - * @param pathValue Must not be {@code null}. - * @param _tag Discriminating tag for this instance. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - private ListFolderError(Tag _tag, LookupError pathValue) { - this._tag = _tag; - this.pathValue = pathValue; - } - - /** - * Returns the tag for this instance. - * - *

This class is a tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isXyz()} - * methods will return {@code true}. Callers are recommended to use the tag - * value in a {@code switch} statement to properly handle the different - * values for this {@code ListFolderError}.

- * - *

If a tag returned by the server is unrecognized by this SDK, the - * {@link Tag#OTHER} value will be used.

- * - * @return the tag for this instance. - */ - public Tag tag() { - return _tag; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#PATH}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#PATH}, - * {@code false} otherwise. - */ - public boolean isPath() { - return this._tag == Tag.PATH; - } - - /** - * Returns an instance of {@code ListFolderError} that has its tag set to - * {@link Tag#PATH}. - * - *

None

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code ListFolderError} with its tag set to {@link - * Tag#PATH}. - * - * @throws IllegalArgumentException if {@code value} is {@code null}. - */ - public static ListFolderError path(LookupError value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - return new ListFolderError(Tag.PATH, value); - } - - /** - * This instance must be tagged as {@link Tag#PATH}. - * - * @return The {@link LookupError} value associated with this instance if - * {@link #isPath} is {@code true}. - * - * @throws IllegalStateException If {@link #isPath} is {@code false}. - */ - public LookupError getPathValue() { - if (this._tag != Tag.PATH) { - throw new IllegalStateException("Invalid tag: required Tag.PATH, but was Tag." + this._tag.name()); - } - return pathValue; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#OTHER}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#OTHER}, - * {@code false} otherwise. - */ - public boolean isOther() { - return this._tag == Tag.OTHER; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - _tag, - pathValue - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - else if (obj instanceof ListFolderError) { - ListFolderError other = (ListFolderError) obj; - if (this._tag != other._tag) { - return false; - } - switch (_tag) { - case PATH: - return (this.pathValue == other.pathValue) || (this.pathValue.equals(other.pathValue)); - case OTHER: - return true; - default: - return false; - } - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends UnionSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(ListFolderError value, JsonGenerator g) throws IOException, JsonGenerationException { - switch (value.tag()) { - case PATH: { - g.writeStartObject(); - writeTag("path", g); - g.writeFieldName("path"); - LookupError.Serializer.INSTANCE.serialize(value.pathValue, g); - g.writeEndObject(); - break; - } - default: { - g.writeString("other"); - } - } - } - - @Override - public ListFolderError deserialize(JsonParser p) throws IOException, JsonParseException { - ListFolderError value; - boolean collapsed; - String tag; - if (p.getCurrentToken() == JsonToken.VALUE_STRING) { - collapsed = true; - tag = getStringValue(p); - p.nextToken(); - } - else { - collapsed = false; - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); - } - else if ("path".equals(tag)) { - LookupError fieldValue = null; - expectField("path", p); - fieldValue = LookupError.Serializer.INSTANCE.deserialize(p); - value = ListFolderError.path(fieldValue); - } - else { - value = ListFolderError.OTHER; - skipFields(p); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderErrorException.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderErrorException.java deleted file mode 100644 index 8e24a985..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderErrorException.java +++ /dev/null @@ -1,38 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated by Stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import autosaveworld.zlibs.com.dropbox.core.DbxApiException; -import autosaveworld.zlibs.com.dropbox.core.LocalizedText; - -/** - * Exception thrown when the server responds with a {@link ListFolderError} - * error. - * - *

This exception is raised by {@link - * DbxUserFilesRequests#listFolderGetLatestCursor(String)} and {@link - * DbxUserFilesRequests#listFolder(String)}.

- */ -public class ListFolderErrorException extends DbxApiException { - // exception for routes: - // 2/files/list_folder/get_latest_cursor - // 2/files/list_folder - - private static final long serialVersionUID = 0L; - - /** - * The error reported by {@link - * DbxUserFilesRequests#listFolderGetLatestCursor(String)} and {@link - * DbxUserFilesRequests#listFolder(String)}. - */ - public final ListFolderError errorValue; - - public ListFolderErrorException(String routeName, String requestId, LocalizedText userMessage, ListFolderError errorValue) { - super(requestId, userMessage, buildMessage(routeName, userMessage, errorValue)); - if (errorValue == null) { - throw new NullPointerException("errorValue"); - } - this.errorValue = errorValue; - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderGetLatestCursorBuilder.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderGetLatestCursorBuilder.java deleted file mode 100644 index 0d5a87e8..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderGetLatestCursorBuilder.java +++ /dev/null @@ -1,111 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated by Stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import autosaveworld.zlibs.com.dropbox.core.DbxException; - -/** - * The request builder returned by {@link - * DbxUserFilesRequests#listFolderGetLatestCursorBuilder}. - * - *

Use this class to set optional request parameters and complete the - * request.

- */ -public class ListFolderGetLatestCursorBuilder { - private final DbxUserFilesRequests _client; - private final ListFolderArg.Builder _builder; - - /** - * Creates a new instance of this builder. - * - * @param _client Dropbox namespace-specific client used to issue files - * requests. - * @param _builder Request argument builder. - * - * @return instsance of this builder - */ - ListFolderGetLatestCursorBuilder(DbxUserFilesRequests _client, ListFolderArg.Builder _builder) { - if (_client == null) { - throw new NullPointerException("_client"); - } - this._client = _client; - if (_builder == null) { - throw new NullPointerException("_builder"); - } - this._builder = _builder; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}.

- * - * @param recursive If true, the list folder operation will be applied - * recursively to all subfolders and the response will contain contents - * of all subfolders. Defaults to {@code false} when set to {@code - * null}. - * - * @return this builder - */ - public ListFolderGetLatestCursorBuilder withRecursive(Boolean recursive) { - this._builder.withRecursive(recursive); - return this; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}.

- * - * @param includeMediaInfo If true, {@link FileMetadata#getMediaInfo} is - * set for photo and video. Defaults to {@code false} when set to {@code - * null}. - * - * @return this builder - */ - public ListFolderGetLatestCursorBuilder withIncludeMediaInfo(Boolean includeMediaInfo) { - this._builder.withIncludeMediaInfo(includeMediaInfo); - return this; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}.

- * - * @param includeDeleted If true, the results will include entries for - * files and folders that used to exist but were deleted. Defaults to - * {@code false} when set to {@code null}. - * - * @return this builder - */ - public ListFolderGetLatestCursorBuilder withIncludeDeleted(Boolean includeDeleted) { - this._builder.withIncludeDeleted(includeDeleted); - return this; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}.

- * - * @param includeHasExplicitSharedMembers If true, the results will include - * a flag for each file indicating whether or not that file has any - * explicit members. Defaults to {@code false} when set to {@code null}. - * - * @return this builder - */ - public ListFolderGetLatestCursorBuilder withIncludeHasExplicitSharedMembers(Boolean includeHasExplicitSharedMembers) { - this._builder.withIncludeHasExplicitSharedMembers(includeHasExplicitSharedMembers); - return this; - } - - /** - * Issues the request. - */ - public ListFolderGetLatestCursorResult start() throws ListFolderErrorException, DbxException { - ListFolderArg arg_ = this._builder.build(); - return _client.listFolderGetLatestCursor(arg_); - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderGetLatestCursorResult.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderGetLatestCursorResult.java deleted file mode 100644 index b0f3bd2f..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderGetLatestCursorResult.java +++ /dev/null @@ -1,145 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -public class ListFolderGetLatestCursorResult { - // struct files.ListFolderGetLatestCursorResult (files.stone) - - protected final String cursor; - - /** - * - * @param cursor Pass the cursor into {@link - * DbxUserFilesRequests#listFolderContinue(String)} to see what's - * changed in the folder since your previous query. Must have length of - * at least 1 and not be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public ListFolderGetLatestCursorResult(String cursor) { - if (cursor == null) { - throw new IllegalArgumentException("Required value for 'cursor' is null"); - } - if (cursor.length() < 1) { - throw new IllegalArgumentException("String 'cursor' is shorter than 1"); - } - this.cursor = cursor; - } - - /** - * Pass the cursor into {@link - * DbxUserFilesRequests#listFolderContinue(String)} to see what's changed in - * the folder since your previous query. - * - * @return value for this field, never {@code null}. - */ - public String getCursor() { - return cursor; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - cursor - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - ListFolderGetLatestCursorResult other = (ListFolderGetLatestCursorResult) obj; - return (this.cursor == other.cursor) || (this.cursor.equals(other.cursor)); - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(ListFolderGetLatestCursorResult value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("cursor"); - StoneSerializers.string().serialize(value.cursor, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public ListFolderGetLatestCursorResult deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - ListFolderGetLatestCursorResult value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - String f_cursor = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("cursor".equals(field)) { - f_cursor = StoneSerializers.string().deserialize(p); - } - else { - skipValue(p); - } - } - if (f_cursor == null) { - throw new JsonParseException(p, "Required field \"cursor\" missing."); - } - value = new ListFolderGetLatestCursorResult(f_cursor); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderResult.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderResult.java deleted file mode 100644 index 5bf89439..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/ListFolderResult.java +++ /dev/null @@ -1,205 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -public class ListFolderResult { - // struct files.ListFolderResult (files.stone) - - protected final List entries; - protected final String cursor; - protected final boolean hasMore; - - /** - * - * @param entries The files and (direct) subfolders in the folder. Must not - * contain a {@code null} item and not be {@code null}. - * @param cursor Pass the cursor into {@link - * DbxUserFilesRequests#listFolderContinue(String)} to see what's - * changed in the folder since your previous query. Must have length of - * at least 1 and not be {@code null}. - * @param hasMore If true, then there are more entries available. Pass the - * cursor to {@link DbxUserFilesRequests#listFolderContinue(String)} to - * retrieve the rest. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public ListFolderResult(List entries, String cursor, boolean hasMore) { - if (entries == null) { - throw new IllegalArgumentException("Required value for 'entries' is null"); - } - for (Metadata x : entries) { - if (x == null) { - throw new IllegalArgumentException("An item in list 'entries' is null"); - } - } - this.entries = entries; - if (cursor == null) { - throw new IllegalArgumentException("Required value for 'cursor' is null"); - } - if (cursor.length() < 1) { - throw new IllegalArgumentException("String 'cursor' is shorter than 1"); - } - this.cursor = cursor; - this.hasMore = hasMore; - } - - /** - * The files and (direct) subfolders in the folder. - * - * @return value for this field, never {@code null}. - */ - public List getEntries() { - return entries; - } - - /** - * Pass the cursor into {@link - * DbxUserFilesRequests#listFolderContinue(String)} to see what's changed in - * the folder since your previous query. - * - * @return value for this field, never {@code null}. - */ - public String getCursor() { - return cursor; - } - - /** - * If true, then there are more entries available. Pass the cursor to {@link - * DbxUserFilesRequests#listFolderContinue(String)} to retrieve the rest. - * - * @return value for this field. - */ - public boolean getHasMore() { - return hasMore; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - entries, - cursor, - hasMore - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - ListFolderResult other = (ListFolderResult) obj; - return ((this.entries == other.entries) || (this.entries.equals(other.entries))) - && ((this.cursor == other.cursor) || (this.cursor.equals(other.cursor))) - && (this.hasMore == other.hasMore) - ; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(ListFolderResult value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("entries"); - StoneSerializers.list(Metadata.Serializer.INSTANCE).serialize(value.entries, g); - g.writeFieldName("cursor"); - StoneSerializers.string().serialize(value.cursor, g); - g.writeFieldName("has_more"); - StoneSerializers.boolean_().serialize(value.hasMore, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public ListFolderResult deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - ListFolderResult value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - List f_entries = null; - String f_cursor = null; - Boolean f_hasMore = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("entries".equals(field)) { - f_entries = StoneSerializers.list(Metadata.Serializer.INSTANCE).deserialize(p); - } - else if ("cursor".equals(field)) { - f_cursor = StoneSerializers.string().deserialize(p); - } - else if ("has_more".equals(field)) { - f_hasMore = StoneSerializers.boolean_().deserialize(p); - } - else { - skipValue(p); - } - } - if (f_entries == null) { - throw new JsonParseException(p, "Required field \"entries\" missing."); - } - if (f_cursor == null) { - throw new JsonParseException(p, "Required field \"cursor\" missing."); - } - if (f_hasMore == null) { - throw new JsonParseException(p, "Required field \"has_more\" missing."); - } - value = new ListFolderResult(f_entries, f_cursor, f_hasMore); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/LookupError.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/LookupError.java deleted file mode 100644 index cab51a63..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/LookupError.java +++ /dev/null @@ -1,459 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.UnionSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * This class is an open tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isAbc()} - * methods will return {@code true}. You can use {@link #tag()} to determine the - * tag associated with this instance. - * - *

Open unions may be extended in the future with additional tags. If a new - * tag is introduced that this SDK does not recognized, the {@link #OTHER} value - * will be used.

- */ -public final class LookupError { - // union files.LookupError (files.stone) - - /** - * Discriminating tag type for {@link LookupError}. - */ - public enum Tag { - MALFORMED_PATH, // String - /** - * There is nothing at the given path. - */ - NOT_FOUND, - /** - * We were expecting a file, but the given path refers to something that - * isn't a file. - */ - NOT_FILE, - /** - * We were expecting a folder, but the given path refers to something - * that isn't a folder. - */ - NOT_FOLDER, - /** - * The file cannot be transferred because the content is restricted. - * For example, sometimes there are legal restrictions due to copyright - * claims. - */ - RESTRICTED_CONTENT, - /** - * The path root parameter provided is invalid. - */ - INVALID_PATH_ROOT, // PathRootError - /** - * Catch-all used for unknown tag values returned by the Dropbox - * servers. - * - *

Receiving a catch-all value typically indicates this SDK version - * is not up to date. Consider updating your SDK version to handle the - * new tags.

- */ - OTHER; // *catch_all - } - - /** - * There is nothing at the given path. - */ - public static final LookupError NOT_FOUND = new LookupError(Tag.NOT_FOUND, null, null); - /** - * We were expecting a file, but the given path refers to something that - * isn't a file. - */ - public static final LookupError NOT_FILE = new LookupError(Tag.NOT_FILE, null, null); - /** - * We were expecting a folder, but the given path refers to something that - * isn't a folder. - */ - public static final LookupError NOT_FOLDER = new LookupError(Tag.NOT_FOLDER, null, null); - /** - * The file cannot be transferred because the content is restricted. For - * example, sometimes there are legal restrictions due to copyright claims. - */ - public static final LookupError RESTRICTED_CONTENT = new LookupError(Tag.RESTRICTED_CONTENT, null, null); - /** - * Catch-all used for unknown tag values returned by the Dropbox servers. - * - *

Receiving a catch-all value typically indicates this SDK version is - * not up to date. Consider updating your SDK version to handle the new - * tags.

- */ - public static final LookupError OTHER = new LookupError(Tag.OTHER, null, null); - - private final Tag _tag; - private final String malformedPathValue; - private final PathRootError invalidPathRootValue; - - /** - * - * @param invalidPathRootValue The path root parameter provided is invalid. - * Must not be {@code null}. - * @param _tag Discriminating tag for this instance. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - private LookupError(Tag _tag, String malformedPathValue, PathRootError invalidPathRootValue) { - this._tag = _tag; - this.malformedPathValue = malformedPathValue; - this.invalidPathRootValue = invalidPathRootValue; - } - - /** - * Returns the tag for this instance. - * - *

This class is a tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isXyz()} - * methods will return {@code true}. Callers are recommended to use the tag - * value in a {@code switch} statement to properly handle the different - * values for this {@code LookupError}.

- * - *

If a tag returned by the server is unrecognized by this SDK, the - * {@link Tag#OTHER} value will be used.

- * - * @return the tag for this instance. - */ - public Tag tag() { - return _tag; - } - - /** - * Returns {@code true} if this instance has the tag {@link - * Tag#MALFORMED_PATH}, {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link - * Tag#MALFORMED_PATH}, {@code false} otherwise. - */ - public boolean isMalformedPath() { - return this._tag == Tag.MALFORMED_PATH; - } - - /** - * Returns an instance of {@code LookupError} that has its tag set to {@link - * Tag#MALFORMED_PATH}. - * - *

None

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code LookupError} with its tag set to {@link - * Tag#MALFORMED_PATH}. - */ - public static LookupError malformedPath(String value) { - return new LookupError(Tag.MALFORMED_PATH, value, null); - } - - /** - * Returns an instance of {@code LookupError} that has its tag set to {@link - * Tag#MALFORMED_PATH}. - * - *

None

- * - * @return Instance of {@code LookupError} with its tag set to {@link - * Tag#MALFORMED_PATH}. - */ - public static LookupError malformedPath() { - return malformedPath(null); - } - - /** - * This instance must be tagged as {@link Tag#MALFORMED_PATH}. - * - * @return The {@link String} value associated with this instance if {@link - * #isMalformedPath} is {@code true}. - * - * @throws IllegalStateException If {@link #isMalformedPath} is {@code - * false}. - */ - public String getMalformedPathValue() { - if (this._tag != Tag.MALFORMED_PATH) { - throw new IllegalStateException("Invalid tag: required Tag.MALFORMED_PATH, but was Tag." + this._tag.name()); - } - return malformedPathValue; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#NOT_FOUND}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#NOT_FOUND}, - * {@code false} otherwise. - */ - public boolean isNotFound() { - return this._tag == Tag.NOT_FOUND; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#NOT_FILE}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#NOT_FILE}, - * {@code false} otherwise. - */ - public boolean isNotFile() { - return this._tag == Tag.NOT_FILE; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#NOT_FOLDER}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link - * Tag#NOT_FOLDER}, {@code false} otherwise. - */ - public boolean isNotFolder() { - return this._tag == Tag.NOT_FOLDER; - } - - /** - * Returns {@code true} if this instance has the tag {@link - * Tag#RESTRICTED_CONTENT}, {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link - * Tag#RESTRICTED_CONTENT}, {@code false} otherwise. - */ - public boolean isRestrictedContent() { - return this._tag == Tag.RESTRICTED_CONTENT; - } - - /** - * Returns {@code true} if this instance has the tag {@link - * Tag#INVALID_PATH_ROOT}, {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link - * Tag#INVALID_PATH_ROOT}, {@code false} otherwise. - */ - public boolean isInvalidPathRoot() { - return this._tag == Tag.INVALID_PATH_ROOT; - } - - /** - * Returns an instance of {@code LookupError} that has its tag set to {@link - * Tag#INVALID_PATH_ROOT}. - * - *

The path root parameter provided is invalid.

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code LookupError} with its tag set to {@link - * Tag#INVALID_PATH_ROOT}. - * - * @throws IllegalArgumentException if {@code value} is {@code null}. - */ - public static LookupError invalidPathRoot(PathRootError value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - return new LookupError(Tag.INVALID_PATH_ROOT, null, value); - } - - /** - * The path root parameter provided is invalid. - * - *

This instance must be tagged as {@link Tag#INVALID_PATH_ROOT}.

- * - * @return The {@link PathRootError} value associated with this instance if - * {@link #isInvalidPathRoot} is {@code true}. - * - * @throws IllegalStateException If {@link #isInvalidPathRoot} is {@code - * false}. - */ - public PathRootError getInvalidPathRootValue() { - if (this._tag != Tag.INVALID_PATH_ROOT) { - throw new IllegalStateException("Invalid tag: required Tag.INVALID_PATH_ROOT, but was Tag." + this._tag.name()); - } - return invalidPathRootValue; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#OTHER}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#OTHER}, - * {@code false} otherwise. - */ - public boolean isOther() { - return this._tag == Tag.OTHER; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - _tag, - malformedPathValue, - invalidPathRootValue - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - else if (obj instanceof LookupError) { - LookupError other = (LookupError) obj; - if (this._tag != other._tag) { - return false; - } - switch (_tag) { - case MALFORMED_PATH: - return (this.malformedPathValue == other.malformedPathValue) || (this.malformedPathValue != null && this.malformedPathValue.equals(other.malformedPathValue)); - case NOT_FOUND: - return true; - case NOT_FILE: - return true; - case NOT_FOLDER: - return true; - case RESTRICTED_CONTENT: - return true; - case INVALID_PATH_ROOT: - return (this.invalidPathRootValue == other.invalidPathRootValue) || (this.invalidPathRootValue.equals(other.invalidPathRootValue)); - case OTHER: - return true; - default: - return false; - } - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - public static class Serializer extends UnionSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(LookupError value, JsonGenerator g) throws IOException, JsonGenerationException { - switch (value.tag()) { - case MALFORMED_PATH: { - g.writeStartObject(); - writeTag("malformed_path", g); - g.writeFieldName("malformed_path"); - StoneSerializers.nullable(StoneSerializers.string()).serialize(value.malformedPathValue, g); - g.writeEndObject(); - break; - } - case NOT_FOUND: { - g.writeString("not_found"); - break; - } - case NOT_FILE: { - g.writeString("not_file"); - break; - } - case NOT_FOLDER: { - g.writeString("not_folder"); - break; - } - case RESTRICTED_CONTENT: { - g.writeString("restricted_content"); - break; - } - case INVALID_PATH_ROOT: { - g.writeStartObject(); - writeTag("invalid_path_root", g); - PathRootError.Serializer.INSTANCE.serialize(value.invalidPathRootValue, g, true); - g.writeEndObject(); - break; - } - default: { - g.writeString("other"); - } - } - } - - @Override - public LookupError deserialize(JsonParser p) throws IOException, JsonParseException { - LookupError value; - boolean collapsed; - String tag; - if (p.getCurrentToken() == JsonToken.VALUE_STRING) { - collapsed = true; - tag = getStringValue(p); - p.nextToken(); - } - else { - collapsed = false; - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); - } - else if ("malformed_path".equals(tag)) { - String fieldValue = null; - if (p.getCurrentToken() != JsonToken.END_OBJECT) { - expectField("malformed_path", p); - fieldValue = StoneSerializers.nullable(StoneSerializers.string()).deserialize(p); - } - if (fieldValue == null) { - value = LookupError.malformedPath(); - } - else { - value = LookupError.malformedPath(fieldValue); - } - } - else if ("not_found".equals(tag)) { - value = LookupError.NOT_FOUND; - } - else if ("not_file".equals(tag)) { - value = LookupError.NOT_FILE; - } - else if ("not_folder".equals(tag)) { - value = LookupError.NOT_FOLDER; - } - else if ("restricted_content".equals(tag)) { - value = LookupError.RESTRICTED_CONTENT; - } - else if ("invalid_path_root".equals(tag)) { - PathRootError fieldValue = null; - fieldValue = PathRootError.Serializer.INSTANCE.deserialize(p, true); - value = LookupError.invalidPathRoot(fieldValue); - } - else { - value = LookupError.OTHER; - skipFields(p); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/MediaInfo.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/MediaInfo.java deleted file mode 100644 index b9a40d8e..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/MediaInfo.java +++ /dev/null @@ -1,250 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.UnionSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * This class is a tagged union. Tagged unions instances are always associated - * to a specific tag. This means only one of the {@code isAbc()} methods will - * return {@code true}. You can use {@link #tag()} to determine the tag - * associated with this instance. - */ -public final class MediaInfo { - // union files.MediaInfo (files.stone) - - /** - * Discriminating tag type for {@link MediaInfo}. - */ - public enum Tag { - /** - * Indicate the photo/video is still under processing and metadata is - * not available yet. - */ - PENDING, - /** - * The metadata for the photo/video. - */ - METADATA; // MediaMetadata - } - - /** - * Indicate the photo/video is still under processing and metadata is not - * available yet. - */ - public static final MediaInfo PENDING = new MediaInfo(Tag.PENDING, null); - - private final Tag _tag; - private final MediaMetadata metadataValue; - - /** - * - * @param metadataValue The metadata for the photo/video. Must not be - * {@code null}. - * @param _tag Discriminating tag for this instance. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - private MediaInfo(Tag _tag, MediaMetadata metadataValue) { - this._tag = _tag; - this.metadataValue = metadataValue; - } - - /** - * Returns the tag for this instance. - * - *

This class is a tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isXyz()} - * methods will return {@code true}. Callers are recommended to use the tag - * value in a {@code switch} statement to properly handle the different - * values for this {@code MediaInfo}.

- * - * @return the tag for this instance. - */ - public Tag tag() { - return _tag; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#PENDING}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#PENDING}, - * {@code false} otherwise. - */ - public boolean isPending() { - return this._tag == Tag.PENDING; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#METADATA}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#METADATA}, - * {@code false} otherwise. - */ - public boolean isMetadata() { - return this._tag == Tag.METADATA; - } - - /** - * Returns an instance of {@code MediaInfo} that has its tag set to {@link - * Tag#METADATA}. - * - *

The metadata for the photo/video.

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code MediaInfo} with its tag set to {@link - * Tag#METADATA}. - * - * @throws IllegalArgumentException if {@code value} is {@code null}. - */ - public static MediaInfo metadata(MediaMetadata value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - return new MediaInfo(Tag.METADATA, value); - } - - /** - * The metadata for the photo/video. - * - *

This instance must be tagged as {@link Tag#METADATA}.

- * - * @return The {@link MediaMetadata} value associated with this instance if - * {@link #isMetadata} is {@code true}. - * - * @throws IllegalStateException If {@link #isMetadata} is {@code false}. - */ - public MediaMetadata getMetadataValue() { - if (this._tag != Tag.METADATA) { - throw new IllegalStateException("Invalid tag: required Tag.METADATA, but was Tag." + this._tag.name()); - } - return metadataValue; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - _tag, - metadataValue - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - else if (obj instanceof MediaInfo) { - MediaInfo other = (MediaInfo) obj; - if (this._tag != other._tag) { - return false; - } - switch (_tag) { - case PENDING: - return true; - case METADATA: - return (this.metadataValue == other.metadataValue) || (this.metadataValue.equals(other.metadataValue)); - default: - return false; - } - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends UnionSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(MediaInfo value, JsonGenerator g) throws IOException, JsonGenerationException { - switch (value.tag()) { - case PENDING: { - g.writeString("pending"); - break; - } - case METADATA: { - g.writeStartObject(); - writeTag("metadata", g); - g.writeFieldName("metadata"); - MediaMetadata.Serializer.INSTANCE.serialize(value.metadataValue, g); - g.writeEndObject(); - break; - } - default: { - throw new IllegalArgumentException("Unrecognized tag: " + value.tag()); - } - } - } - - @Override - public MediaInfo deserialize(JsonParser p) throws IOException, JsonParseException { - MediaInfo value; - boolean collapsed; - String tag; - if (p.getCurrentToken() == JsonToken.VALUE_STRING) { - collapsed = true; - tag = getStringValue(p); - p.nextToken(); - } - else { - collapsed = false; - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); - } - else if ("pending".equals(tag)) { - value = MediaInfo.PENDING; - } - else if ("metadata".equals(tag)) { - MediaMetadata fieldValue = null; - expectField("metadata", p); - fieldValue = MediaMetadata.Serializer.INSTANCE.deserialize(p); - value = MediaInfo.metadata(fieldValue); - } - else { - throw new JsonParseException(p, "Unknown tag: " + tag); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/MediaMetadata.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/MediaMetadata.java deleted file mode 100644 index 39fd6901..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/MediaMetadata.java +++ /dev/null @@ -1,284 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Date; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.dropbox.core.util.LangUtil; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * Metadata for a photo or video. - */ -public class MediaMetadata { - // struct files.MediaMetadata (files.stone) - - protected final Dimensions dimensions; - protected final GpsCoordinates location; - protected final Date timeTaken; - - /** - * Metadata for a photo or video. - * - *

Use {@link newBuilder} to create instances of this class without - * specifying values for all optional fields.

- * - * @param dimensions Dimension of the photo/video. - * @param location The GPS coordinate of the photo/video. - * @param timeTaken The timestamp when the photo/video is taken. - */ - public MediaMetadata(Dimensions dimensions, GpsCoordinates location, Date timeTaken) { - this.dimensions = dimensions; - this.location = location; - this.timeTaken = LangUtil.truncateMillis(timeTaken); - } - - /** - * Metadata for a photo or video. - * - *

The default values for unset fields will be used.

- */ - public MediaMetadata() { - this(null, null, null); - } - - /** - * Dimension of the photo/video. - * - * @return value for this field, or {@code null} if not present. - */ - public Dimensions getDimensions() { - return dimensions; - } - - /** - * The GPS coordinate of the photo/video. - * - * @return value for this field, or {@code null} if not present. - */ - public GpsCoordinates getLocation() { - return location; - } - - /** - * The timestamp when the photo/video is taken. - * - * @return value for this field, or {@code null} if not present. - */ - public Date getTimeTaken() { - return timeTaken; - } - - /** - * Returns a new builder for creating an instance of this class. - * - * @return builder for this class. - */ - public static Builder newBuilder() { - return new Builder(); - } - - /** - * Builder for {@link MediaMetadata}. - */ - public static class Builder { - - protected Dimensions dimensions; - protected GpsCoordinates location; - protected Date timeTaken; - - protected Builder() { - this.dimensions = null; - this.location = null; - this.timeTaken = null; - } - - /** - * Set value for optional field. - * - * @param dimensions Dimension of the photo/video. - * - * @return this builder - */ - public Builder withDimensions(Dimensions dimensions) { - this.dimensions = dimensions; - return this; - } - - /** - * Set value for optional field. - * - * @param location The GPS coordinate of the photo/video. - * - * @return this builder - */ - public Builder withLocation(GpsCoordinates location) { - this.location = location; - return this; - } - - /** - * Set value for optional field. - * - * @param timeTaken The timestamp when the photo/video is taken. - * - * @return this builder - */ - public Builder withTimeTaken(Date timeTaken) { - this.timeTaken = LangUtil.truncateMillis(timeTaken); - return this; - } - - /** - * Builds an instance of {@link MediaMetadata} configured with this - * builder's values - * - * @return new instance of {@link MediaMetadata} - */ - public MediaMetadata build() { - return new MediaMetadata(dimensions, location, timeTaken); - } - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - dimensions, - location, - timeTaken - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - MediaMetadata other = (MediaMetadata) obj; - return ((this.dimensions == other.dimensions) || (this.dimensions != null && this.dimensions.equals(other.dimensions))) - && ((this.location == other.location) || (this.location != null && this.location.equals(other.location))) - && ((this.timeTaken == other.timeTaken) || (this.timeTaken != null && this.timeTaken.equals(other.timeTaken))) - ; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(MediaMetadata value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (value instanceof PhotoMetadata) { - PhotoMetadata.Serializer.INSTANCE.serialize((PhotoMetadata) value, g, collapse); - return; - } - if (value instanceof VideoMetadata) { - VideoMetadata.Serializer.INSTANCE.serialize((VideoMetadata) value, g, collapse); - return; - } - if (!collapse) { - g.writeStartObject(); - } - if (value.dimensions != null) { - g.writeFieldName("dimensions"); - StoneSerializers.nullable(Dimensions.Serializer.INSTANCE).serialize(value.dimensions, g); - } - if (value.location != null) { - g.writeFieldName("location"); - StoneSerializers.nullable(GpsCoordinates.Serializer.INSTANCE).serialize(value.location, g); - } - if (value.timeTaken != null) { - g.writeFieldName("time_taken"); - StoneSerializers.nullable(StoneSerializers.timestamp()).serialize(value.timeTaken, g); - } - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public MediaMetadata deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - MediaMetadata value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - if ("".equals(tag)) { - tag = null; - } - } - if (tag == null) { - Dimensions f_dimensions = null; - GpsCoordinates f_location = null; - Date f_timeTaken = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("dimensions".equals(field)) { - f_dimensions = StoneSerializers.nullable(Dimensions.Serializer.INSTANCE).deserialize(p); - } - else if ("location".equals(field)) { - f_location = StoneSerializers.nullable(GpsCoordinates.Serializer.INSTANCE).deserialize(p); - } - else if ("time_taken".equals(field)) { - f_timeTaken = StoneSerializers.nullable(StoneSerializers.timestamp()).deserialize(p); - } - else { - skipValue(p); - } - } - value = new MediaMetadata(f_dimensions, f_location, f_timeTaken); - } - else if ("".equals(tag)) { - value = Serializer.INSTANCE.deserialize(p, true); - } - else if ("photo".equals(tag)) { - value = PhotoMetadata.Serializer.INSTANCE.deserialize(p, true); - } - else if ("video".equals(tag)) { - value = VideoMetadata.Serializer.INSTANCE.deserialize(p, true); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/Metadata.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/Metadata.java deleted file mode 100644 index 6ffb5aa7..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/Metadata.java +++ /dev/null @@ -1,378 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * Metadata for a file or folder. - */ -public class Metadata { - // struct files.Metadata (files.stone) - - protected final String name; - protected final String pathLower; - protected final String pathDisplay; - protected final String parentSharedFolderId; - - /** - * Metadata for a file or folder. - * - *

Use {@link newBuilder} to create instances of this class without - * specifying values for all optional fields.

- * - * @param name The last component of the path (including extension). This - * never contains a slash. Must not be {@code null}. - * @param pathLower The lowercased full path in the user's Dropbox. This - * always starts with a slash. This field will be null if the file or - * folder is not mounted. - * @param pathDisplay The cased path to be used for display purposes only. - * In rare instances the casing will not correctly match the user's - * filesystem, but this behavior will match the path provided in the - * Core API v1. Changes to the casing of paths won't be returned by - * {@link DbxUserFilesRequests#listFolderContinue(String)}. This field - * will be null if the file or folder is not mounted. - * @param parentSharedFolderId Deprecated. Please use {@link - * FileSharingInfo#getParentSharedFolderId} or {@link - * FolderSharingInfo#getParentSharedFolderId} instead. Must match - * pattern "{@code [-_0-9a-zA-Z:]+}". - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public Metadata(String name, String pathLower, String pathDisplay, String parentSharedFolderId) { - if (name == null) { - throw new IllegalArgumentException("Required value for 'name' is null"); - } - this.name = name; - this.pathLower = pathLower; - this.pathDisplay = pathDisplay; - if (parentSharedFolderId != null) { - if (!java.util.regex.Pattern.matches("[-_0-9a-zA-Z:]+", parentSharedFolderId)) { - throw new IllegalArgumentException("String 'parentSharedFolderId' does not match pattern"); - } - } - this.parentSharedFolderId = parentSharedFolderId; - } - - /** - * Metadata for a file or folder. - * - *

The default values for unset fields will be used.

- * - * @param name The last component of the path (including extension). This - * never contains a slash. Must not be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public Metadata(String name) { - this(name, null, null, null); - } - - /** - * The last component of the path (including extension). This never contains - * a slash. - * - * @return value for this field, never {@code null}. - */ - public String getName() { - return name; - } - - /** - * The lowercased full path in the user's Dropbox. This always starts with a - * slash. This field will be null if the file or folder is not mounted. - * - * @return value for this field, or {@code null} if not present. - */ - public String getPathLower() { - return pathLower; - } - - /** - * The cased path to be used for display purposes only. In rare instances - * the casing will not correctly match the user's filesystem, but this - * behavior will match the path provided in the Core API v1. Changes to the - * casing of paths won't be returned by {@link - * DbxUserFilesRequests#listFolderContinue(String)}. This field will be null - * if the file or folder is not mounted. - * - * @return value for this field, or {@code null} if not present. - */ - public String getPathDisplay() { - return pathDisplay; - } - - /** - * Deprecated. Please use {@link FileSharingInfo#getParentSharedFolderId} or - * {@link FolderSharingInfo#getParentSharedFolderId} instead. - * - * @return value for this field, or {@code null} if not present. - */ - public String getParentSharedFolderId() { - return parentSharedFolderId; - } - - /** - * Returns a new builder for creating an instance of this class. - * - * @param name The last component of the path (including extension). This - * never contains a slash. Must not be {@code null}. - * - * @return builder for this class. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public static Builder newBuilder(String name) { - return new Builder(name); - } - - /** - * Builder for {@link Metadata}. - */ - public static class Builder { - protected final String name; - - protected String pathLower; - protected String pathDisplay; - protected String parentSharedFolderId; - - protected Builder(String name) { - if (name == null) { - throw new IllegalArgumentException("Required value for 'name' is null"); - } - this.name = name; - this.pathLower = null; - this.pathDisplay = null; - this.parentSharedFolderId = null; - } - - /** - * Set value for optional field. - * - * @param pathLower The lowercased full path in the user's Dropbox. - * This always starts with a slash. This field will be null if the - * file or folder is not mounted. - * - * @return this builder - */ - public Builder withPathLower(String pathLower) { - this.pathLower = pathLower; - return this; - } - - /** - * Set value for optional field. - * - * @param pathDisplay The cased path to be used for display purposes - * only. In rare instances the casing will not correctly match the - * user's filesystem, but this behavior will match the path provided - * in the Core API v1. Changes to the casing of paths won't be - * returned by {@link - * DbxUserFilesRequests#listFolderContinue(String)}. This field will - * be null if the file or folder is not mounted. - * - * @return this builder - */ - public Builder withPathDisplay(String pathDisplay) { - this.pathDisplay = pathDisplay; - return this; - } - - /** - * Set value for optional field. - * - * @param parentSharedFolderId Deprecated. Please use {@link - * FileSharingInfo#getParentSharedFolderId} or {@link - * FolderSharingInfo#getParentSharedFolderId} instead. Must match - * pattern "{@code [-_0-9a-zA-Z:]+}". - * - * @return this builder - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public Builder withParentSharedFolderId(String parentSharedFolderId) { - if (parentSharedFolderId != null) { - if (!java.util.regex.Pattern.matches("[-_0-9a-zA-Z:]+", parentSharedFolderId)) { - throw new IllegalArgumentException("String 'parentSharedFolderId' does not match pattern"); - } - } - this.parentSharedFolderId = parentSharedFolderId; - return this; - } - - /** - * Builds an instance of {@link Metadata} configured with this builder's - * values - * - * @return new instance of {@link Metadata} - */ - public Metadata build() { - return new Metadata(name, pathLower, pathDisplay, parentSharedFolderId); - } - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - name, - pathLower, - pathDisplay, - parentSharedFolderId - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - Metadata other = (Metadata) obj; - return ((this.name == other.name) || (this.name.equals(other.name))) - && ((this.pathLower == other.pathLower) || (this.pathLower != null && this.pathLower.equals(other.pathLower))) - && ((this.pathDisplay == other.pathDisplay) || (this.pathDisplay != null && this.pathDisplay.equals(other.pathDisplay))) - && ((this.parentSharedFolderId == other.parentSharedFolderId) || (this.parentSharedFolderId != null && this.parentSharedFolderId.equals(other.parentSharedFolderId))) - ; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(Metadata value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (value instanceof FileMetadata) { - FileMetadata.Serializer.INSTANCE.serialize((FileMetadata) value, g, collapse); - return; - } - if (value instanceof FolderMetadata) { - FolderMetadata.Serializer.INSTANCE.serialize((FolderMetadata) value, g, collapse); - return; - } - if (value instanceof DeletedMetadata) { - DeletedMetadata.Serializer.INSTANCE.serialize((DeletedMetadata) value, g, collapse); - return; - } - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("name"); - StoneSerializers.string().serialize(value.name, g); - if (value.pathLower != null) { - g.writeFieldName("path_lower"); - StoneSerializers.nullable(StoneSerializers.string()).serialize(value.pathLower, g); - } - if (value.pathDisplay != null) { - g.writeFieldName("path_display"); - StoneSerializers.nullable(StoneSerializers.string()).serialize(value.pathDisplay, g); - } - if (value.parentSharedFolderId != null) { - g.writeFieldName("parent_shared_folder_id"); - StoneSerializers.nullable(StoneSerializers.string()).serialize(value.parentSharedFolderId, g); - } - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public Metadata deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - Metadata value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - if ("".equals(tag)) { - tag = null; - } - } - if (tag == null) { - String f_name = null; - String f_pathLower = null; - String f_pathDisplay = null; - String f_parentSharedFolderId = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("name".equals(field)) { - f_name = StoneSerializers.string().deserialize(p); - } - else if ("path_lower".equals(field)) { - f_pathLower = StoneSerializers.nullable(StoneSerializers.string()).deserialize(p); - } - else if ("path_display".equals(field)) { - f_pathDisplay = StoneSerializers.nullable(StoneSerializers.string()).deserialize(p); - } - else if ("parent_shared_folder_id".equals(field)) { - f_parentSharedFolderId = StoneSerializers.nullable(StoneSerializers.string()).deserialize(p); - } - else { - skipValue(p); - } - } - if (f_name == null) { - throw new JsonParseException(p, "Required field \"name\" missing."); - } - value = new Metadata(f_name, f_pathLower, f_pathDisplay, f_parentSharedFolderId); - } - else if ("".equals(tag)) { - value = Serializer.INSTANCE.deserialize(p, true); - } - else if ("file".equals(tag)) { - value = FileMetadata.Serializer.INSTANCE.deserialize(p, true); - } - else if ("folder".equals(tag)) { - value = FolderMetadata.Serializer.INSTANCE.deserialize(p, true); - } - else if ("deleted".equals(tag)) { - value = DeletedMetadata.Serializer.INSTANCE.deserialize(p, true); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/PathRootError.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/PathRootError.java deleted file mode 100644 index 552c1c07..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/PathRootError.java +++ /dev/null @@ -1,141 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -public class PathRootError { - // struct files.PathRootError (files.stone) - - protected final String pathRoot; - - /** - * - * @param pathRoot The user's latest path root value. None if the user no - * longer has a path root. - */ - public PathRootError(String pathRoot) { - this.pathRoot = pathRoot; - } - - /** - * None - * - *

The default values for unset fields will be used.

- */ - public PathRootError() { - this(null); - } - - /** - * The user's latest path root value. None if the user no longer has a path - * root. - * - * @return value for this field, or {@code null} if not present. - */ - public String getPathRoot() { - return pathRoot; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - pathRoot - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - PathRootError other = (PathRootError) obj; - return (this.pathRoot == other.pathRoot) || (this.pathRoot != null && this.pathRoot.equals(other.pathRoot)); - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - public static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(PathRootError value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - if (value.pathRoot != null) { - g.writeFieldName("path_root"); - StoneSerializers.nullable(StoneSerializers.string()).serialize(value.pathRoot, g); - } - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public PathRootError deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - PathRootError value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - String f_pathRoot = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("path_root".equals(field)) { - f_pathRoot = StoneSerializers.nullable(StoneSerializers.string()).deserialize(p); - } - else { - skipValue(p); - } - } - value = new PathRootError(f_pathRoot); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/PhotoMetadata.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/PhotoMetadata.java deleted file mode 100644 index 8e6c86c6..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/PhotoMetadata.java +++ /dev/null @@ -1,250 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Date; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * Metadata for a photo. - */ -public class PhotoMetadata extends MediaMetadata { - // struct files.PhotoMetadata (files.stone) - - - /** - * Metadata for a photo. - * - *

Use {@link newBuilder} to create instances of this class without - * specifying values for all optional fields.

- * - * @param dimensions Dimension of the photo/video. - * @param location The GPS coordinate of the photo/video. - * @param timeTaken The timestamp when the photo/video is taken. - */ - public PhotoMetadata(Dimensions dimensions, GpsCoordinates location, Date timeTaken) { - super(dimensions, location, timeTaken); - } - - /** - * Metadata for a photo. - * - *

The default values for unset fields will be used.

- */ - public PhotoMetadata() { - this(null, null, null); - } - - /** - * Dimension of the photo/video. - * - * @return value for this field, or {@code null} if not present. - */ - public Dimensions getDimensions() { - return dimensions; - } - - /** - * The GPS coordinate of the photo/video. - * - * @return value for this field, or {@code null} if not present. - */ - public GpsCoordinates getLocation() { - return location; - } - - /** - * The timestamp when the photo/video is taken. - * - * @return value for this field, or {@code null} if not present. - */ - public Date getTimeTaken() { - return timeTaken; - } - - /** - * Returns a new builder for creating an instance of this class. - * - * @return builder for this class. - */ - public static Builder newBuilder() { - return new Builder(); - } - - /** - * Builder for {@link PhotoMetadata}. - */ - public static class Builder extends MediaMetadata.Builder { - - protected Builder() { - } - - /** - * Set value for optional field. - * - * @param dimensions Dimension of the photo/video. - * - * @return this builder - */ - public Builder withDimensions(Dimensions dimensions) { - super.withDimensions(dimensions); - return this; - } - - /** - * Set value for optional field. - * - * @param location The GPS coordinate of the photo/video. - * - * @return this builder - */ - public Builder withLocation(GpsCoordinates location) { - super.withLocation(location); - return this; - } - - /** - * Set value for optional field. - * - * @param timeTaken The timestamp when the photo/video is taken. - * - * @return this builder - */ - public Builder withTimeTaken(Date timeTaken) { - super.withTimeTaken(timeTaken); - return this; - } - - /** - * Builds an instance of {@link PhotoMetadata} configured with this - * builder's values - * - * @return new instance of {@link PhotoMetadata} - */ - public PhotoMetadata build() { - return new PhotoMetadata(dimensions, location, timeTaken); - } - } - - @Override - public int hashCode() { - // attempt to deal with inheritance - return getClass().toString().hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - PhotoMetadata other = (PhotoMetadata) obj; - return ((this.dimensions == other.dimensions) || (this.dimensions != null && this.dimensions.equals(other.dimensions))) - && ((this.location == other.location) || (this.location != null && this.location.equals(other.location))) - && ((this.timeTaken == other.timeTaken) || (this.timeTaken != null && this.timeTaken.equals(other.timeTaken))) - ; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(PhotoMetadata value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - writeTag("photo", g); - if (value.dimensions != null) { - g.writeFieldName("dimensions"); - StoneSerializers.nullable(Dimensions.Serializer.INSTANCE).serialize(value.dimensions, g); - } - if (value.location != null) { - g.writeFieldName("location"); - StoneSerializers.nullable(GpsCoordinates.Serializer.INSTANCE).serialize(value.location, g); - } - if (value.timeTaken != null) { - g.writeFieldName("time_taken"); - StoneSerializers.nullable(StoneSerializers.timestamp()).serialize(value.timeTaken, g); - } - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public PhotoMetadata deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - PhotoMetadata value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - if ("photo".equals(tag)) { - tag = null; - } - } - if (tag == null) { - Dimensions f_dimensions = null; - GpsCoordinates f_location = null; - Date f_timeTaken = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("dimensions".equals(field)) { - f_dimensions = StoneSerializers.nullable(Dimensions.Serializer.INSTANCE).deserialize(p); - } - else if ("location".equals(field)) { - f_location = StoneSerializers.nullable(GpsCoordinates.Serializer.INSTANCE).deserialize(p); - } - else if ("time_taken".equals(field)) { - f_timeTaken = StoneSerializers.nullable(StoneSerializers.timestamp()).deserialize(p); - } - else { - skipValue(p); - } - } - value = new PhotoMetadata(f_dimensions, f_location, f_timeTaken); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/SharingInfo.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/SharingInfo.java deleted file mode 100644 index 772e3ff9..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/SharingInfo.java +++ /dev/null @@ -1,136 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * Sharing info for a file or folder. - */ -public class SharingInfo { - // struct files.SharingInfo (files.stone) - - protected final boolean readOnly; - - /** - * Sharing info for a file or folder. - * - * @param readOnly True if the file or folder is inside a read-only shared - * folder. - */ - public SharingInfo(boolean readOnly) { - this.readOnly = readOnly; - } - - /** - * True if the file or folder is inside a read-only shared folder. - * - * @return value for this field. - */ - public boolean getReadOnly() { - return readOnly; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - readOnly - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - SharingInfo other = (SharingInfo) obj; - return this.readOnly == other.readOnly; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - private static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(SharingInfo value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("read_only"); - StoneSerializers.boolean_().serialize(value.readOnly, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public SharingInfo deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - SharingInfo value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - Boolean f_readOnly = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("read_only".equals(field)) { - f_readOnly = StoneSerializers.boolean_().deserialize(p); - } - else { - skipValue(p); - } - } - if (f_readOnly == null) { - throw new JsonParseException(p, "Required field \"read_only\" missing."); - } - value = new SharingInfo(f_readOnly); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadBuilder.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadBuilder.java deleted file mode 100644 index 6899b3cf..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadBuilder.java +++ /dev/null @@ -1,118 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated by Stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.util.Date; - -import autosaveworld.zlibs.com.dropbox.core.DbxException; -import autosaveworld.zlibs.com.dropbox.core.v2.DbxUploadStyleBuilder; - -/** - * The request builder returned by {@link DbxUserFilesRequests#uploadBuilder}. - * - *

Use this class to set optional request parameters and complete the - * request.

- */ -public class UploadBuilder extends DbxUploadStyleBuilder { - private final DbxUserFilesRequests _client; - private final CommitInfo.Builder _builder; - - /** - * Creates a new instance of this builder. - * - * @param _client Dropbox namespace-specific client used to issue files - * requests. - * @param _builder Request argument builder. - * - * @return instsance of this builder - */ - UploadBuilder(DbxUserFilesRequests _client, CommitInfo.Builder _builder) { - if (_client == null) { - throw new NullPointerException("_client"); - } - this._client = _client; - if (_builder == null) { - throw new NullPointerException("_builder"); - } - this._builder = _builder; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code - * WriteMode.ADD}.

- * - * @param mode Selects what to do if the file already exists. Must not be - * {@code null}. Defaults to {@code WriteMode.ADD} when set to {@code - * null}. - * - * @return this builder - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public UploadBuilder withMode(WriteMode mode) { - this._builder.withMode(mode); - return this; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}.

- * - * @param autorename If there's a conflict, as determined by {@link - * CommitInfo#getMode}, have the Dropbox server try to autorename the - * file to avoid conflict. Defaults to {@code false} when set to {@code - * null}. - * - * @return this builder - */ - public UploadBuilder withAutorename(Boolean autorename) { - this._builder.withAutorename(autorename); - return this; - } - - /** - * Set value for optional field. - * - * @param clientModified The value to store as the {@link - * CommitInfo#getClientModified} timestamp. Dropbox automatically - * records the time at which the file was written to the Dropbox - * servers. It can also record an additional timestamp, provided by - * Dropbox desktop clients, mobile clients, and API apps of when the - * file was actually created or modified. - * - * @return this builder - */ - public UploadBuilder withClientModified(Date clientModified) { - this._builder.withClientModified(clientModified); - return this; - } - - /** - * Set value for optional field. - * - *

If left unset or set to {@code null}, defaults to {@code false}.

- * - * @param mute Normally, users are made aware of any file modifications in - * their Dropbox account via notifications in the client software. If - * {@code true}, this tells the clients that this modification shouldn't - * result in a user notification. Defaults to {@code false} when set to - * {@code null}. - * - * @return this builder - */ - public UploadBuilder withMute(Boolean mute) { - this._builder.withMute(mute); - return this; - } - - @Override - public UploadUploader start() throws UploadErrorException, DbxException { - CommitInfo arg_ = this._builder.build(); - return _client.upload(arg_); - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadError.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadError.java deleted file mode 100644 index 9250eeed..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadError.java +++ /dev/null @@ -1,256 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.UnionSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * This class is an open tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isAbc()} - * methods will return {@code true}. You can use {@link #tag()} to determine the - * tag associated with this instance. - * - *

Open unions may be extended in the future with additional tags. If a new - * tag is introduced that this SDK does not recognized, the {@link #OTHER} value - * will be used.

- */ -public final class UploadError { - // union files.UploadError (files.stone) - - /** - * Discriminating tag type for {@link UploadError}. - */ - public enum Tag { - /** - * Unable to save the uploaded contents to a file. - */ - PATH, // UploadWriteFailed - /** - * Catch-all used for unknown tag values returned by the Dropbox - * servers. - * - *

Receiving a catch-all value typically indicates this SDK version - * is not up to date. Consider updating your SDK version to handle the - * new tags.

- */ - OTHER; // *catch_all - } - - /** - * Catch-all used for unknown tag values returned by the Dropbox servers. - * - *

Receiving a catch-all value typically indicates this SDK version is - * not up to date. Consider updating your SDK version to handle the new - * tags.

- */ - public static final UploadError OTHER = new UploadError(Tag.OTHER, null); - - private final Tag _tag; - private final UploadWriteFailed pathValue; - - /** - * - * @param pathValue Unable to save the uploaded contents to a file. Must - * not be {@code null}. - * @param _tag Discriminating tag for this instance. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - private UploadError(Tag _tag, UploadWriteFailed pathValue) { - this._tag = _tag; - this.pathValue = pathValue; - } - - /** - * Returns the tag for this instance. - * - *

This class is a tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isXyz()} - * methods will return {@code true}. Callers are recommended to use the tag - * value in a {@code switch} statement to properly handle the different - * values for this {@code UploadError}.

- * - *

If a tag returned by the server is unrecognized by this SDK, the - * {@link Tag#OTHER} value will be used.

- * - * @return the tag for this instance. - */ - public Tag tag() { - return _tag; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#PATH}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#PATH}, - * {@code false} otherwise. - */ - public boolean isPath() { - return this._tag == Tag.PATH; - } - - /** - * Returns an instance of {@code UploadError} that has its tag set to {@link - * Tag#PATH}. - * - *

Unable to save the uploaded contents to a file.

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code UploadError} with its tag set to {@link - * Tag#PATH}. - * - * @throws IllegalArgumentException if {@code value} is {@code null}. - */ - public static UploadError path(UploadWriteFailed value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - return new UploadError(Tag.PATH, value); - } - - /** - * Unable to save the uploaded contents to a file. - * - *

This instance must be tagged as {@link Tag#PATH}.

- * - * @return The {@link UploadWriteFailed} value associated with this instance - * if {@link #isPath} is {@code true}. - * - * @throws IllegalStateException If {@link #isPath} is {@code false}. - */ - public UploadWriteFailed getPathValue() { - if (this._tag != Tag.PATH) { - throw new IllegalStateException("Invalid tag: required Tag.PATH, but was Tag." + this._tag.name()); - } - return pathValue; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#OTHER}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#OTHER}, - * {@code false} otherwise. - */ - public boolean isOther() { - return this._tag == Tag.OTHER; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - _tag, - pathValue - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - else if (obj instanceof UploadError) { - UploadError other = (UploadError) obj; - if (this._tag != other._tag) { - return false; - } - switch (_tag) { - case PATH: - return (this.pathValue == other.pathValue) || (this.pathValue.equals(other.pathValue)); - case OTHER: - return true; - default: - return false; - } - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends UnionSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(UploadError value, JsonGenerator g) throws IOException, JsonGenerationException { - switch (value.tag()) { - case PATH: { - g.writeStartObject(); - writeTag("path", g); - UploadWriteFailed.Serializer.INSTANCE.serialize(value.pathValue, g, true); - g.writeEndObject(); - break; - } - default: { - g.writeString("other"); - } - } - } - - @Override - public UploadError deserialize(JsonParser p) throws IOException, JsonParseException { - UploadError value; - boolean collapsed; - String tag; - if (p.getCurrentToken() == JsonToken.VALUE_STRING) { - collapsed = true; - tag = getStringValue(p); - p.nextToken(); - } - else { - collapsed = false; - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); - } - else if ("path".equals(tag)) { - UploadWriteFailed fieldValue = null; - fieldValue = UploadWriteFailed.Serializer.INSTANCE.deserialize(p, true); - value = UploadError.path(fieldValue); - } - else { - value = UploadError.OTHER; - skipFields(p); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadErrorException.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadErrorException.java deleted file mode 100644 index ae92291a..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadErrorException.java +++ /dev/null @@ -1,33 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated by Stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import autosaveworld.zlibs.com.dropbox.core.DbxApiException; -import autosaveworld.zlibs.com.dropbox.core.LocalizedText; - -/** - * Exception thrown when the server responds with a {@link UploadError} error. - * - *

This exception is raised by {@link DbxUserFilesRequests#upload(String)}. - *

- */ -public class UploadErrorException extends DbxApiException { - // exception for routes: - // 2/files/upload - - private static final long serialVersionUID = 0L; - - /** - * The error reported by {@link DbxUserFilesRequests#upload(String)}. - */ - public final UploadError errorValue; - - public UploadErrorException(String routeName, String requestId, LocalizedText userMessage, UploadError errorValue) { - super(requestId, userMessage, buildMessage(routeName, userMessage, errorValue)); - if (errorValue == null) { - throw new NullPointerException("errorValue"); - } - this.errorValue = errorValue; - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionAppendArg.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionAppendArg.java deleted file mode 100644 index bc449a1d..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionAppendArg.java +++ /dev/null @@ -1,181 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -class UploadSessionAppendArg { - // struct files.UploadSessionAppendArg (files.stone) - - protected final UploadSessionCursor cursor; - protected final boolean close; - - /** - * - * @param cursor Contains the upload session ID and the offset. Must not be - * {@code null}. - * @param close If true, the current session will be closed, at which point - * you won't be able to call {@link - * DbxUserFilesRequests#uploadSessionAppendV2(UploadSessionCursor,boolean)} - * anymore with the current session. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public UploadSessionAppendArg(UploadSessionCursor cursor, boolean close) { - if (cursor == null) { - throw new IllegalArgumentException("Required value for 'cursor' is null"); - } - this.cursor = cursor; - this.close = close; - } - - /** - * None - * - *

The default values for unset fields will be used.

- * - * @param cursor Contains the upload session ID and the offset. Must not be - * {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public UploadSessionAppendArg(UploadSessionCursor cursor) { - this(cursor, false); - } - - /** - * Contains the upload session ID and the offset. - * - * @return value for this field, never {@code null}. - */ - public UploadSessionCursor getCursor() { - return cursor; - } - - /** - * If true, the current session will be closed, at which point you won't be - * able to call {@link - * DbxUserFilesRequests#uploadSessionAppendV2(UploadSessionCursor,boolean)} - * anymore with the current session. - * - * @return value for this field, or {@code null} if not present. Defaults to - * false. - */ - public boolean getClose() { - return close; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - cursor, - close - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - UploadSessionAppendArg other = (UploadSessionAppendArg) obj; - return ((this.cursor == other.cursor) || (this.cursor.equals(other.cursor))) - && (this.close == other.close) - ; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(UploadSessionAppendArg value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("cursor"); - UploadSessionCursor.Serializer.INSTANCE.serialize(value.cursor, g); - g.writeFieldName("close"); - StoneSerializers.boolean_().serialize(value.close, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public UploadSessionAppendArg deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - UploadSessionAppendArg value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - UploadSessionCursor f_cursor = null; - Boolean f_close = false; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("cursor".equals(field)) { - f_cursor = UploadSessionCursor.Serializer.INSTANCE.deserialize(p); - } - else if ("close".equals(field)) { - f_close = StoneSerializers.boolean_().deserialize(p); - } - else { - skipValue(p); - } - } - if (f_cursor == null) { - throw new JsonParseException(p, "Required field \"cursor\" missing."); - } - value = new UploadSessionAppendArg(f_cursor, f_close); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionAppendUploader.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionAppendUploader.java deleted file mode 100644 index 6c61b8d3..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionAppendUploader.java +++ /dev/null @@ -1,37 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated by Stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import autosaveworld.zlibs.com.dropbox.core.DbxUploader; -import autosaveworld.zlibs.com.dropbox.core.DbxWrappedException; -import autosaveworld.zlibs.com.dropbox.core.http.HttpRequestor; - -/** - * The {@link DbxUploader} returned by {@link - * DbxUserFilesRequests#uploadSessionAppend(String,long)}. - * - *

Use this class to upload data to the server and complete the request. - *

- * - *

This class should be properly closed after use to prevent resource leaks - * and allow network connection reuse. Always call {@link #close} when complete - * (see {@link DbxUploader} for examples).

- */ -public class UploadSessionAppendUploader extends DbxUploader { - - /** - * Creates a new instance of this uploader. - * - * @param httpUploader Initiated HTTP upload request - * - * @throws NullPointerException if {@code httpUploader} is {@code null} - */ - public UploadSessionAppendUploader(HttpRequestor.Uploader httpUploader) { - super(httpUploader, autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers.void_(), UploadSessionLookupError.Serializer.INSTANCE); - } - - protected UploadSessionLookupErrorException newException(DbxWrappedException error) { - return new UploadSessionLookupErrorException("2/files/upload_session/append", error.getRequestId(), error.getUserMessage(), (UploadSessionLookupError) error.getErrorValue()); - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionAppendV2Uploader.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionAppendV2Uploader.java deleted file mode 100644 index 640bee2f..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionAppendV2Uploader.java +++ /dev/null @@ -1,37 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated by Stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import autosaveworld.zlibs.com.dropbox.core.DbxUploader; -import autosaveworld.zlibs.com.dropbox.core.DbxWrappedException; -import autosaveworld.zlibs.com.dropbox.core.http.HttpRequestor; - -/** - * The {@link DbxUploader} returned by {@link - * DbxUserFilesRequests#uploadSessionAppendV2(UploadSessionCursor,boolean)}. - * - *

Use this class to upload data to the server and complete the request. - *

- * - *

This class should be properly closed after use to prevent resource leaks - * and allow network connection reuse. Always call {@link #close} when complete - * (see {@link DbxUploader} for examples).

- */ -public class UploadSessionAppendV2Uploader extends DbxUploader { - - /** - * Creates a new instance of this uploader. - * - * @param httpUploader Initiated HTTP upload request - * - * @throws NullPointerException if {@code httpUploader} is {@code null} - */ - public UploadSessionAppendV2Uploader(HttpRequestor.Uploader httpUploader) { - super(httpUploader, autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers.void_(), UploadSessionLookupError.Serializer.INSTANCE); - } - - protected UploadSessionLookupErrorException newException(DbxWrappedException error) { - return new UploadSessionLookupErrorException("2/files/upload_session/append_v2", error.getRequestId(), error.getUserMessage(), (UploadSessionLookupError) error.getErrorValue()); - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionCursor.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionCursor.java deleted file mode 100644 index 196b344b..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionCursor.java +++ /dev/null @@ -1,168 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -public class UploadSessionCursor { - // struct files.UploadSessionCursor (files.stone) - - protected final String sessionId; - protected final long offset; - - /** - * - * @param sessionId The upload session ID (returned by {@link - * DbxUserFilesRequests#uploadSessionStart(boolean)}). Must not be - * {@code null}. - * @param offset The amount of data that has been uploaded so far. We use - * this to make sure upload data isn't lost or duplicated in the event - * of a network error. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public UploadSessionCursor(String sessionId, long offset) { - if (sessionId == null) { - throw new IllegalArgumentException("Required value for 'sessionId' is null"); - } - this.sessionId = sessionId; - this.offset = offset; - } - - /** - * The upload session ID (returned by {@link - * DbxUserFilesRequests#uploadSessionStart(boolean)}). - * - * @return value for this field, never {@code null}. - */ - public String getSessionId() { - return sessionId; - } - - /** - * The amount of data that has been uploaded so far. We use this to make - * sure upload data isn't lost or duplicated in the event of a network - * error. - * - * @return value for this field. - */ - public long getOffset() { - return offset; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - sessionId, - offset - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - UploadSessionCursor other = (UploadSessionCursor) obj; - return ((this.sessionId == other.sessionId) || (this.sessionId.equals(other.sessionId))) - && (this.offset == other.offset) - ; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(UploadSessionCursor value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("session_id"); - StoneSerializers.string().serialize(value.sessionId, g); - g.writeFieldName("offset"); - StoneSerializers.uInt64().serialize(value.offset, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public UploadSessionCursor deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - UploadSessionCursor value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - String f_sessionId = null; - Long f_offset = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("session_id".equals(field)) { - f_sessionId = StoneSerializers.string().deserialize(p); - } - else if ("offset".equals(field)) { - f_offset = StoneSerializers.uInt64().deserialize(p); - } - else { - skipValue(p); - } - } - if (f_sessionId == null) { - throw new JsonParseException(p, "Required field \"session_id\" missing."); - } - if (f_offset == null) { - throw new JsonParseException(p, "Required field \"offset\" missing."); - } - value = new UploadSessionCursor(f_sessionId, f_offset); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishArg.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishArg.java deleted file mode 100644 index 51bec1e1..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishArg.java +++ /dev/null @@ -1,165 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -public class UploadSessionFinishArg { - // struct files.UploadSessionFinishArg (files.stone) - - protected final UploadSessionCursor cursor; - protected final CommitInfo commit; - - /** - * - * @param cursor Contains the upload session ID and the offset. Must not be - * {@code null}. - * @param commit Contains the path and other optional modifiers for the - * commit. Must not be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public UploadSessionFinishArg(UploadSessionCursor cursor, CommitInfo commit) { - if (cursor == null) { - throw new IllegalArgumentException("Required value for 'cursor' is null"); - } - this.cursor = cursor; - if (commit == null) { - throw new IllegalArgumentException("Required value for 'commit' is null"); - } - this.commit = commit; - } - - /** - * Contains the upload session ID and the offset. - * - * @return value for this field, never {@code null}. - */ - public UploadSessionCursor getCursor() { - return cursor; - } - - /** - * Contains the path and other optional modifiers for the commit. - * - * @return value for this field, never {@code null}. - */ - public CommitInfo getCommit() { - return commit; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - cursor, - commit - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - UploadSessionFinishArg other = (UploadSessionFinishArg) obj; - return ((this.cursor == other.cursor) || (this.cursor.equals(other.cursor))) - && ((this.commit == other.commit) || (this.commit.equals(other.commit))) - ; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(UploadSessionFinishArg value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("cursor"); - UploadSessionCursor.Serializer.INSTANCE.serialize(value.cursor, g); - g.writeFieldName("commit"); - CommitInfo.Serializer.INSTANCE.serialize(value.commit, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public UploadSessionFinishArg deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - UploadSessionFinishArg value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - UploadSessionCursor f_cursor = null; - CommitInfo f_commit = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("cursor".equals(field)) { - f_cursor = UploadSessionCursor.Serializer.INSTANCE.deserialize(p); - } - else if ("commit".equals(field)) { - f_commit = CommitInfo.Serializer.INSTANCE.deserialize(p); - } - else { - skipValue(p); - } - } - if (f_cursor == null) { - throw new JsonParseException(p, "Required field \"cursor\" missing."); - } - if (f_commit == null) { - throw new JsonParseException(p, "Required field \"commit\" missing."); - } - value = new UploadSessionFinishArg(f_cursor, f_commit); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishBatchArg.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishBatchArg.java deleted file mode 100644 index 4ac49518..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishBatchArg.java +++ /dev/null @@ -1,148 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -class UploadSessionFinishBatchArg { - // struct files.UploadSessionFinishBatchArg (files.stone) - - protected final List entries; - - /** - * - * @param entries Commit information for each file in the batch. Must - * contain at most 1000 items, not contain a {@code null} item, and not - * be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public UploadSessionFinishBatchArg(List entries) { - if (entries == null) { - throw new IllegalArgumentException("Required value for 'entries' is null"); - } - if (entries.size() > 1000) { - throw new IllegalArgumentException("List 'entries' has more than 1000 items"); - } - for (UploadSessionFinishArg x : entries) { - if (x == null) { - throw new IllegalArgumentException("An item in list 'entries' is null"); - } - } - this.entries = entries; - } - - /** - * Commit information for each file in the batch. - * - * @return value for this field, never {@code null}. - */ - public List getEntries() { - return entries; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - entries - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - UploadSessionFinishBatchArg other = (UploadSessionFinishBatchArg) obj; - return (this.entries == other.entries) || (this.entries.equals(other.entries)); - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(UploadSessionFinishBatchArg value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("entries"); - StoneSerializers.list(UploadSessionFinishArg.Serializer.INSTANCE).serialize(value.entries, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public UploadSessionFinishBatchArg deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - UploadSessionFinishBatchArg value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - List f_entries = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("entries".equals(field)) { - f_entries = StoneSerializers.list(UploadSessionFinishArg.Serializer.INSTANCE).deserialize(p); - } - else { - skipValue(p); - } - } - if (f_entries == null) { - throw new JsonParseException(p, "Required field \"entries\" missing."); - } - value = new UploadSessionFinishBatchArg(f_entries); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishBatchJobStatus.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishBatchJobStatus.java deleted file mode 100644 index d497d1f1..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishBatchJobStatus.java +++ /dev/null @@ -1,253 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.UnionSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * This class is a tagged union. Tagged unions instances are always associated - * to a specific tag. This means only one of the {@code isAbc()} methods will - * return {@code true}. You can use {@link #tag()} to determine the tag - * associated with this instance. - */ -public final class UploadSessionFinishBatchJobStatus { - // union files.UploadSessionFinishBatchJobStatus (files.stone) - - /** - * Discriminating tag type for {@link UploadSessionFinishBatchJobStatus}. - */ - public enum Tag { - /** - * The asynchronous job is still in progress. - */ - IN_PROGRESS, - /** - * The {@link - * DbxUserFilesRequests#uploadSessionFinishBatch(java.util.List)} has - * finished. - */ - COMPLETE; // UploadSessionFinishBatchResult - } - - /** - * The asynchronous job is still in progress. - */ - public static final UploadSessionFinishBatchJobStatus IN_PROGRESS = new UploadSessionFinishBatchJobStatus(Tag.IN_PROGRESS, null); - - private final Tag _tag; - private final UploadSessionFinishBatchResult completeValue; - - /** - * - * @param completeValue The {@link - * DbxUserFilesRequests#uploadSessionFinishBatch(java.util.List)} has - * finished. Must not be {@code null}. - * @param _tag Discriminating tag for this instance. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - private UploadSessionFinishBatchJobStatus(Tag _tag, UploadSessionFinishBatchResult completeValue) { - this._tag = _tag; - this.completeValue = completeValue; - } - - /** - * Returns the tag for this instance. - * - *

This class is a tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isXyz()} - * methods will return {@code true}. Callers are recommended to use the tag - * value in a {@code switch} statement to properly handle the different - * values for this {@code UploadSessionFinishBatchJobStatus}.

- * - * @return the tag for this instance. - */ - public Tag tag() { - return _tag; - } - - /** - * Returns {@code true} if this instance has the tag {@link - * Tag#IN_PROGRESS}, {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link - * Tag#IN_PROGRESS}, {@code false} otherwise. - */ - public boolean isInProgress() { - return this._tag == Tag.IN_PROGRESS; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#COMPLETE}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#COMPLETE}, - * {@code false} otherwise. - */ - public boolean isComplete() { - return this._tag == Tag.COMPLETE; - } - - /** - * Returns an instance of {@code UploadSessionFinishBatchJobStatus} that has - * its tag set to {@link Tag#COMPLETE}. - * - *

The {@link - * DbxUserFilesRequests#uploadSessionFinishBatch(java.util.List)} has - * finished.

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code UploadSessionFinishBatchJobStatus} with its - * tag set to {@link Tag#COMPLETE}. - * - * @throws IllegalArgumentException if {@code value} is {@code null}. - */ - public static UploadSessionFinishBatchJobStatus complete(UploadSessionFinishBatchResult value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - return new UploadSessionFinishBatchJobStatus(Tag.COMPLETE, value); - } - - /** - * The {@link DbxUserFilesRequests#uploadSessionFinishBatch(java.util.List)} - * has finished. - * - *

This instance must be tagged as {@link Tag#COMPLETE}.

- * - * @return The {@link UploadSessionFinishBatchResult} value associated with - * this instance if {@link #isComplete} is {@code true}. - * - * @throws IllegalStateException If {@link #isComplete} is {@code false}. - */ - public UploadSessionFinishBatchResult getCompleteValue() { - if (this._tag != Tag.COMPLETE) { - throw new IllegalStateException("Invalid tag: required Tag.COMPLETE, but was Tag." + this._tag.name()); - } - return completeValue; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - _tag, - completeValue - }); - hash = (31 * super.hashCode()) + hash; - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - else if (obj instanceof UploadSessionFinishBatchJobStatus) { - UploadSessionFinishBatchJobStatus other = (UploadSessionFinishBatchJobStatus) obj; - if (this._tag != other._tag) { - return false; - } - switch (_tag) { - case IN_PROGRESS: - return true; - case COMPLETE: - return (this.completeValue == other.completeValue) || (this.completeValue.equals(other.completeValue)); - default: - return false; - } - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends UnionSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(UploadSessionFinishBatchJobStatus value, JsonGenerator g) throws IOException, JsonGenerationException { - switch (value.tag()) { - case IN_PROGRESS: { - g.writeString("in_progress"); - break; - } - case COMPLETE: { - g.writeStartObject(); - writeTag("complete", g); - UploadSessionFinishBatchResult.Serializer.INSTANCE.serialize(value.completeValue, g, true); - g.writeEndObject(); - break; - } - default: { - throw new IllegalArgumentException("Unrecognized tag: " + value.tag()); - } - } - } - - @Override - public UploadSessionFinishBatchJobStatus deserialize(JsonParser p) throws IOException, JsonParseException { - UploadSessionFinishBatchJobStatus value; - boolean collapsed; - String tag; - if (p.getCurrentToken() == JsonToken.VALUE_STRING) { - collapsed = true; - tag = getStringValue(p); - p.nextToken(); - } - else { - collapsed = false; - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); - } - else if ("in_progress".equals(tag)) { - value = UploadSessionFinishBatchJobStatus.IN_PROGRESS; - } - else if ("complete".equals(tag)) { - UploadSessionFinishBatchResult fieldValue = null; - fieldValue = UploadSessionFinishBatchResult.Serializer.INSTANCE.deserialize(p, true); - value = UploadSessionFinishBatchJobStatus.complete(fieldValue); - } - else { - throw new JsonParseException(p, "Unknown tag: " + tag); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishBatchResult.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishBatchResult.java deleted file mode 100644 index 86a79604..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishBatchResult.java +++ /dev/null @@ -1,144 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -public class UploadSessionFinishBatchResult { - // struct files.UploadSessionFinishBatchResult (files.stone) - - protected final List entries; - - /** - * - * @param entries Commit result for each file in the batch. Must not - * contain a {@code null} item and not be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public UploadSessionFinishBatchResult(List entries) { - if (entries == null) { - throw new IllegalArgumentException("Required value for 'entries' is null"); - } - for (UploadSessionFinishBatchResultEntry x : entries) { - if (x == null) { - throw new IllegalArgumentException("An item in list 'entries' is null"); - } - } - this.entries = entries; - } - - /** - * Commit result for each file in the batch. - * - * @return value for this field, never {@code null}. - */ - public List getEntries() { - return entries; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - entries - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - UploadSessionFinishBatchResult other = (UploadSessionFinishBatchResult) obj; - return (this.entries == other.entries) || (this.entries.equals(other.entries)); - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(UploadSessionFinishBatchResult value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("entries"); - StoneSerializers.list(UploadSessionFinishBatchResultEntry.Serializer.INSTANCE).serialize(value.entries, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public UploadSessionFinishBatchResult deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - UploadSessionFinishBatchResult value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - List f_entries = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("entries".equals(field)) { - f_entries = StoneSerializers.list(UploadSessionFinishBatchResultEntry.Serializer.INSTANCE).deserialize(p); - } - else { - skipValue(p); - } - } - if (f_entries == null) { - throw new JsonParseException(p, "Required field \"entries\" missing."); - } - value = new UploadSessionFinishBatchResult(f_entries); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishBatchResultEntry.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishBatchResultEntry.java deleted file mode 100644 index 74258a1b..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishBatchResultEntry.java +++ /dev/null @@ -1,278 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.UnionSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * This class is a tagged union. Tagged unions instances are always associated - * to a specific tag. This means only one of the {@code isAbc()} methods will - * return {@code true}. You can use {@link #tag()} to determine the tag - * associated with this instance. - */ -public final class UploadSessionFinishBatchResultEntry { - // union files.UploadSessionFinishBatchResultEntry (files.stone) - - /** - * Discriminating tag type for {@link UploadSessionFinishBatchResultEntry}. - */ - public enum Tag { - SUCCESS, // FileMetadata - FAILURE; // UploadSessionFinishError - } - - private final Tag _tag; - private final FileMetadata successValue; - private final UploadSessionFinishError failureValue; - - /** - * - * @param successValue Must not be {@code null}. - * @param failureValue Must not be {@code null}. - * @param _tag Discriminating tag for this instance. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - private UploadSessionFinishBatchResultEntry(Tag _tag, FileMetadata successValue, UploadSessionFinishError failureValue) { - this._tag = _tag; - this.successValue = successValue; - this.failureValue = failureValue; - } - - /** - * Returns the tag for this instance. - * - *

This class is a tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isXyz()} - * methods will return {@code true}. Callers are recommended to use the tag - * value in a {@code switch} statement to properly handle the different - * values for this {@code UploadSessionFinishBatchResultEntry}.

- * - * @return the tag for this instance. - */ - public Tag tag() { - return _tag; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#SUCCESS}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#SUCCESS}, - * {@code false} otherwise. - */ - public boolean isSuccess() { - return this._tag == Tag.SUCCESS; - } - - /** - * Returns an instance of {@code UploadSessionFinishBatchResultEntry} that - * has its tag set to {@link Tag#SUCCESS}. - * - *

None

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code UploadSessionFinishBatchResultEntry} with its - * tag set to {@link Tag#SUCCESS}. - * - * @throws IllegalArgumentException if {@code value} is {@code null}. - */ - public static UploadSessionFinishBatchResultEntry success(FileMetadata value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - return new UploadSessionFinishBatchResultEntry(Tag.SUCCESS, value, null); - } - - /** - * This instance must be tagged as {@link Tag#SUCCESS}. - * - * @return The {@link FileMetadata} value associated with this instance if - * {@link #isSuccess} is {@code true}. - * - * @throws IllegalStateException If {@link #isSuccess} is {@code false}. - */ - public FileMetadata getSuccessValue() { - if (this._tag != Tag.SUCCESS) { - throw new IllegalStateException("Invalid tag: required Tag.SUCCESS, but was Tag." + this._tag.name()); - } - return successValue; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#FAILURE}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#FAILURE}, - * {@code false} otherwise. - */ - public boolean isFailure() { - return this._tag == Tag.FAILURE; - } - - /** - * Returns an instance of {@code UploadSessionFinishBatchResultEntry} that - * has its tag set to {@link Tag#FAILURE}. - * - *

None

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code UploadSessionFinishBatchResultEntry} with its - * tag set to {@link Tag#FAILURE}. - * - * @throws IllegalArgumentException if {@code value} is {@code null}. - */ - public static UploadSessionFinishBatchResultEntry failure(UploadSessionFinishError value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - return new UploadSessionFinishBatchResultEntry(Tag.FAILURE, null, value); - } - - /** - * This instance must be tagged as {@link Tag#FAILURE}. - * - * @return The {@link UploadSessionFinishError} value associated with this - * instance if {@link #isFailure} is {@code true}. - * - * @throws IllegalStateException If {@link #isFailure} is {@code false}. - */ - public UploadSessionFinishError getFailureValue() { - if (this._tag != Tag.FAILURE) { - throw new IllegalStateException("Invalid tag: required Tag.FAILURE, but was Tag." + this._tag.name()); - } - return failureValue; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - _tag, - successValue, - failureValue - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - else if (obj instanceof UploadSessionFinishBatchResultEntry) { - UploadSessionFinishBatchResultEntry other = (UploadSessionFinishBatchResultEntry) obj; - if (this._tag != other._tag) { - return false; - } - switch (_tag) { - case SUCCESS: - return (this.successValue == other.successValue) || (this.successValue.equals(other.successValue)); - case FAILURE: - return (this.failureValue == other.failureValue) || (this.failureValue.equals(other.failureValue)); - default: - return false; - } - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends UnionSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(UploadSessionFinishBatchResultEntry value, JsonGenerator g) throws IOException, JsonGenerationException { - switch (value.tag()) { - case SUCCESS: { - g.writeStartObject(); - writeTag("success", g); - FileMetadata.Serializer.INSTANCE.serialize(value.successValue, g, true); - g.writeEndObject(); - break; - } - case FAILURE: { - g.writeStartObject(); - writeTag("failure", g); - g.writeFieldName("failure"); - UploadSessionFinishError.Serializer.INSTANCE.serialize(value.failureValue, g); - g.writeEndObject(); - break; - } - default: { - throw new IllegalArgumentException("Unrecognized tag: " + value.tag()); - } - } - } - - @Override - public UploadSessionFinishBatchResultEntry deserialize(JsonParser p) throws IOException, JsonParseException { - UploadSessionFinishBatchResultEntry value; - boolean collapsed; - String tag; - if (p.getCurrentToken() == JsonToken.VALUE_STRING) { - collapsed = true; - tag = getStringValue(p); - p.nextToken(); - } - else { - collapsed = false; - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); - } - else if ("success".equals(tag)) { - FileMetadata fieldValue = null; - fieldValue = FileMetadata.Serializer.INSTANCE.deserialize(p, true); - value = UploadSessionFinishBatchResultEntry.success(fieldValue); - } - else if ("failure".equals(tag)) { - UploadSessionFinishError fieldValue = null; - expectField("failure", p); - fieldValue = UploadSessionFinishError.Serializer.INSTANCE.deserialize(p); - value = UploadSessionFinishBatchResultEntry.failure(fieldValue); - } - else { - throw new JsonParseException(p, "Unknown tag: " + tag); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishError.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishError.java deleted file mode 100644 index 9b7ff413..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishError.java +++ /dev/null @@ -1,365 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.UnionSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * This class is an open tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isAbc()} - * methods will return {@code true}. You can use {@link #tag()} to determine the - * tag associated with this instance. - * - *

Open unions may be extended in the future with additional tags. If a new - * tag is introduced that this SDK does not recognized, the {@link #OTHER} value - * will be used.

- */ -public final class UploadSessionFinishError { - // union files.UploadSessionFinishError (files.stone) - - /** - * Discriminating tag type for {@link UploadSessionFinishError}. - */ - public enum Tag { - /** - * The session arguments are incorrect; the value explains the reason. - */ - LOOKUP_FAILED, // UploadSessionLookupError - /** - * Unable to save the uploaded contents to a file. - */ - PATH, // WriteError - /** - * The batch request commits files into too many different shared - * folders. Please limit your batch request to files contained in a - * single shared folder. - */ - TOO_MANY_SHARED_FOLDER_TARGETS, - /** - * Catch-all used for unknown tag values returned by the Dropbox - * servers. - * - *

Receiving a catch-all value typically indicates this SDK version - * is not up to date. Consider updating your SDK version to handle the - * new tags.

- */ - OTHER; // *catch_all - } - - /** - * The batch request commits files into too many different shared folders. - * Please limit your batch request to files contained in a single shared - * folder. - */ - public static final UploadSessionFinishError TOO_MANY_SHARED_FOLDER_TARGETS = new UploadSessionFinishError(Tag.TOO_MANY_SHARED_FOLDER_TARGETS, null, null); - /** - * Catch-all used for unknown tag values returned by the Dropbox servers. - * - *

Receiving a catch-all value typically indicates this SDK version is - * not up to date. Consider updating your SDK version to handle the new - * tags.

- */ - public static final UploadSessionFinishError OTHER = new UploadSessionFinishError(Tag.OTHER, null, null); - - private final Tag _tag; - private final UploadSessionLookupError lookupFailedValue; - private final WriteError pathValue; - - /** - * - * @param lookupFailedValue The session arguments are incorrect; the value - * explains the reason. Must not be {@code null}. - * @param pathValue Unable to save the uploaded contents to a file. Must - * not be {@code null}. - * @param _tag Discriminating tag for this instance. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - private UploadSessionFinishError(Tag _tag, UploadSessionLookupError lookupFailedValue, WriteError pathValue) { - this._tag = _tag; - this.lookupFailedValue = lookupFailedValue; - this.pathValue = pathValue; - } - - /** - * Returns the tag for this instance. - * - *

This class is a tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isXyz()} - * methods will return {@code true}. Callers are recommended to use the tag - * value in a {@code switch} statement to properly handle the different - * values for this {@code UploadSessionFinishError}.

- * - *

If a tag returned by the server is unrecognized by this SDK, the - * {@link Tag#OTHER} value will be used.

- * - * @return the tag for this instance. - */ - public Tag tag() { - return _tag; - } - - /** - * Returns {@code true} if this instance has the tag {@link - * Tag#LOOKUP_FAILED}, {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link - * Tag#LOOKUP_FAILED}, {@code false} otherwise. - */ - public boolean isLookupFailed() { - return this._tag == Tag.LOOKUP_FAILED; - } - - /** - * Returns an instance of {@code UploadSessionFinishError} that has its tag - * set to {@link Tag#LOOKUP_FAILED}. - * - *

The session arguments are incorrect; the value explains the reason. - *

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code UploadSessionFinishError} with its tag set to - * {@link Tag#LOOKUP_FAILED}. - * - * @throws IllegalArgumentException if {@code value} is {@code null}. - */ - public static UploadSessionFinishError lookupFailed(UploadSessionLookupError value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - return new UploadSessionFinishError(Tag.LOOKUP_FAILED, value, null); - } - - /** - * The session arguments are incorrect; the value explains the reason. - * - *

This instance must be tagged as {@link Tag#LOOKUP_FAILED}.

- * - * @return The {@link UploadSessionLookupError} value associated with this - * instance if {@link #isLookupFailed} is {@code true}. - * - * @throws IllegalStateException If {@link #isLookupFailed} is {@code - * false}. - */ - public UploadSessionLookupError getLookupFailedValue() { - if (this._tag != Tag.LOOKUP_FAILED) { - throw new IllegalStateException("Invalid tag: required Tag.LOOKUP_FAILED, but was Tag." + this._tag.name()); - } - return lookupFailedValue; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#PATH}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#PATH}, - * {@code false} otherwise. - */ - public boolean isPath() { - return this._tag == Tag.PATH; - } - - /** - * Returns an instance of {@code UploadSessionFinishError} that has its tag - * set to {@link Tag#PATH}. - * - *

Unable to save the uploaded contents to a file.

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code UploadSessionFinishError} with its tag set to - * {@link Tag#PATH}. - * - * @throws IllegalArgumentException if {@code value} is {@code null}. - */ - public static UploadSessionFinishError path(WriteError value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - return new UploadSessionFinishError(Tag.PATH, null, value); - } - - /** - * Unable to save the uploaded contents to a file. - * - *

This instance must be tagged as {@link Tag#PATH}.

- * - * @return The {@link WriteError} value associated with this instance if - * {@link #isPath} is {@code true}. - * - * @throws IllegalStateException If {@link #isPath} is {@code false}. - */ - public WriteError getPathValue() { - if (this._tag != Tag.PATH) { - throw new IllegalStateException("Invalid tag: required Tag.PATH, but was Tag." + this._tag.name()); - } - return pathValue; - } - - /** - * Returns {@code true} if this instance has the tag {@link - * Tag#TOO_MANY_SHARED_FOLDER_TARGETS}, {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link - * Tag#TOO_MANY_SHARED_FOLDER_TARGETS}, {@code false} otherwise. - */ - public boolean isTooManySharedFolderTargets() { - return this._tag == Tag.TOO_MANY_SHARED_FOLDER_TARGETS; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#OTHER}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#OTHER}, - * {@code false} otherwise. - */ - public boolean isOther() { - return this._tag == Tag.OTHER; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - _tag, - lookupFailedValue, - pathValue - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - else if (obj instanceof UploadSessionFinishError) { - UploadSessionFinishError other = (UploadSessionFinishError) obj; - if (this._tag != other._tag) { - return false; - } - switch (_tag) { - case LOOKUP_FAILED: - return (this.lookupFailedValue == other.lookupFailedValue) || (this.lookupFailedValue.equals(other.lookupFailedValue)); - case PATH: - return (this.pathValue == other.pathValue) || (this.pathValue.equals(other.pathValue)); - case TOO_MANY_SHARED_FOLDER_TARGETS: - return true; - case OTHER: - return true; - default: - return false; - } - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends UnionSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(UploadSessionFinishError value, JsonGenerator g) throws IOException, JsonGenerationException { - switch (value.tag()) { - case LOOKUP_FAILED: { - g.writeStartObject(); - writeTag("lookup_failed", g); - g.writeFieldName("lookup_failed"); - UploadSessionLookupError.Serializer.INSTANCE.serialize(value.lookupFailedValue, g); - g.writeEndObject(); - break; - } - case PATH: { - g.writeStartObject(); - writeTag("path", g); - g.writeFieldName("path"); - WriteError.Serializer.INSTANCE.serialize(value.pathValue, g); - g.writeEndObject(); - break; - } - case TOO_MANY_SHARED_FOLDER_TARGETS: { - g.writeString("too_many_shared_folder_targets"); - break; - } - default: { - g.writeString("other"); - } - } - } - - @Override - public UploadSessionFinishError deserialize(JsonParser p) throws IOException, JsonParseException { - UploadSessionFinishError value; - boolean collapsed; - String tag; - if (p.getCurrentToken() == JsonToken.VALUE_STRING) { - collapsed = true; - tag = getStringValue(p); - p.nextToken(); - } - else { - collapsed = false; - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); - } - else if ("lookup_failed".equals(tag)) { - UploadSessionLookupError fieldValue = null; - expectField("lookup_failed", p); - fieldValue = UploadSessionLookupError.Serializer.INSTANCE.deserialize(p); - value = UploadSessionFinishError.lookupFailed(fieldValue); - } - else if ("path".equals(tag)) { - WriteError fieldValue = null; - expectField("path", p); - fieldValue = WriteError.Serializer.INSTANCE.deserialize(p); - value = UploadSessionFinishError.path(fieldValue); - } - else if ("too_many_shared_folder_targets".equals(tag)) { - value = UploadSessionFinishError.TOO_MANY_SHARED_FOLDER_TARGETS; - } - else { - value = UploadSessionFinishError.OTHER; - skipFields(p); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishErrorException.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishErrorException.java deleted file mode 100644 index 75a3f9ef..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishErrorException.java +++ /dev/null @@ -1,36 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated by Stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import autosaveworld.zlibs.com.dropbox.core.DbxApiException; -import autosaveworld.zlibs.com.dropbox.core.LocalizedText; - -/** - * Exception thrown when the server responds with a {@link - * UploadSessionFinishError} error. - * - *

This exception is raised by {@link - * DbxUserFilesRequests#uploadSessionFinish(UploadSessionCursor,CommitInfo)}. - *

- */ -public class UploadSessionFinishErrorException extends DbxApiException { - // exception for routes: - // 2/files/upload_session/finish - - private static final long serialVersionUID = 0L; - - /** - * The error reported by {@link - * DbxUserFilesRequests#uploadSessionFinish(UploadSessionCursor,CommitInfo)}. - */ - public final UploadSessionFinishError errorValue; - - public UploadSessionFinishErrorException(String routeName, String requestId, LocalizedText userMessage, UploadSessionFinishError errorValue) { - super(requestId, userMessage, buildMessage(routeName, userMessage, errorValue)); - if (errorValue == null) { - throw new NullPointerException("errorValue"); - } - this.errorValue = errorValue; - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishUploader.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishUploader.java deleted file mode 100644 index db18670f..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionFinishUploader.java +++ /dev/null @@ -1,37 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated by Stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import autosaveworld.zlibs.com.dropbox.core.DbxUploader; -import autosaveworld.zlibs.com.dropbox.core.DbxWrappedException; -import autosaveworld.zlibs.com.dropbox.core.http.HttpRequestor; - -/** - * The {@link DbxUploader} returned by {@link - * DbxUserFilesRequests#uploadSessionFinish(UploadSessionCursor,CommitInfo)}. - * - *

Use this class to upload data to the server and complete the request. - *

- * - *

This class should be properly closed after use to prevent resource leaks - * and allow network connection reuse. Always call {@link #close} when complete - * (see {@link DbxUploader} for examples).

- */ -public class UploadSessionFinishUploader extends DbxUploader { - - /** - * Creates a new instance of this uploader. - * - * @param httpUploader Initiated HTTP upload request - * - * @throws NullPointerException if {@code httpUploader} is {@code null} - */ - public UploadSessionFinishUploader(HttpRequestor.Uploader httpUploader) { - super(httpUploader, FileMetadata.Serializer.INSTANCE, UploadSessionFinishError.Serializer.INSTANCE); - } - - protected UploadSessionFinishErrorException newException(DbxWrappedException error) { - return new UploadSessionFinishErrorException("2/files/upload_session/finish", error.getRequestId(), error.getUserMessage(), (UploadSessionFinishError) error.getErrorValue()); - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionLookupError.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionLookupError.java deleted file mode 100644 index 683cec43..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionLookupError.java +++ /dev/null @@ -1,356 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.UnionSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * This class is an open tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isAbc()} - * methods will return {@code true}. You can use {@link #tag()} to determine the - * tag associated with this instance. - * - *

Open unions may be extended in the future with additional tags. If a new - * tag is introduced that this SDK does not recognized, the {@link #OTHER} value - * will be used.

- */ -public final class UploadSessionLookupError { - // union files.UploadSessionLookupError (files.stone) - - /** - * Discriminating tag type for {@link UploadSessionLookupError}. - */ - public enum Tag { - /** - * The upload session id was not found. - */ - NOT_FOUND, - /** - * The specified offset was incorrect. See the value for the correct - * offset. This error may occur when a previous request was received and - * processed successfully but the client did not receive the response, - * e.g. due to a network error. - */ - INCORRECT_OFFSET, // UploadSessionOffsetError - /** - * You are attempting to append data to an upload session that has - * alread been closed (i.e. committed). - */ - CLOSED, - /** - * The session must be closed before calling - * upload_session/finish_batch. - */ - NOT_CLOSED, - /** - * Catch-all used for unknown tag values returned by the Dropbox - * servers. - * - *

Receiving a catch-all value typically indicates this SDK version - * is not up to date. Consider updating your SDK version to handle the - * new tags.

- */ - OTHER; // *catch_all - } - - /** - * The upload session id was not found. - */ - public static final UploadSessionLookupError NOT_FOUND = new UploadSessionLookupError(Tag.NOT_FOUND, null); - /** - * You are attempting to append data to an upload session that has alread - * been closed (i.e. committed). - */ - public static final UploadSessionLookupError CLOSED = new UploadSessionLookupError(Tag.CLOSED, null); - /** - * The session must be closed before calling upload_session/finish_batch. - */ - public static final UploadSessionLookupError NOT_CLOSED = new UploadSessionLookupError(Tag.NOT_CLOSED, null); - /** - * Catch-all used for unknown tag values returned by the Dropbox servers. - * - *

Receiving a catch-all value typically indicates this SDK version is - * not up to date. Consider updating your SDK version to handle the new - * tags.

- */ - public static final UploadSessionLookupError OTHER = new UploadSessionLookupError(Tag.OTHER, null); - - private final Tag _tag; - private final UploadSessionOffsetError incorrectOffsetValue; - - /** - * - * @param incorrectOffsetValue The specified offset was incorrect. See the - * value for the correct offset. This error may occur when a previous - * request was received and processed successfully but the client did - * not receive the response, e.g. due to a network error. Must not be - * {@code null}. - * @param _tag Discriminating tag for this instance. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - private UploadSessionLookupError(Tag _tag, UploadSessionOffsetError incorrectOffsetValue) { - this._tag = _tag; - this.incorrectOffsetValue = incorrectOffsetValue; - } - - /** - * Returns the tag for this instance. - * - *

This class is a tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isXyz()} - * methods will return {@code true}. Callers are recommended to use the tag - * value in a {@code switch} statement to properly handle the different - * values for this {@code UploadSessionLookupError}.

- * - *

If a tag returned by the server is unrecognized by this SDK, the - * {@link Tag#OTHER} value will be used.

- * - * @return the tag for this instance. - */ - public Tag tag() { - return _tag; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#NOT_FOUND}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#NOT_FOUND}, - * {@code false} otherwise. - */ - public boolean isNotFound() { - return this._tag == Tag.NOT_FOUND; - } - - /** - * Returns {@code true} if this instance has the tag {@link - * Tag#INCORRECT_OFFSET}, {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link - * Tag#INCORRECT_OFFSET}, {@code false} otherwise. - */ - public boolean isIncorrectOffset() { - return this._tag == Tag.INCORRECT_OFFSET; - } - - /** - * Returns an instance of {@code UploadSessionLookupError} that has its tag - * set to {@link Tag#INCORRECT_OFFSET}. - * - *

The specified offset was incorrect. See the value for the correct - * offset. This error may occur when a previous request was received and - * processed successfully but the client did not receive the response, e.g. - * due to a network error.

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code UploadSessionLookupError} with its tag set to - * {@link Tag#INCORRECT_OFFSET}. - * - * @throws IllegalArgumentException if {@code value} is {@code null}. - */ - public static UploadSessionLookupError incorrectOffset(UploadSessionOffsetError value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - return new UploadSessionLookupError(Tag.INCORRECT_OFFSET, value); - } - - /** - * The specified offset was incorrect. See the value for the correct offset. - * This error may occur when a previous request was received and processed - * successfully but the client did not receive the response, e.g. due to a - * network error. - * - *

This instance must be tagged as {@link Tag#INCORRECT_OFFSET}.

- * - * @return The {@link UploadSessionOffsetError} value associated with this - * instance if {@link #isIncorrectOffset} is {@code true}. - * - * @throws IllegalStateException If {@link #isIncorrectOffset} is {@code - * false}. - */ - public UploadSessionOffsetError getIncorrectOffsetValue() { - if (this._tag != Tag.INCORRECT_OFFSET) { - throw new IllegalStateException("Invalid tag: required Tag.INCORRECT_OFFSET, but was Tag." + this._tag.name()); - } - return incorrectOffsetValue; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#CLOSED}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#CLOSED}, - * {@code false} otherwise. - */ - public boolean isClosed() { - return this._tag == Tag.CLOSED; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#NOT_CLOSED}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link - * Tag#NOT_CLOSED}, {@code false} otherwise. - */ - public boolean isNotClosed() { - return this._tag == Tag.NOT_CLOSED; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#OTHER}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#OTHER}, - * {@code false} otherwise. - */ - public boolean isOther() { - return this._tag == Tag.OTHER; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - _tag, - incorrectOffsetValue - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - else if (obj instanceof UploadSessionLookupError) { - UploadSessionLookupError other = (UploadSessionLookupError) obj; - if (this._tag != other._tag) { - return false; - } - switch (_tag) { - case NOT_FOUND: - return true; - case INCORRECT_OFFSET: - return (this.incorrectOffsetValue == other.incorrectOffsetValue) || (this.incorrectOffsetValue.equals(other.incorrectOffsetValue)); - case CLOSED: - return true; - case NOT_CLOSED: - return true; - case OTHER: - return true; - default: - return false; - } - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends UnionSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(UploadSessionLookupError value, JsonGenerator g) throws IOException, JsonGenerationException { - switch (value.tag()) { - case NOT_FOUND: { - g.writeString("not_found"); - break; - } - case INCORRECT_OFFSET: { - g.writeStartObject(); - writeTag("incorrect_offset", g); - UploadSessionOffsetError.Serializer.INSTANCE.serialize(value.incorrectOffsetValue, g, true); - g.writeEndObject(); - break; - } - case CLOSED: { - g.writeString("closed"); - break; - } - case NOT_CLOSED: { - g.writeString("not_closed"); - break; - } - default: { - g.writeString("other"); - } - } - } - - @Override - public UploadSessionLookupError deserialize(JsonParser p) throws IOException, JsonParseException { - UploadSessionLookupError value; - boolean collapsed; - String tag; - if (p.getCurrentToken() == JsonToken.VALUE_STRING) { - collapsed = true; - tag = getStringValue(p); - p.nextToken(); - } - else { - collapsed = false; - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); - } - else if ("not_found".equals(tag)) { - value = UploadSessionLookupError.NOT_FOUND; - } - else if ("incorrect_offset".equals(tag)) { - UploadSessionOffsetError fieldValue = null; - fieldValue = UploadSessionOffsetError.Serializer.INSTANCE.deserialize(p, true); - value = UploadSessionLookupError.incorrectOffset(fieldValue); - } - else if ("closed".equals(tag)) { - value = UploadSessionLookupError.CLOSED; - } - else if ("not_closed".equals(tag)) { - value = UploadSessionLookupError.NOT_CLOSED; - } - else { - value = UploadSessionLookupError.OTHER; - skipFields(p); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionLookupErrorException.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionLookupErrorException.java deleted file mode 100644 index b79dfd8d..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionLookupErrorException.java +++ /dev/null @@ -1,39 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated by Stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import autosaveworld.zlibs.com.dropbox.core.DbxApiException; -import autosaveworld.zlibs.com.dropbox.core.LocalizedText; - -/** - * Exception thrown when the server responds with a {@link - * UploadSessionLookupError} error. - * - *

This exception is raised by {@link - * DbxUserFilesRequests#uploadSessionAppend(String,long)} and {@link - * DbxUserFilesRequests#uploadSessionAppendV2(UploadSessionCursor,boolean)}. - *

- */ -public class UploadSessionLookupErrorException extends DbxApiException { - // exception for routes: - // 2/files/upload_session/append - // 2/files/upload_session/append_v2 - - private static final long serialVersionUID = 0L; - - /** - * The error reported by {@link - * DbxUserFilesRequests#uploadSessionAppend(String,long)} and {@link - * DbxUserFilesRequests#uploadSessionAppendV2(UploadSessionCursor,boolean)}. - */ - public final UploadSessionLookupError errorValue; - - public UploadSessionLookupErrorException(String routeName, String requestId, LocalizedText userMessage, UploadSessionLookupError errorValue) { - super(requestId, userMessage, buildMessage(routeName, userMessage, errorValue)); - if (errorValue == null) { - throw new NullPointerException("errorValue"); - } - this.errorValue = errorValue; - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionOffsetError.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionOffsetError.java deleted file mode 100644 index 86e0a5ff..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionOffsetError.java +++ /dev/null @@ -1,131 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -public class UploadSessionOffsetError { - // struct files.UploadSessionOffsetError (files.stone) - - protected final long correctOffset; - - /** - * - * @param correctOffset The offset up to which data has been collected. - */ - public UploadSessionOffsetError(long correctOffset) { - this.correctOffset = correctOffset; - } - - /** - * The offset up to which data has been collected. - * - * @return value for this field. - */ - public long getCorrectOffset() { - return correctOffset; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - correctOffset - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - UploadSessionOffsetError other = (UploadSessionOffsetError) obj; - return this.correctOffset == other.correctOffset; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(UploadSessionOffsetError value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("correct_offset"); - StoneSerializers.uInt64().serialize(value.correctOffset, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public UploadSessionOffsetError deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - UploadSessionOffsetError value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - Long f_correctOffset = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("correct_offset".equals(field)) { - f_correctOffset = StoneSerializers.uInt64().deserialize(p); - } - else { - skipValue(p); - } - } - if (f_correctOffset == null) { - throw new JsonParseException(p, "Required field \"correct_offset\" missing."); - } - value = new UploadSessionOffsetError(f_correctOffset); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionStartArg.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionStartArg.java deleted file mode 100644 index b020a61e..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionStartArg.java +++ /dev/null @@ -1,144 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -class UploadSessionStartArg { - // struct files.UploadSessionStartArg (files.stone) - - protected final boolean close; - - /** - * - * @param close If true, the current session will be closed, at which point - * you won't be able to call {@link - * DbxUserFilesRequests#uploadSessionAppendV2(UploadSessionCursor,boolean)} - * anymore with the current session. - */ - public UploadSessionStartArg(boolean close) { - this.close = close; - } - - /** - * None - * - *

The default values for unset fields will be used.

- */ - public UploadSessionStartArg() { - this(false); - } - - /** - * If true, the current session will be closed, at which point you won't be - * able to call {@link - * DbxUserFilesRequests#uploadSessionAppendV2(UploadSessionCursor,boolean)} - * anymore with the current session. - * - * @return value for this field, or {@code null} if not present. Defaults to - * false. - */ - public boolean getClose() { - return close; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - close - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - UploadSessionStartArg other = (UploadSessionStartArg) obj; - return this.close == other.close; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(UploadSessionStartArg value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("close"); - StoneSerializers.boolean_().serialize(value.close, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public UploadSessionStartArg deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - UploadSessionStartArg value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - Boolean f_close = false; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("close".equals(field)) { - f_close = StoneSerializers.boolean_().deserialize(p); - } - else { - skipValue(p); - } - } - value = new UploadSessionStartArg(f_close); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionStartResult.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionStartResult.java deleted file mode 100644 index 239c5a4d..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionStartResult.java +++ /dev/null @@ -1,145 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -public class UploadSessionStartResult { - // struct files.UploadSessionStartResult (files.stone) - - protected final String sessionId; - - /** - * - * @param sessionId A unique identifier for the upload session. Pass this - * to {@link - * DbxUserFilesRequests#uploadSessionAppendV2(UploadSessionCursor,boolean)} - * and {@link - * DbxUserFilesRequests#uploadSessionFinish(UploadSessionCursor,CommitInfo)}. - * Must not be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public UploadSessionStartResult(String sessionId) { - if (sessionId == null) { - throw new IllegalArgumentException("Required value for 'sessionId' is null"); - } - this.sessionId = sessionId; - } - - /** - * A unique identifier for the upload session. Pass this to {@link - * DbxUserFilesRequests#uploadSessionAppendV2(UploadSessionCursor,boolean)} - * and {@link - * DbxUserFilesRequests#uploadSessionFinish(UploadSessionCursor,CommitInfo)}. - * - * @return value for this field, never {@code null}. - */ - public String getSessionId() { - return sessionId; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - sessionId - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - UploadSessionStartResult other = (UploadSessionStartResult) obj; - return (this.sessionId == other.sessionId) || (this.sessionId.equals(other.sessionId)); - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(UploadSessionStartResult value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("session_id"); - StoneSerializers.string().serialize(value.sessionId, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public UploadSessionStartResult deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - UploadSessionStartResult value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - String f_sessionId = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("session_id".equals(field)) { - f_sessionId = StoneSerializers.string().deserialize(p); - } - else { - skipValue(p); - } - } - if (f_sessionId == null) { - throw new JsonParseException(p, "Required field \"session_id\" missing."); - } - value = new UploadSessionStartResult(f_sessionId); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionStartUploader.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionStartUploader.java deleted file mode 100644 index 4d569b97..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadSessionStartUploader.java +++ /dev/null @@ -1,38 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated by Stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import autosaveworld.zlibs.com.dropbox.core.DbxApiException; -import autosaveworld.zlibs.com.dropbox.core.DbxUploader; -import autosaveworld.zlibs.com.dropbox.core.DbxWrappedException; -import autosaveworld.zlibs.com.dropbox.core.http.HttpRequestor; - -/** - * The {@link DbxUploader} returned by {@link - * DbxUserFilesRequests#uploadSessionStart(boolean)}. - * - *

Use this class to upload data to the server and complete the request. - *

- * - *

This class should be properly closed after use to prevent resource leaks - * and allow network connection reuse. Always call {@link #close} when complete - * (see {@link DbxUploader} for examples).

- */ -public class UploadSessionStartUploader extends DbxUploader { - - /** - * Creates a new instance of this uploader. - * - * @param httpUploader Initiated HTTP upload request - * - * @throws NullPointerException if {@code httpUploader} is {@code null} - */ - public UploadSessionStartUploader(HttpRequestor.Uploader httpUploader) { - super(httpUploader, UploadSessionStartResult.Serializer.INSTANCE, autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers.void_()); - } - - protected DbxApiException newException(DbxWrappedException error) { - return new DbxApiException(error.getRequestId(), error.getUserMessage(), "Unexpected error response for \"upload_session/start\":" + error.getErrorValue()); - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadUploader.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadUploader.java deleted file mode 100644 index 36b0bb97..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadUploader.java +++ /dev/null @@ -1,37 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated by Stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import autosaveworld.zlibs.com.dropbox.core.DbxUploader; -import autosaveworld.zlibs.com.dropbox.core.DbxWrappedException; -import autosaveworld.zlibs.com.dropbox.core.http.HttpRequestor; - -/** - * The {@link DbxUploader} returned by {@link - * DbxUserFilesRequests#upload(String)}. - * - *

Use this class to upload data to the server and complete the request. - *

- * - *

This class should be properly closed after use to prevent resource leaks - * and allow network connection reuse. Always call {@link #close} when complete - * (see {@link DbxUploader} for examples).

- */ -public class UploadUploader extends DbxUploader { - - /** - * Creates a new instance of this uploader. - * - * @param httpUploader Initiated HTTP upload request - * - * @throws NullPointerException if {@code httpUploader} is {@code null} - */ - public UploadUploader(HttpRequestor.Uploader httpUploader) { - super(httpUploader, FileMetadata.Serializer.INSTANCE, UploadError.Serializer.INSTANCE); - } - - protected UploadErrorException newException(DbxWrappedException error) { - return new UploadErrorException("2/files/upload", error.getRequestId(), error.getUserMessage(), (UploadError) error.getErrorValue()); - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadWriteFailed.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadWriteFailed.java deleted file mode 100644 index 3bceb0c5..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/UploadWriteFailed.java +++ /dev/null @@ -1,166 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -public class UploadWriteFailed { - // struct files.UploadWriteFailed (files.stone) - - protected final WriteError reason; - protected final String uploadSessionId; - - /** - * - * @param reason The reason why the file couldn't be saved. Must not be - * {@code null}. - * @param uploadSessionId The upload session ID; this may be used to retry - * the commit. Must not be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public UploadWriteFailed(WriteError reason, String uploadSessionId) { - if (reason == null) { - throw new IllegalArgumentException("Required value for 'reason' is null"); - } - this.reason = reason; - if (uploadSessionId == null) { - throw new IllegalArgumentException("Required value for 'uploadSessionId' is null"); - } - this.uploadSessionId = uploadSessionId; - } - - /** - * The reason why the file couldn't be saved. - * - * @return value for this field, never {@code null}. - */ - public WriteError getReason() { - return reason; - } - - /** - * The upload session ID; this may be used to retry the commit. - * - * @return value for this field, never {@code null}. - */ - public String getUploadSessionId() { - return uploadSessionId; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - reason, - uploadSessionId - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - UploadWriteFailed other = (UploadWriteFailed) obj; - return ((this.reason == other.reason) || (this.reason.equals(other.reason))) - && ((this.uploadSessionId == other.uploadSessionId) || (this.uploadSessionId.equals(other.uploadSessionId))) - ; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(UploadWriteFailed value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("reason"); - WriteError.Serializer.INSTANCE.serialize(value.reason, g); - g.writeFieldName("upload_session_id"); - StoneSerializers.string().serialize(value.uploadSessionId, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public UploadWriteFailed deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - UploadWriteFailed value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - WriteError f_reason = null; - String f_uploadSessionId = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("reason".equals(field)) { - f_reason = WriteError.Serializer.INSTANCE.deserialize(p); - } - else if ("upload_session_id".equals(field)) { - f_uploadSessionId = StoneSerializers.string().deserialize(p); - } - else { - skipValue(p); - } - } - if (f_reason == null) { - throw new JsonParseException(p, "Required field \"reason\" missing."); - } - if (f_uploadSessionId == null) { - throw new JsonParseException(p, "Required field \"upload_session_id\" missing."); - } - value = new UploadWriteFailed(f_reason, f_uploadSessionId); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/VideoMetadata.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/VideoMetadata.java deleted file mode 100644 index c341a137..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/VideoMetadata.java +++ /dev/null @@ -1,290 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Date; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * Metadata for a video. - */ -public class VideoMetadata extends MediaMetadata { - // struct files.VideoMetadata (files.stone) - - protected final Long duration; - - /** - * Metadata for a video. - * - *

Use {@link newBuilder} to create instances of this class without - * specifying values for all optional fields.

- * - * @param dimensions Dimension of the photo/video. - * @param location The GPS coordinate of the photo/video. - * @param timeTaken The timestamp when the photo/video is taken. - * @param duration The duration of the video in milliseconds. - */ - public VideoMetadata(Dimensions dimensions, GpsCoordinates location, Date timeTaken, Long duration) { - super(dimensions, location, timeTaken); - this.duration = duration; - } - - /** - * Metadata for a video. - * - *

The default values for unset fields will be used.

- */ - public VideoMetadata() { - this(null, null, null, null); - } - - /** - * Dimension of the photo/video. - * - * @return value for this field, or {@code null} if not present. - */ - public Dimensions getDimensions() { - return dimensions; - } - - /** - * The GPS coordinate of the photo/video. - * - * @return value for this field, or {@code null} if not present. - */ - public GpsCoordinates getLocation() { - return location; - } - - /** - * The timestamp when the photo/video is taken. - * - * @return value for this field, or {@code null} if not present. - */ - public Date getTimeTaken() { - return timeTaken; - } - - /** - * The duration of the video in milliseconds. - * - * @return value for this field, or {@code null} if not present. - */ - public Long getDuration() { - return duration; - } - - /** - * Returns a new builder for creating an instance of this class. - * - * @return builder for this class. - */ - public static Builder newBuilder() { - return new Builder(); - } - - /** - * Builder for {@link VideoMetadata}. - */ - public static class Builder extends MediaMetadata.Builder { - - protected Long duration; - - protected Builder() { - this.duration = null; - } - - /** - * Set value for optional field. - * - * @param duration The duration of the video in milliseconds. - * - * @return this builder - */ - public Builder withDuration(Long duration) { - this.duration = duration; - return this; - } - - /** - * Set value for optional field. - * - * @param dimensions Dimension of the photo/video. - * - * @return this builder - */ - public Builder withDimensions(Dimensions dimensions) { - super.withDimensions(dimensions); - return this; - } - - /** - * Set value for optional field. - * - * @param location The GPS coordinate of the photo/video. - * - * @return this builder - */ - public Builder withLocation(GpsCoordinates location) { - super.withLocation(location); - return this; - } - - /** - * Set value for optional field. - * - * @param timeTaken The timestamp when the photo/video is taken. - * - * @return this builder - */ - public Builder withTimeTaken(Date timeTaken) { - super.withTimeTaken(timeTaken); - return this; - } - - /** - * Builds an instance of {@link VideoMetadata} configured with this - * builder's values - * - * @return new instance of {@link VideoMetadata} - */ - public VideoMetadata build() { - return new VideoMetadata(dimensions, location, timeTaken, duration); - } - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - duration - }); - hash = (31 * super.hashCode()) + hash; - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - VideoMetadata other = (VideoMetadata) obj; - return ((this.dimensions == other.dimensions) || (this.dimensions != null && this.dimensions.equals(other.dimensions))) - && ((this.location == other.location) || (this.location != null && this.location.equals(other.location))) - && ((this.timeTaken == other.timeTaken) || (this.timeTaken != null && this.timeTaken.equals(other.timeTaken))) - && ((this.duration == other.duration) || (this.duration != null && this.duration.equals(other.duration))) - ; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(VideoMetadata value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - writeTag("video", g); - if (value.dimensions != null) { - g.writeFieldName("dimensions"); - StoneSerializers.nullable(Dimensions.Serializer.INSTANCE).serialize(value.dimensions, g); - } - if (value.location != null) { - g.writeFieldName("location"); - StoneSerializers.nullable(GpsCoordinates.Serializer.INSTANCE).serialize(value.location, g); - } - if (value.timeTaken != null) { - g.writeFieldName("time_taken"); - StoneSerializers.nullable(StoneSerializers.timestamp()).serialize(value.timeTaken, g); - } - if (value.duration != null) { - g.writeFieldName("duration"); - StoneSerializers.nullable(StoneSerializers.uInt64()).serialize(value.duration, g); - } - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public VideoMetadata deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - VideoMetadata value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - if ("video".equals(tag)) { - tag = null; - } - } - if (tag == null) { - Dimensions f_dimensions = null; - GpsCoordinates f_location = null; - Date f_timeTaken = null; - Long f_duration = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("dimensions".equals(field)) { - f_dimensions = StoneSerializers.nullable(Dimensions.Serializer.INSTANCE).deserialize(p); - } - else if ("location".equals(field)) { - f_location = StoneSerializers.nullable(GpsCoordinates.Serializer.INSTANCE).deserialize(p); - } - else if ("time_taken".equals(field)) { - f_timeTaken = StoneSerializers.nullable(StoneSerializers.timestamp()).deserialize(p); - } - else if ("duration".equals(field)) { - f_duration = StoneSerializers.nullable(StoneSerializers.uInt64()).deserialize(p); - } - else { - skipValue(p); - } - } - value = new VideoMetadata(f_dimensions, f_location, f_timeTaken, f_duration); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/WriteConflictError.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/WriteConflictError.java deleted file mode 100644 index 010f67c7..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/WriteConflictError.java +++ /dev/null @@ -1,103 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; - -import autosaveworld.zlibs.com.dropbox.core.stone.UnionSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -public enum WriteConflictError { - // union files.WriteConflictError (files.stone) - /** - * There's a file in the way. - */ - FILE, - /** - * There's a folder in the way. - */ - FOLDER, - /** - * There's a file at an ancestor path, so we couldn't create the required - * parent folders. - */ - FILE_ANCESTOR, - /** - * Catch-all used for unknown tag values returned by the Dropbox servers. - * - *

Receiving a catch-all value typically indicates this SDK version is - * not up to date. Consider updating your SDK version to handle the new - * tags.

- */ - OTHER; // *catch_all - - /** - * For internal use only. - */ - static class Serializer extends UnionSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(WriteConflictError value, JsonGenerator g) throws IOException, JsonGenerationException { - switch (value) { - case FILE: { - g.writeString("file"); - break; - } - case FOLDER: { - g.writeString("folder"); - break; - } - case FILE_ANCESTOR: { - g.writeString("file_ancestor"); - break; - } - default: { - g.writeString("other"); - } - } - } - - @Override - public WriteConflictError deserialize(JsonParser p) throws IOException, JsonParseException { - WriteConflictError value; - boolean collapsed; - String tag; - if (p.getCurrentToken() == JsonToken.VALUE_STRING) { - collapsed = true; - tag = getStringValue(p); - p.nextToken(); - } - else { - collapsed = false; - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); - } - else if ("file".equals(tag)) { - value = WriteConflictError.FILE; - } - else if ("folder".equals(tag)) { - value = WriteConflictError.FOLDER; - } - else if ("file_ancestor".equals(tag)) { - value = WriteConflictError.FILE_ANCESTOR; - } - else { - value = WriteConflictError.OTHER; - skipFields(p); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/WriteError.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/WriteError.java deleted file mode 100644 index e84d5c36..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/WriteError.java +++ /dev/null @@ -1,428 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.UnionSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * This class is an open tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isAbc()} - * methods will return {@code true}. You can use {@link #tag()} to determine the - * tag associated with this instance. - * - *

Open unions may be extended in the future with additional tags. If a new - * tag is introduced that this SDK does not recognized, the {@link #OTHER} value - * will be used.

- */ -public final class WriteError { - // union files.WriteError (files.stone) - - /** - * Discriminating tag type for {@link WriteError}. - */ - public enum Tag { - MALFORMED_PATH, // String - /** - * Couldn't write to the target path because there was something in the - * way. - */ - CONFLICT, // WriteConflictError - /** - * The user doesn't have permissions to write to the target location. - */ - NO_WRITE_PERMISSION, - /** - * The user doesn't have enough available space (bytes) to write more - * data. - */ - INSUFFICIENT_SPACE, - /** - * Dropbox will not save the file or folder because of its name. - */ - DISALLOWED_NAME, - /** - * Catch-all used for unknown tag values returned by the Dropbox - * servers. - * - *

Receiving a catch-all value typically indicates this SDK version - * is not up to date. Consider updating your SDK version to handle the - * new tags.

- */ - OTHER; // *catch_all - } - - /** - * The user doesn't have permissions to write to the target location. - */ - public static final WriteError NO_WRITE_PERMISSION = new WriteError(Tag.NO_WRITE_PERMISSION, null, null); - /** - * The user doesn't have enough available space (bytes) to write more data. - */ - public static final WriteError INSUFFICIENT_SPACE = new WriteError(Tag.INSUFFICIENT_SPACE, null, null); - /** - * Dropbox will not save the file or folder because of its name. - */ - public static final WriteError DISALLOWED_NAME = new WriteError(Tag.DISALLOWED_NAME, null, null); - /** - * Catch-all used for unknown tag values returned by the Dropbox servers. - * - *

Receiving a catch-all value typically indicates this SDK version is - * not up to date. Consider updating your SDK version to handle the new - * tags.

- */ - public static final WriteError OTHER = new WriteError(Tag.OTHER, null, null); - - private final Tag _tag; - private final String malformedPathValue; - private final WriteConflictError conflictValue; - - /** - * - * @param conflictValue Couldn't write to the target path because there was - * something in the way. Must not be {@code null}. - * @param _tag Discriminating tag for this instance. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - private WriteError(Tag _tag, String malformedPathValue, WriteConflictError conflictValue) { - this._tag = _tag; - this.malformedPathValue = malformedPathValue; - this.conflictValue = conflictValue; - } - - /** - * Returns the tag for this instance. - * - *

This class is a tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isXyz()} - * methods will return {@code true}. Callers are recommended to use the tag - * value in a {@code switch} statement to properly handle the different - * values for this {@code WriteError}.

- * - *

If a tag returned by the server is unrecognized by this SDK, the - * {@link Tag#OTHER} value will be used.

- * - * @return the tag for this instance. - */ - public Tag tag() { - return _tag; - } - - /** - * Returns {@code true} if this instance has the tag {@link - * Tag#MALFORMED_PATH}, {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link - * Tag#MALFORMED_PATH}, {@code false} otherwise. - */ - public boolean isMalformedPath() { - return this._tag == Tag.MALFORMED_PATH; - } - - /** - * Returns an instance of {@code WriteError} that has its tag set to {@link - * Tag#MALFORMED_PATH}. - * - *

None

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code WriteError} with its tag set to {@link - * Tag#MALFORMED_PATH}. - */ - public static WriteError malformedPath(String value) { - return new WriteError(Tag.MALFORMED_PATH, value, null); - } - - /** - * Returns an instance of {@code WriteError} that has its tag set to {@link - * Tag#MALFORMED_PATH}. - * - *

None

- * - * @return Instance of {@code WriteError} with its tag set to {@link - * Tag#MALFORMED_PATH}. - */ - public static WriteError malformedPath() { - return malformedPath(null); - } - - /** - * This instance must be tagged as {@link Tag#MALFORMED_PATH}. - * - * @return The {@link String} value associated with this instance if {@link - * #isMalformedPath} is {@code true}. - * - * @throws IllegalStateException If {@link #isMalformedPath} is {@code - * false}. - */ - public String getMalformedPathValue() { - if (this._tag != Tag.MALFORMED_PATH) { - throw new IllegalStateException("Invalid tag: required Tag.MALFORMED_PATH, but was Tag." + this._tag.name()); - } - return malformedPathValue; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#CONFLICT}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#CONFLICT}, - * {@code false} otherwise. - */ - public boolean isConflict() { - return this._tag == Tag.CONFLICT; - } - - /** - * Returns an instance of {@code WriteError} that has its tag set to {@link - * Tag#CONFLICT}. - * - *

Couldn't write to the target path because there was something in the - * way.

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code WriteError} with its tag set to {@link - * Tag#CONFLICT}. - * - * @throws IllegalArgumentException if {@code value} is {@code null}. - */ - public static WriteError conflict(WriteConflictError value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - return new WriteError(Tag.CONFLICT, null, value); - } - - /** - * Couldn't write to the target path because there was something in the way. - * - *

This instance must be tagged as {@link Tag#CONFLICT}.

- * - * @return The {@link WriteConflictError} value associated with this - * instance if {@link #isConflict} is {@code true}. - * - * @throws IllegalStateException If {@link #isConflict} is {@code false}. - */ - public WriteConflictError getConflictValue() { - if (this._tag != Tag.CONFLICT) { - throw new IllegalStateException("Invalid tag: required Tag.CONFLICT, but was Tag." + this._tag.name()); - } - return conflictValue; - } - - /** - * Returns {@code true} if this instance has the tag {@link - * Tag#NO_WRITE_PERMISSION}, {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link - * Tag#NO_WRITE_PERMISSION}, {@code false} otherwise. - */ - public boolean isNoWritePermission() { - return this._tag == Tag.NO_WRITE_PERMISSION; - } - - /** - * Returns {@code true} if this instance has the tag {@link - * Tag#INSUFFICIENT_SPACE}, {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link - * Tag#INSUFFICIENT_SPACE}, {@code false} otherwise. - */ - public boolean isInsufficientSpace() { - return this._tag == Tag.INSUFFICIENT_SPACE; - } - - /** - * Returns {@code true} if this instance has the tag {@link - * Tag#DISALLOWED_NAME}, {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link - * Tag#DISALLOWED_NAME}, {@code false} otherwise. - */ - public boolean isDisallowedName() { - return this._tag == Tag.DISALLOWED_NAME; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#OTHER}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#OTHER}, - * {@code false} otherwise. - */ - public boolean isOther() { - return this._tag == Tag.OTHER; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - _tag, - malformedPathValue, - conflictValue - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - else if (obj instanceof WriteError) { - WriteError other = (WriteError) obj; - if (this._tag != other._tag) { - return false; - } - switch (_tag) { - case MALFORMED_PATH: - return (this.malformedPathValue == other.malformedPathValue) || (this.malformedPathValue != null && this.malformedPathValue.equals(other.malformedPathValue)); - case CONFLICT: - return (this.conflictValue == other.conflictValue) || (this.conflictValue.equals(other.conflictValue)); - case NO_WRITE_PERMISSION: - return true; - case INSUFFICIENT_SPACE: - return true; - case DISALLOWED_NAME: - return true; - case OTHER: - return true; - default: - return false; - } - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends UnionSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(WriteError value, JsonGenerator g) throws IOException, JsonGenerationException { - switch (value.tag()) { - case MALFORMED_PATH: { - g.writeStartObject(); - writeTag("malformed_path", g); - g.writeFieldName("malformed_path"); - StoneSerializers.nullable(StoneSerializers.string()).serialize(value.malformedPathValue, g); - g.writeEndObject(); - break; - } - case CONFLICT: { - g.writeStartObject(); - writeTag("conflict", g); - g.writeFieldName("conflict"); - WriteConflictError.Serializer.INSTANCE.serialize(value.conflictValue, g); - g.writeEndObject(); - break; - } - case NO_WRITE_PERMISSION: { - g.writeString("no_write_permission"); - break; - } - case INSUFFICIENT_SPACE: { - g.writeString("insufficient_space"); - break; - } - case DISALLOWED_NAME: { - g.writeString("disallowed_name"); - break; - } - default: { - g.writeString("other"); - } - } - } - - @Override - public WriteError deserialize(JsonParser p) throws IOException, JsonParseException { - WriteError value; - boolean collapsed; - String tag; - if (p.getCurrentToken() == JsonToken.VALUE_STRING) { - collapsed = true; - tag = getStringValue(p); - p.nextToken(); - } - else { - collapsed = false; - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); - } - else if ("malformed_path".equals(tag)) { - String fieldValue = null; - if (p.getCurrentToken() != JsonToken.END_OBJECT) { - expectField("malformed_path", p); - fieldValue = StoneSerializers.nullable(StoneSerializers.string()).deserialize(p); - } - if (fieldValue == null) { - value = WriteError.malformedPath(); - } - else { - value = WriteError.malformedPath(fieldValue); - } - } - else if ("conflict".equals(tag)) { - WriteConflictError fieldValue = null; - expectField("conflict", p); - fieldValue = WriteConflictError.Serializer.INSTANCE.deserialize(p); - value = WriteError.conflict(fieldValue); - } - else if ("no_write_permission".equals(tag)) { - value = WriteError.NO_WRITE_PERMISSION; - } - else if ("insufficient_space".equals(tag)) { - value = WriteError.INSUFFICIENT_SPACE; - } - else if ("disallowed_name".equals(tag)) { - value = WriteError.DISALLOWED_NAME; - } - else { - value = WriteError.OTHER; - skipFields(p); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/WriteMode.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/files/WriteMode.java deleted file mode 100644 index fef2a82b..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/files/WriteMode.java +++ /dev/null @@ -1,322 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from files.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.files; - -import java.io.IOException; -import java.util.Arrays; -import java.util.regex.Pattern; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.UnionSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * Your intent when writing a file to some path. This is used to determine what - * constitutes a conflict and what the autorename strategy is. In some - * situations, the conflict behavior is identical: (a) If the target path - * doesn't contain anything, the file is always written; no conflict. (b) If the - * target path contains a folder, it's always a conflict. (c) If the target path - * contains a file with identical contents, nothing gets written; no conflict. - * The conflict checking differs in the case where there's a file at the target - * path with contents different from the contents you're trying to write. - * - *

This class is a tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isAbc()} - * methods will return {@code true}. You can use {@link #tag()} to determine the - * tag associated with this instance.

- */ -public final class WriteMode { - // union files.WriteMode (files.stone) - - /** - * Discriminating tag type for {@link WriteMode}. - */ - public enum Tag { - /** - * Never overwrite the existing file. The autorename strategy is to - * append a number to the file name. For example, "document.txt" might - * become "document (2).txt". - */ - ADD, - /** - * Always overwrite the existing file. The autorename strategy is the - * same as it is for {@link WriteMode#ADD}. - */ - OVERWRITE, - /** - * Overwrite if the given "rev" matches the existing file's "rev". The - * autorename strategy is to append the string "conflicted copy" to the - * file name. For example, "document.txt" might become "document - * (conflicted copy).txt" or "document (Panda's conflicted copy).txt". - */ - UPDATE; // String - } - - /** - * Never overwrite the existing file. The autorename strategy is to append a - * number to the file name. For example, "document.txt" might become - * "document (2).txt". - */ - public static final WriteMode ADD = new WriteMode(Tag.ADD, null); - /** - * Always overwrite the existing file. The autorename strategy is the same - * as it is for {@link WriteMode#ADD}. - */ - public static final WriteMode OVERWRITE = new WriteMode(Tag.OVERWRITE, null); - - private final Tag _tag; - private final String updateValue; - - /** - * Your intent when writing a file to some path. This is used to determine - * what constitutes a conflict and what the autorename strategy is. In some - * situations, the conflict behavior is identical: (a) If the target path - * doesn't contain anything, the file is always written; no conflict. (b) If - * the target path contains a folder, it's always a conflict. (c) If the - * target path contains a file with identical contents, nothing gets - * written; no conflict. The conflict checking differs in the case where - * there's a file at the target path with contents different from the - * contents you're trying to write. - * - * @param updateValue Overwrite if the given "rev" matches the existing - * file's "rev". The autorename strategy is to append the string - * "conflicted copy" to the file name. For example, "document.txt" might - * become "document (conflicted copy).txt" or "document (Panda's - * conflicted copy).txt". Must have length of at least 9, match pattern - * "{@code [0-9a-f]+}", and not be {@code null}. - * @param _tag Discriminating tag for this instance. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - private WriteMode(Tag _tag, String updateValue) { - this._tag = _tag; - this.updateValue = updateValue; - } - - /** - * Returns the tag for this instance. - * - *

This class is a tagged union. Tagged unions instances are always - * associated to a specific tag. This means only one of the {@code isXyz()} - * methods will return {@code true}. Callers are recommended to use the tag - * value in a {@code switch} statement to properly handle the different - * values for this {@code WriteMode}.

- * - * @return the tag for this instance. - */ - public Tag tag() { - return _tag; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#ADD}, {@code - * false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#ADD}, - * {@code false} otherwise. - */ - public boolean isAdd() { - return this._tag == Tag.ADD; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#OVERWRITE}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#OVERWRITE}, - * {@code false} otherwise. - */ - public boolean isOverwrite() { - return this._tag == Tag.OVERWRITE; - } - - /** - * Returns {@code true} if this instance has the tag {@link Tag#UPDATE}, - * {@code false} otherwise. - * - * @return {@code true} if this instance is tagged as {@link Tag#UPDATE}, - * {@code false} otherwise. - */ - public boolean isUpdate() { - return this._tag == Tag.UPDATE; - } - - /** - * Returns an instance of {@code WriteMode} that has its tag set to {@link - * Tag#UPDATE}. - * - *

Overwrite if the given "rev" matches the existing file's "rev". The - * autorename strategy is to append the string "conflicted copy" to the file - * name. For example, "document.txt" might become "document (conflicted - * copy).txt" or "document (Panda's conflicted copy).txt".

- * - * @param value value to assign to this instance. - * - * @return Instance of {@code WriteMode} with its tag set to {@link - * Tag#UPDATE}. - * - * @throws IllegalArgumentException if {@code value} is shorter than 9, - * does not match pattern "{@code [0-9a-f]+}", or is {@code null}. - */ - public static WriteMode update(String value) { - if (value == null) { - throw new IllegalArgumentException("Value is null"); - } - if (value.length() < 9) { - throw new IllegalArgumentException("String is shorter than 9"); - } - if (!Pattern.matches("[0-9a-f]+", value)) { - throw new IllegalArgumentException("String does not match pattern"); - } - return new WriteMode(Tag.UPDATE, value); - } - - /** - * Overwrite if the given "rev" matches the existing file's "rev". The - * autorename strategy is to append the string "conflicted copy" to the file - * name. For example, "document.txt" might become "document (conflicted - * copy).txt" or "document (Panda's conflicted copy).txt". - * - *

This instance must be tagged as {@link Tag#UPDATE}.

- * - * @return The {@link String} value associated with this instance if {@link - * #isUpdate} is {@code true}. - * - * @throws IllegalStateException If {@link #isUpdate} is {@code false}. - */ - public String getUpdateValue() { - if (this._tag != Tag.UPDATE) { - throw new IllegalStateException("Invalid tag: required Tag.UPDATE, but was Tag." + this._tag.name()); - } - return updateValue; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - _tag, - updateValue - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - else if (obj instanceof WriteMode) { - WriteMode other = (WriteMode) obj; - if (this._tag != other._tag) { - return false; - } - switch (_tag) { - case ADD: - return true; - case OVERWRITE: - return true; - case UPDATE: - return (this.updateValue == other.updateValue) || (this.updateValue.equals(other.updateValue)); - default: - return false; - } - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends UnionSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(WriteMode value, JsonGenerator g) throws IOException, JsonGenerationException { - switch (value.tag()) { - case ADD: { - g.writeString("add"); - break; - } - case OVERWRITE: { - g.writeString("overwrite"); - break; - } - case UPDATE: { - g.writeStartObject(); - writeTag("update", g); - g.writeFieldName("update"); - StoneSerializers.string().serialize(value.updateValue, g); - g.writeEndObject(); - break; - } - default: { - throw new IllegalArgumentException("Unrecognized tag: " + value.tag()); - } - } - } - - @Override - public WriteMode deserialize(JsonParser p) throws IOException, JsonParseException { - WriteMode value; - boolean collapsed; - String tag; - if (p.getCurrentToken() == JsonToken.VALUE_STRING) { - collapsed = true; - tag = getStringValue(p); - p.nextToken(); - } - else { - collapsed = false; - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - throw new JsonParseException(p, "Required field missing: " + TAG_FIELD); - } - else if ("add".equals(tag)) { - value = WriteMode.ADD; - } - else if ("overwrite".equals(tag)) { - value = WriteMode.OVERWRITE; - } - else if ("update".equals(tag)) { - String fieldValue = null; - expectField("update", p); - fieldValue = StoneSerializers.string().deserialize(p); - value = WriteMode.update(fieldValue); - } - else { - throw new JsonParseException(p, "Unknown tag: " + tag); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/properties/PropertyField.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/properties/PropertyField.java deleted file mode 100644 index 331d3752..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/properties/PropertyField.java +++ /dev/null @@ -1,169 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from properties.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.properties; - -import java.io.IOException; -import java.util.Arrays; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -public class PropertyField { - // struct properties.PropertyField (properties.stone) - - protected final String name; - protected final String value; - - /** - * - * @param name This is the name or key of a custom property in a property - * template. File property names can be up to 256 bytes. Must not be - * {@code null}. - * @param value Value of a custom property attached to a file. Values can - * be up to 1024 bytes. Must not be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public PropertyField(String name, String value) { - if (name == null) { - throw new IllegalArgumentException("Required value for 'name' is null"); - } - this.name = name; - if (value == null) { - throw new IllegalArgumentException("Required value for 'value' is null"); - } - this.value = value; - } - - /** - * This is the name or key of a custom property in a property template. File - * property names can be up to 256 bytes. - * - * @return value for this field, never {@code null}. - */ - public String getName() { - return name; - } - - /** - * Value of a custom property attached to a file. Values can be up to 1024 - * bytes. - * - * @return value for this field, never {@code null}. - */ - public String getValue() { - return value; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - name, - value - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - PropertyField other = (PropertyField) obj; - return ((this.name == other.name) || (this.name.equals(other.name))) - && ((this.value == other.value) || (this.value.equals(other.value))) - ; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(PropertyField value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("name"); - StoneSerializers.string().serialize(value.name, g); - g.writeFieldName("value"); - StoneSerializers.string().serialize(value.value, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public PropertyField deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - PropertyField value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - String f_name = null; - String f_value = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("name".equals(field)) { - f_name = StoneSerializers.string().deserialize(p); - } - else if ("value".equals(field)) { - f_value = StoneSerializers.string().deserialize(p); - } - else { - skipValue(p); - } - } - if (f_name == null) { - throw new JsonParseException(p, "Required field \"name\" missing."); - } - if (f_value == null) { - throw new JsonParseException(p, "Required field \"value\" missing."); - } - value = new PropertyField(f_name, f_value); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/dropbox/core/v2/properties/PropertyGroup.java b/src/autosaveworld/zlibs/com/dropbox/core/v2/properties/PropertyGroup.java deleted file mode 100644 index 5bb7904a..00000000 --- a/src/autosaveworld/zlibs/com/dropbox/core/v2/properties/PropertyGroup.java +++ /dev/null @@ -1,186 +0,0 @@ -/* DO NOT EDIT */ -/* This file was generated from properties.stone */ - -package autosaveworld.zlibs.com.dropbox.core.v2.properties; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.regex.Pattern; - -import autosaveworld.zlibs.com.dropbox.core.stone.StoneSerializers; -import autosaveworld.zlibs.com.dropbox.core.stone.StructSerializer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * Collection of custom properties in filled property templates. - */ -public class PropertyGroup { - // struct properties.PropertyGroup (properties.stone) - - protected final String templateId; - protected final List fields; - - /** - * Collection of custom properties in filled property templates. - * - * @param templateId A unique identifier for a property template type. Must - * have length of at least 1, match pattern "{@code (/|ptid:).*}", and - * not be {@code null}. - * @param fields This is a list of custom properties associated with a - * file. There can be up to 32 properties for a template. Must not - * contain a {@code null} item and not be {@code null}. - * - * @throws IllegalArgumentException If any argument does not meet its - * preconditions. - */ - public PropertyGroup(String templateId, List fields) { - if (templateId == null) { - throw new IllegalArgumentException("Required value for 'templateId' is null"); - } - if (templateId.length() < 1) { - throw new IllegalArgumentException("String 'templateId' is shorter than 1"); - } - if (!Pattern.matches("(/|ptid:).*", templateId)) { - throw new IllegalArgumentException("String 'templateId' does not match pattern"); - } - this.templateId = templateId; - if (fields == null) { - throw new IllegalArgumentException("Required value for 'fields' is null"); - } - for (PropertyField x : fields) { - if (x == null) { - throw new IllegalArgumentException("An item in list 'fields' is null"); - } - } - this.fields = fields; - } - - /** - * A unique identifier for a property template type. - * - * @return value for this field, never {@code null}. - */ - public String getTemplateId() { - return templateId; - } - - /** - * This is a list of custom properties associated with a file. There can be - * up to 32 properties for a template. - * - * @return value for this field, never {@code null}. - */ - public List getFields() { - return fields; - } - - @Override - public int hashCode() { - int hash = Arrays.hashCode(new Object [] { - templateId, - fields - }); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - // be careful with inheritance - else if (obj.getClass().equals(this.getClass())) { - PropertyGroup other = (PropertyGroup) obj; - return ((this.templateId == other.templateId) || (this.templateId.equals(other.templateId))) - && ((this.fields == other.fields) || (this.fields.equals(other.fields))) - ; - } - else { - return false; - } - } - - @Override - public String toString() { - return Serializer.INSTANCE.serialize(this, false); - } - - /** - * Returns a String representation of this object formatted for easier - * readability. - * - *

The returned String may contain newlines.

- * - * @return Formatted, multiline String representation of this object - */ - public String toStringMultiline() { - return Serializer.INSTANCE.serialize(this, true); - } - - /** - * For internal use only. - */ - public static class Serializer extends StructSerializer { - public static final Serializer INSTANCE = new Serializer(); - - @Override - public void serialize(PropertyGroup value, JsonGenerator g, boolean collapse) throws IOException, JsonGenerationException { - if (!collapse) { - g.writeStartObject(); - } - g.writeFieldName("template_id"); - StoneSerializers.string().serialize(value.templateId, g); - g.writeFieldName("fields"); - StoneSerializers.list(PropertyField.Serializer.INSTANCE).serialize(value.fields, g); - if (!collapse) { - g.writeEndObject(); - } - } - - @Override - public PropertyGroup deserialize(JsonParser p, boolean collapsed) throws IOException, JsonParseException { - PropertyGroup value; - String tag = null; - if (!collapsed) { - expectStartObject(p); - tag = readTag(p); - } - if (tag == null) { - String f_templateId = null; - List f_fields = null; - while (p.getCurrentToken() == JsonToken.FIELD_NAME) { - String field = p.getCurrentName(); - p.nextToken(); - if ("template_id".equals(field)) { - f_templateId = StoneSerializers.string().deserialize(p); - } - else if ("fields".equals(field)) { - f_fields = StoneSerializers.list(PropertyField.Serializer.INSTANCE).deserialize(p); - } - else { - skipValue(p); - } - } - if (f_templateId == null) { - throw new JsonParseException(p, "Required field \"template_id\" missing."); - } - if (f_fields == null) { - throw new JsonParseException(p, "Required field \"fields\" missing."); - } - value = new PropertyGroup(f_templateId, f_fields); - } - else { - throw new JsonParseException(p, "No subtype found that matches tag: \"" + tag + "\""); - } - if (!collapsed) { - expectEndObject(p); - } - return value; - } - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/Base64Variant.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/Base64Variant.java deleted file mode 100644 index fd41fcba..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/Base64Variant.java +++ /dev/null @@ -1,594 +0,0 @@ -/* Jackson JSON-processor. - * - * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi - */ -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -import java.util.Arrays; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.ByteArrayBuilder; - -/** - * Abstract base class used to define specific details of which - * variant of Base64 encoding/decoding is to be used. Although there is - * somewhat standard basic version (so-called "MIME Base64"), other variants - * exists, see Base64 Wikipedia entry for details. - * - * @author Tatu Saloranta - */ -public final class Base64Variant - implements java.io.Serializable -{ - private final static int INT_SPACE = 0x20; - - // We'll only serialize name - private static final long serialVersionUID = 1L; - - /** - * Placeholder used by "no padding" variant, to be used when a character - * value is needed. - */ - final static char PADDING_CHAR_NONE = '\0'; - - /** - * Marker used to denote ascii characters that do not correspond - * to a 6-bit value (in this variant), and is not used as a padding - * character. - */ - public final static int BASE64_VALUE_INVALID = -1; - - /** - * Marker used to denote ascii character (in decoding table) that - * is the padding character using this variant (if any). - */ - public final static int BASE64_VALUE_PADDING = -2; - - /* - /********************************************************** - /* Encoding/decoding tables - /********************************************************** - */ - - /** - * Decoding table used for base 64 decoding. - */ - private final transient int[] _asciiToBase64 = new int[128]; - - /** - * Encoding table used for base 64 decoding when output is done - * as characters. - */ - private final transient char[] _base64ToAsciiC = new char[64]; - - /** - * Alternative encoding table used for base 64 decoding when output is done - * as ascii bytes. - */ - private final transient byte[] _base64ToAsciiB = new byte[64]; - - /* - /********************************************************** - /* Other configuration - /********************************************************** - */ - - /** - * Symbolic name of variant; used for diagnostics/debugging. - *

- * Note that this is the only non-transient field; used when reading - * back from serialized state. - *

- * Also: must not be private, accessed from `BaseVariants` - */ - final String _name; - - /** - * Whether this variant uses padding or not. - */ - private final transient boolean _usesPadding; - - /** - * Characted used for padding, if any ({@link #PADDING_CHAR_NONE} if not). - */ - private final transient char _paddingChar; - - /** - * Maximum number of encoded base64 characters to output during encoding - * before adding a linefeed, if line length is to be limited - * ({@link java.lang.Integer#MAX_VALUE} if not limited). - *

- * Note: for some output modes (when writing attributes) linefeeds may - * need to be avoided, and this value ignored. - */ - private final transient int _maxLineLength; - - /* - /********************************************************** - /* Life-cycle - /********************************************************** - */ - - public Base64Variant(String name, String base64Alphabet, boolean usesPadding, char paddingChar, int maxLineLength) - { - _name = name; - _usesPadding = usesPadding; - _paddingChar = paddingChar; - _maxLineLength = maxLineLength; - - // Ok and then we need to create codec tables. - - // First the main encoding table: - int alphaLen = base64Alphabet.length(); - if (alphaLen != 64) { - throw new IllegalArgumentException("Base64Alphabet length must be exactly 64 (was "+alphaLen+")"); - } - - // And then secondary encoding table and decoding table: - base64Alphabet.getChars(0, alphaLen, _base64ToAsciiC, 0); - Arrays.fill(_asciiToBase64, BASE64_VALUE_INVALID); - for (int i = 0; i < alphaLen; ++i) { - char alpha = _base64ToAsciiC[i]; - _base64ToAsciiB[i] = (byte) alpha; - _asciiToBase64[alpha] = i; - } - - // Plus if we use padding, add that in too - if (usesPadding) { - _asciiToBase64[(int) paddingChar] = BASE64_VALUE_PADDING; - } - } - - /** - * "Copy constructor" that can be used when the base alphabet is identical - * to one used by another variant except for the maximum line length - * (and obviously, name). - */ - public Base64Variant(Base64Variant base, String name, int maxLineLength) - { - this(base, name, base._usesPadding, base._paddingChar, maxLineLength); - } - - /** - * "Copy constructor" that can be used when the base alphabet is identical - * to one used by another variant, but other details (padding, maximum - * line length) differ - */ - public Base64Variant(Base64Variant base, String name, boolean usesPadding, char paddingChar, int maxLineLength) - { - _name = name; - byte[] srcB = base._base64ToAsciiB; - System.arraycopy(srcB, 0, this._base64ToAsciiB, 0, srcB.length); - char[] srcC = base._base64ToAsciiC; - System.arraycopy(srcC, 0, this._base64ToAsciiC, 0, srcC.length); - int[] srcV = base._asciiToBase64; - System.arraycopy(srcV, 0, this._asciiToBase64, 0, srcV.length); - - _usesPadding = usesPadding; - _paddingChar = paddingChar; - _maxLineLength = maxLineLength; - } - - /* - /********************************************************** - /* Serializable overrides - /********************************************************** - */ - - /** - * Method used to "demote" deserialized instances back to - * canonical ones - */ - protected Object readResolve() { - return Base64Variants.valueOf(_name); - } - - /* - /********************************************************** - /* Public accessors - /********************************************************** - */ - - public String getName() { return _name; } - - public boolean usesPadding() { return _usesPadding; } - public boolean usesPaddingChar(char c) { return c == _paddingChar; } - public boolean usesPaddingChar(int ch) { return ch == (int) _paddingChar; } - public char getPaddingChar() { return _paddingChar; } - public byte getPaddingByte() { return (byte)_paddingChar; } - - public int getMaxLineLength() { return _maxLineLength; } - - /* - /********************************************************** - /* Decoding support - /********************************************************** - */ - - /** - * @return 6-bit decoded value, if valid character; - */ - public int decodeBase64Char(char c) - { - int ch = (int) c; - return (ch <= 127) ? _asciiToBase64[ch] : BASE64_VALUE_INVALID; - } - - public int decodeBase64Char(int ch) - { - return (ch <= 127) ? _asciiToBase64[ch] : BASE64_VALUE_INVALID; - } - - public int decodeBase64Byte(byte b) - { - int ch = (int) b; - // note: cast retains sign, so it's from -128 to +127 - if (ch < 0) { - return BASE64_VALUE_INVALID; - } - return _asciiToBase64[ch]; - } - - /* - /********************************************************** - /* Encoding support - /********************************************************** - */ - - public char encodeBase64BitsAsChar(int value) - { - /* Let's assume caller has done necessary checks; this - * method must be fast and inlinable - */ - return _base64ToAsciiC[value]; - } - - /** - * Method that encodes given right-aligned (LSB) 24-bit value - * into 4 base64 characters, stored in given result buffer. - */ - public int encodeBase64Chunk(int b24, char[] buffer, int ptr) - { - buffer[ptr++] = _base64ToAsciiC[(b24 >> 18) & 0x3F]; - buffer[ptr++] = _base64ToAsciiC[(b24 >> 12) & 0x3F]; - buffer[ptr++] = _base64ToAsciiC[(b24 >> 6) & 0x3F]; - buffer[ptr++] = _base64ToAsciiC[b24 & 0x3F]; - return ptr; - } - - public void encodeBase64Chunk(StringBuilder sb, int b24) - { - sb.append(_base64ToAsciiC[(b24 >> 18) & 0x3F]); - sb.append(_base64ToAsciiC[(b24 >> 12) & 0x3F]); - sb.append(_base64ToAsciiC[(b24 >> 6) & 0x3F]); - sb.append(_base64ToAsciiC[b24 & 0x3F]); - } - - /** - * Method that outputs partial chunk (which only encodes one - * or two bytes of data). Data given is still aligned same as if - * it as full data; that is, missing data is at the "right end" - * (LSB) of int. - * - * @param outputBytes Number of encoded bytes included (either 1 or 2) - */ - public int encodeBase64Partial(int bits, int outputBytes, char[] buffer, int outPtr) - { - buffer[outPtr++] = _base64ToAsciiC[(bits >> 18) & 0x3F]; - buffer[outPtr++] = _base64ToAsciiC[(bits >> 12) & 0x3F]; - if (_usesPadding) { - buffer[outPtr++] = (outputBytes == 2) ? - _base64ToAsciiC[(bits >> 6) & 0x3F] : _paddingChar; - buffer[outPtr++] = _paddingChar; - } else { - if (outputBytes == 2) { - buffer[outPtr++] = _base64ToAsciiC[(bits >> 6) & 0x3F]; - } - } - return outPtr; - } - - public void encodeBase64Partial(StringBuilder sb, int bits, int outputBytes) - { - sb.append(_base64ToAsciiC[(bits >> 18) & 0x3F]); - sb.append(_base64ToAsciiC[(bits >> 12) & 0x3F]); - if (_usesPadding) { - sb.append((outputBytes == 2) ? - _base64ToAsciiC[(bits >> 6) & 0x3F] : _paddingChar); - sb.append(_paddingChar); - } else { - if (outputBytes == 2) { - sb.append(_base64ToAsciiC[(bits >> 6) & 0x3F]); - } - } - } - - public byte encodeBase64BitsAsByte(int value) - { - // As with above, assuming it is 6-bit value - return _base64ToAsciiB[value]; - } - - /** - * Method that encodes given right-aligned (LSB) 24-bit value - * into 4 base64 bytes (ascii), stored in given result buffer. - */ - public int encodeBase64Chunk(int b24, byte[] buffer, int ptr) - { - buffer[ptr++] = _base64ToAsciiB[(b24 >> 18) & 0x3F]; - buffer[ptr++] = _base64ToAsciiB[(b24 >> 12) & 0x3F]; - buffer[ptr++] = _base64ToAsciiB[(b24 >> 6) & 0x3F]; - buffer[ptr++] = _base64ToAsciiB[b24 & 0x3F]; - return ptr; - } - - /** - * Method that outputs partial chunk (which only encodes one - * or two bytes of data). Data given is still aligned same as if - * it as full data; that is, missing data is at the "right end" - * (LSB) of int. - * - * @param outputBytes Number of encoded bytes included (either 1 or 2) - */ - public int encodeBase64Partial(int bits, int outputBytes, byte[] buffer, int outPtr) - { - buffer[outPtr++] = _base64ToAsciiB[(bits >> 18) & 0x3F]; - buffer[outPtr++] = _base64ToAsciiB[(bits >> 12) & 0x3F]; - if (_usesPadding) { - byte pb = (byte) _paddingChar; - buffer[outPtr++] = (outputBytes == 2) ? - _base64ToAsciiB[(bits >> 6) & 0x3F] : pb; - buffer[outPtr++] = pb; - } else { - if (outputBytes == 2) { - buffer[outPtr++] = _base64ToAsciiB[(bits >> 6) & 0x3F]; - } - } - return outPtr; - } - - /* - /********************************************************** - /* Convenience conversion methods for String to/from bytes - /* use case. - /********************************************************** - */ - - /** - * Convenience method for converting given byte array as base64 encoded - * String using this variant's settings. - * Resulting value is "raw", that is, not enclosed in double-quotes. - * - * @param input Byte array to encode - */ - public String encode(byte[] input) - { - return encode(input, false); - } - - /** - * Convenience method for converting given byte array as base64 encoded String - * using this variant's settings, - * optionally enclosed in double-quotes. - * - * @param input Byte array to encode - * @param addQuotes Whether to surround resulting value in double quotes or not - */ - public String encode(byte[] input, boolean addQuotes) - { - int inputEnd = input.length; - StringBuilder sb; - { - // let's approximate... 33% overhead, ~= 3/8 (0.375) - int outputLen = inputEnd + (inputEnd >> 2) + (inputEnd >> 3); - sb = new StringBuilder(outputLen); - } - if (addQuotes) { - sb.append('"'); - } - - int chunksBeforeLF = getMaxLineLength() >> 2; - - // Ok, first we loop through all full triplets of data: - int inputPtr = 0; - int safeInputEnd = inputEnd-3; // to get only full triplets - - while (inputPtr <= safeInputEnd) { - // First, mash 3 bytes into lsb of 32-bit int - int b24 = ((int) input[inputPtr++]) << 8; - b24 |= ((int) input[inputPtr++]) & 0xFF; - b24 = (b24 << 8) | (((int) input[inputPtr++]) & 0xFF); - encodeBase64Chunk(sb, b24); - if (--chunksBeforeLF <= 0) { - // note: must quote in JSON value, so not really useful... - sb.append('\\'); - sb.append('n'); - chunksBeforeLF = getMaxLineLength() >> 2; - } - } - - // And then we may have 1 or 2 leftover bytes to encode - int inputLeft = inputEnd - inputPtr; // 0, 1 or 2 - if (inputLeft > 0) { // yes, but do we have room for output? - int b24 = ((int) input[inputPtr++]) << 16; - if (inputLeft == 2) { - b24 |= (((int) input[inputPtr++]) & 0xFF) << 8; - } - encodeBase64Partial(sb, b24, inputLeft); - } - - if (addQuotes) { - sb.append('"'); - } - return sb.toString(); - } - - /** - * Convenience method for decoding contents of a Base64-encoded String, - * using this variant's settings. - * - * @param input - * - * @since 2.2.3 - * - * @throws IllegalArgumentException if input is not valid base64 encoded data - */ - public byte[] decode(String input) throws IllegalArgumentException - { - ByteArrayBuilder b = new ByteArrayBuilder(); - decode(input, b); - return b.toByteArray(); - } - - /** - * Convenience method for decoding contents of a Base64-encoded String, - * using this variant's settings - * and appending decoded binary data using provided {@link ByteArrayBuilder}. - *

- * NOTE: builder will NOT be reset before decoding (nor cleared afterwards); - * assumption is that caller will ensure it is given in proper state, and - * used as appropriate afterwards. - * - * @since 2.3 - * - * @throws IllegalArgumentException if input is not valid base64 encoded data - */ - public void decode(String str, ByteArrayBuilder builder) throws IllegalArgumentException - { - int ptr = 0; - int len = str.length(); - - while (ptr < len) { - // first, we'll skip preceding white space, if any - char ch; - do { - ch = str.charAt(ptr++); - } while ((ptr < len) && (ch <= INT_SPACE)); - int bits = decodeBase64Char(ch); - if (bits < 0) { - _reportInvalidBase64(ch, 0, null); - } - int decodedData = bits; - // then second base64 char; can't get padding yet, nor ws - if (ptr >= len) { - _reportBase64EOF(); - } - ch = str.charAt(ptr++); - bits = decodeBase64Char(ch); - if (bits < 0) { - _reportInvalidBase64(ch, 1, null); - } - decodedData = (decodedData << 6) | bits; - // third base64 char; can be padding, but not ws - if (ptr >= len) { - // but as per [JACKSON-631] can be end-of-input, iff not using padding - if (!usesPadding()) { - decodedData >>= 4; - builder.append(decodedData); - break; - } - _reportBase64EOF(); - } - ch = str.charAt(ptr++); - bits = decodeBase64Char(ch); - - // First branch: can get padding (-> 1 byte) - if (bits < 0) { - if (bits != Base64Variant.BASE64_VALUE_PADDING) { - _reportInvalidBase64(ch, 2, null); - } - // Ok, must get padding - if (ptr >= len) { - _reportBase64EOF(); - } - ch = str.charAt(ptr++); - if (!usesPaddingChar(ch)) { - _reportInvalidBase64(ch, 3, "expected padding character '"+getPaddingChar()+"'"); - } - // Got 12 bits, only need 8, need to shift - decodedData >>= 4; - builder.append(decodedData); - continue; - } - // Nope, 2 or 3 bytes - decodedData = (decodedData << 6) | bits; - // fourth and last base64 char; can be padding, but not ws - if (ptr >= len) { - // but as per [JACKSON-631] can be end-of-input, iff not using padding - if (!usesPadding()) { - decodedData >>= 2; - builder.appendTwoBytes(decodedData); - break; - } - _reportBase64EOF(); - } - ch = str.charAt(ptr++); - bits = decodeBase64Char(ch); - if (bits < 0) { - if (bits != Base64Variant.BASE64_VALUE_PADDING) { - _reportInvalidBase64(ch, 3, null); - } - decodedData >>= 2; - builder.appendTwoBytes(decodedData); - } else { - // otherwise, our triple is now complete - decodedData = (decodedData << 6) | bits; - builder.appendThreeBytes(decodedData); - } - } - } - - /* - /********************************************************** - /* Overridden standard methods - /********************************************************** - */ - - @Override - public String toString() { return _name; } - - @Override - public boolean equals(Object o) { - // identity comparison should be dine - return (o == this); - } - - @Override - public int hashCode() { - return _name.hashCode(); - } - - /* - /********************************************************** - /* Internal helper methods - /********************************************************** - */ - - /** - * @param bindex Relative index within base64 character unit; between 0 - * and 3 (as unit has exactly 4 characters) - */ - protected void _reportInvalidBase64(char ch, int bindex, String msg) - throws IllegalArgumentException - { - String base; - if (ch <= INT_SPACE) { - base = "Illegal white space character (code 0x"+Integer.toHexString(ch)+") as character #"+(bindex+1)+" of 4-char base64 unit: can only used between units"; - } else if (usesPaddingChar(ch)) { - base = "Unexpected padding character ('"+getPaddingChar()+"') as character #"+(bindex+1)+" of 4-char base64 unit: padding only legal as 3rd or 4th character"; - } else if (!Character.isDefined(ch) || Character.isISOControl(ch)) { - // Not sure if we can really get here... ? (most illegal xml chars are caught at lower level) - base = "Illegal character (code 0x"+Integer.toHexString(ch)+") in base64 content"; - } else { - base = "Illegal character '"+ch+"' (code 0x"+Integer.toHexString(ch)+") in base64 content"; - } - if (msg != null) { - base = base + ": " + msg; - } - throw new IllegalArgumentException(base); - } - - protected void _reportBase64EOF() throws IllegalArgumentException { - throw new IllegalArgumentException("Unexpected end-of-String in base64 content"); - } -} - diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/Base64Variants.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/Base64Variants.java deleted file mode 100644 index 4c47c323..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/Base64Variants.java +++ /dev/null @@ -1,111 +0,0 @@ -/* Jackson JSON-processor. - * - * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi - */ -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -/** - * Container for commonly used Base64 variants: - *

    - *
  • {@link #MIME} - *
  • {@link #MIME_NO_LINEFEEDS} - *
  • {@link #PEM} - *
  • {@link #MODIFIED_FOR_URL} - *
- * - * @author Tatu Saloranta - */ -public final class Base64Variants -{ - final static String STD_BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - /** - * This variant is what most people would think of "the standard" - * Base64 encoding. - *

- * See wikipedia Base64 entry for details. - *

- * Note that although this can be thought of as the standard variant, - * it is not the default for Jackson: no-linefeeds alternative - * is because of JSON requirement of escaping all linefeeds. - */ - public final static Base64Variant MIME; - static { - MIME = new Base64Variant("MIME", STD_BASE64_ALPHABET, true, '=', 76); - } - - /** - * Slightly non-standard modification of {@link #MIME} which does not - * use linefeeds (max line length set to infinite). Useful when linefeeds - * wouldn't work well (possibly in attributes), or for minor space savings - * (save 1 linefeed per 76 data chars, ie. ~1.4% savings). - */ - public final static Base64Variant MIME_NO_LINEFEEDS; - static { - MIME_NO_LINEFEEDS = new Base64Variant(MIME, "MIME-NO-LINEFEEDS", Integer.MAX_VALUE); - } - - /** - * This variant is the one that predates {@link #MIME}: it is otherwise - * identical, except that it mandates shorter line length. - */ - public final static Base64Variant PEM = new Base64Variant(MIME, "PEM", true, '=', 64); - - /** - * This non-standard variant is usually used when encoded data needs to be - * passed via URLs (such as part of GET request). It differs from the - * base {@link #MIME} variant in multiple ways. - * First, no padding is used: this also means that it generally can not - * be written in multiple separate but adjacent chunks (which would not - * be the usual use case in any case). Also, no linefeeds are used (max - * line length set to infinite). And finally, two characters (plus and - * slash) that would need quoting in URLs are replaced with more - * optimal alternatives (hyphen and underscore, respectively). - */ - public final static Base64Variant MODIFIED_FOR_URL; - static { - StringBuilder sb = new StringBuilder(STD_BASE64_ALPHABET); - // Replace plus with hyphen, slash with underscore (and no padding) - sb.setCharAt(sb.indexOf("+"), '-'); - sb.setCharAt(sb.indexOf("/"), '_'); - /* And finally, let's not split lines either, wouldn't work too - * well with URLs - */ - MODIFIED_FOR_URL = new Base64Variant("MODIFIED-FOR-URL", sb.toString(), false, Base64Variant.PADDING_CHAR_NONE, Integer.MAX_VALUE); - } - - /** - * Method used to get the default variant ("MIME_NO_LINEFEEDS") for cases - * where caller does not explicitly specify the variant. - * We will prefer no-linefeed version because linefeeds in JSON values - * must be escaped, making linefeed-containing variants sub-optimal. - */ - public static Base64Variant getDefaultVariant() { - return MIME_NO_LINEFEEDS; - } - - /** - * @since 2.1 - */ - public static Base64Variant valueOf(String name) throws IllegalArgumentException - { - if (MIME._name.equals(name)) { - return MIME; - } - if (MIME_NO_LINEFEEDS._name.equals(name)) { - return MIME_NO_LINEFEEDS; - } - if (PEM._name.equals(name)) { - return PEM; - } - if (MODIFIED_FOR_URL._name.equals(name)) { - return MODIFIED_FOR_URL; - } - if (name == null) { - name = ""; - } else { - name = "'"+name+"'"; - } - throw new IllegalArgumentException("No Base64Variant with name "+name); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/FormatFeature.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/FormatFeature.java deleted file mode 100644 index 7fd3710f..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/FormatFeature.java +++ /dev/null @@ -1,33 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -/** - * Marker interface that is to be implemented by data format - specific features. - * Interface used since Java Enums can not extend classes or other Enums, but - * they can implement interfaces; and as such we may be able to use limited - * amount of generic functionality. - *

- * Note that this type is only implemented by non-JSON formats: - * types {@link JsonParser.Feature} and {@link JsonGenerator.Feature} do NOT - * implement it. This is to make it easier to avoid ambiguity with method - * calls. - * - * @since 2.6 (to be fully used in 2.7 and beyond) - */ -public interface FormatFeature -{ - /** - * Accessor for checking whether this feature is enabled by default. - */ - public boolean enabledByDefault(); - - /** - * Returns bit mask for this feature instance; must be a single bit, - * that is of form (1 << N) - */ - public int getMask(); - - /** - * Convenience method for checking whether feature is enabled in given bitmask - */ - public boolean enabledIn(int flags); -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/FormatSchema.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/FormatSchema.java deleted file mode 100644 index b767d84d..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/FormatSchema.java +++ /dev/null @@ -1,32 +0,0 @@ -/* Jackson JSON-processor. - * - * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi - */ - -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -/** - * Simple tag interface used to mark schema objects that are used by some - * {@link JsonParser} and {@link JsonGenerator} implementations to further - * specify structure of expected format. - * Basic JSON-based parsers and generators do not use schemas, but some data - * formats (like many binary data formats like Thrift, protobuf) mandate - * use of schemas. - *

- * Since there is little commonality between schemas for different data formats, - * this interface does not define much meaningful functionality for accessing - * schema details; rather, specific parser and generator implementations need - * to cast to schema implementations they use. This marker interface is mostly - * used for tagging "some kind of schema" -- instead of passing opaque - * {@link java.lang.Object} -- for documentation purposes. - */ -public interface FormatSchema -{ - /** - * Method that can be used to get an identifier that can be used for diagnostics - * purposes, to indicate what kind of data format this schema is used for: typically - * it is a short name of format itself, but it can also contain additional information - * in cases where data format supports multiple types of schemas. - */ - String getSchemaType(); -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonEncoding.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonEncoding.java deleted file mode 100644 index 47c1ae1f..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonEncoding.java +++ /dev/null @@ -1,57 +0,0 @@ -/* Jackson JSON-processor. - * - * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi - */ - -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -/** - * Enumeration that defines legal encodings that can be used - * for JSON content, based on list of allowed encodings from - * JSON specification. - *

- * Note: if application want to explicitly disregard Encoding - * limitations (to read in JSON encoded using an encoding not - * listed as allowed), they can use {@link java.io.Reader} / - * {@link java.io.Writer} instances as input - */ -public enum JsonEncoding { - UTF8("UTF-8", false, 8), // N/A for big-endian, really - UTF16_BE("UTF-16BE", true, 16), - UTF16_LE("UTF-16LE", false, 16), - UTF32_BE("UTF-32BE", true, 32), - UTF32_LE("UTF-32LE", false, 32) - ; - - private final String _javaName; - - private final boolean _bigEndian; - - private final int _bits; - - JsonEncoding(String javaName, boolean bigEndian, int bits) - { - _javaName = javaName; - _bigEndian = bigEndian; - _bits = bits; - } - - /** - * Method for accessing encoding name that JDK will support. - * - * @return Matching encoding name that JDK will support. - */ - public String getJavaName() { return _javaName; } - - /** - * Whether encoding is big-endian (if encoding supports such - * notion). If no such distinction is made (as is the case for - * {@link #UTF8}), return value is undefined. - * - * @return True for big-endian encodings; false for little-endian - * (or if not applicable) - */ - public boolean isBigEndian() { return _bigEndian; } - - public int bits() { return _bits; } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonFactory.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonFactory.java deleted file mode 100644 index 3f64e300..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonFactory.java +++ /dev/null @@ -1,1572 +0,0 @@ -/* Jackson JSON-processor. - * - * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi - */ -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -import java.io.CharArrayReader; -import java.io.DataInput; -import java.io.DataOutput; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.io.StringReader; -import java.io.Writer; -import java.lang.ref.SoftReference; -import java.net.URL; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.format.InputAccessor; -import autosaveworld.zlibs.com.fasterxml.jackson.core.format.MatchStrength; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.CharacterEscapes; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.DataOutputAsStream; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.IOContext; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.InputDecorator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.OutputDecorator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.SerializedString; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.UTF8Writer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.json.ByteSourceJsonBootstrapper; -import autosaveworld.zlibs.com.fasterxml.jackson.core.json.ReaderBasedJsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.json.UTF8DataInputJsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.json.UTF8JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.json.WriterBasedJsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.sym.CharsToNameCanonicalizer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.BufferRecycler; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.DefaultPrettyPrinter; - -/** - * The main factory class of Jackson package, used to configure and - * construct reader (aka parser, {@link JsonParser}) - * and writer (aka generator, {@link JsonGenerator}) - * instances. - *

- * Factory instances are thread-safe and reusable after configuration - * (if any). Typically applications and services use only a single - * globally shared factory instance, unless they need differently - * configured factories. Factory reuse is important if efficiency matters; - * most recycling of expensive construct is done on per-factory basis. - *

- * Creation of a factory instance is a light-weight operation, - * and since there is no need for pluggable alternative implementations - * (as there is no "standard" JSON processor API to implement), - * the default constructor is used for constructing factory - * instances. - * - * @author Tatu Saloranta - */ -public class JsonFactory - implements Versioned, - java.io.Serializable // since 2.1 (for Android, mostly) -{ - private static final long serialVersionUID = 1; // since 2.6.0 - - /* - /********************************************************** - /* Helper types - /********************************************************** - */ - - /** - * Enumeration that defines all on/off features that can only be - * changed for {@link JsonFactory}. - */ - public enum Feature { - - // // // Symbol handling (interning etc) - - /** - * Feature that determines whether JSON object field names are - * to be canonicalized using {@link String#intern} or not: - * if enabled, all field names will be intern()ed (and caller - * can count on this being true for all such names); if disabled, - * no intern()ing is done. There may still be basic - * canonicalization (that is, same String will be used to represent - * all identical object property names for a single document). - *

- * Note: this setting only has effect if - * {@link #CANONICALIZE_FIELD_NAMES} is true -- otherwise no - * canonicalization of any sort is done. - *

- * This setting is enabled by default. - */ - INTERN_FIELD_NAMES(true), - - /** - * Feature that determines whether JSON object field names are - * to be canonicalized (details of how canonicalization is done - * then further specified by - * {@link #INTERN_FIELD_NAMES}). - *

- * This setting is enabled by default. - */ - CANONICALIZE_FIELD_NAMES(true), - - /** - * Feature that determines what happens if we encounter a case in symbol - * handling where number of hash collisions exceeds a safety threshold - * -- which almost certainly means a denial-of-service attack via generated - * duplicate hash codes. - * If feature is enabled, an {@link IllegalStateException} is - * thrown to indicate the suspected denial-of-service attack; if disabled, processing continues but - * canonicalization (and thereby intern()ing) is disabled) as protective - * measure. - *

- * This setting is enabled by default. - * - * @since 2.4 - */ - FAIL_ON_SYMBOL_HASH_OVERFLOW(true), - - /** - * Feature that determines whether we will use {@link BufferRecycler} with - * {@link ThreadLocal} and {@link SoftReference}, for efficient reuse of - * underlying input/output buffers. - * This usually makes sense on normal J2SE/J2EE server-side processing; - * but may not make sense on platforms where {@link SoftReference} handling - * is broken (like Android), or if there are retention issues due to - * {@link ThreadLocal} (see - * Issue #189 - * for a possible case) - *

- * This setting is enabled by default. - * - * @since 2.6 - */ - USE_THREAD_LOCAL_FOR_BUFFER_RECYCLING(true) - - ; - - /** - * Whether feature is enabled or disabled by default. - */ - private final boolean _defaultState; - - /** - * Method that calculates bit set (flags) of all features that - * are enabled by default. - */ - public static int collectDefaults() { - int flags = 0; - for (Feature f : values()) { - if (f.enabledByDefault()) { flags |= f.getMask(); } - } - return flags; - } - - private Feature(boolean defaultState) { _defaultState = defaultState; } - - public boolean enabledByDefault() { return _defaultState; } - public boolean enabledIn(int flags) { return (flags & getMask()) != 0; } - public int getMask() { return (1 << ordinal()); } - } - - /* - /********************************************************** - /* Constants - /********************************************************** - */ - - /** - * Name used to identify JSON format - * (and returned by {@link #getFormatName()} - */ - public final static String FORMAT_NAME_JSON = "JSON"; - - /** - * Bitfield (set of flags) of all factory features that are enabled by default. - */ - protected final static int DEFAULT_FACTORY_FEATURE_FLAGS = JsonFactory.Feature.collectDefaults(); - - /** - * Bitfield (set of flags) of all parser features that are enabled - * by default. - */ - protected final static int DEFAULT_PARSER_FEATURE_FLAGS = JsonParser.Feature.collectDefaults(); - - /** - * Bitfield (set of flags) of all generator features that are enabled - * by default. - */ - protected final static int DEFAULT_GENERATOR_FEATURE_FLAGS = JsonGenerator.Feature.collectDefaults(); - - private final static SerializableString DEFAULT_ROOT_VALUE_SEPARATOR = DefaultPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR; - - /* - /********************************************************** - /* Buffer, symbol table management - /********************************************************** - */ - - /** - * This ThreadLocal contains a {@link java.lang.ref.SoftReference} - * to a {@link BufferRecycler} used to provide a low-cost - * buffer recycling between reader and writer instances. - */ - final protected static ThreadLocal> _recyclerRef - = new ThreadLocal>(); - - /** - * Each factory comes equipped with a shared root symbol table. - * It should not be linked back to the original blueprint, to - * avoid contents from leaking between factories. - */ - protected final transient CharsToNameCanonicalizer _rootCharSymbols = CharsToNameCanonicalizer.createRoot(); - - /** - * Alternative to the basic symbol table, some stream-based - * parsers use different name canonicalization method. - *

- * TODO: should clean up this; looks messy having 2 alternatives - * with not very clear differences. - * - * @since 2.6.0 - */ - protected final transient ByteQuadsCanonicalizer _byteSymbolCanonicalizer = ByteQuadsCanonicalizer.createRoot(); - - /* - /********************************************************** - /* Configuration - /********************************************************** - */ - - /** - * Object that implements conversion functionality between - * Java objects and JSON content. For base JsonFactory implementation - * usually not set by default, but can be explicitly set. - * Sub-classes (like @link org.codehaus.jackson.map.MappingJsonFactory} - * usually provide an implementation. - */ - protected ObjectCodec _objectCodec; - - /** - * Currently enabled factory features. - */ - protected int _factoryFeatures = DEFAULT_FACTORY_FEATURE_FLAGS; - - /** - * Currently enabled parser features. - */ - protected int _parserFeatures = DEFAULT_PARSER_FEATURE_FLAGS; - - /** - * Currently enabled generator features. - */ - protected int _generatorFeatures = DEFAULT_GENERATOR_FEATURE_FLAGS; - - /** - * Definition of custom character escapes to use for generators created - * by this factory, if any. If null, standard data format specific - * escapes are used. - */ - protected CharacterEscapes _characterEscapes; - - /** - * Optional helper object that may decorate input sources, to do - * additional processing on input during parsing. - */ - protected InputDecorator _inputDecorator; - - /** - * Optional helper object that may decorate output object, to do - * additional processing on output during content generation. - */ - protected OutputDecorator _outputDecorator; - - /** - * Separator used between root-level values, if any; null indicates - * "do not add separator". - * Default separator is a single space character. - * - * @since 2.1 - */ - protected SerializableString _rootValueSeparator = DEFAULT_ROOT_VALUE_SEPARATOR; - - /* - /********************************************************** - /* Construction - /********************************************************** - */ - - /** - * Default constructor used to create factory instances. - * Creation of a factory instance is a light-weight operation, - * but it is still a good idea to reuse limited number of - * factory instances (and quite often just a single instance): - * factories are used as context for storing some reused - * processing objects (such as symbol tables parsers use) - * and this reuse only works within context of a single - * factory instance. - */ - public JsonFactory() { this(null); } - - public JsonFactory(ObjectCodec oc) { _objectCodec = oc; } - - /** - * Constructor used when copy()ing a factory instance. - * - * @since 2.2.1 - */ - protected JsonFactory(JsonFactory src, ObjectCodec codec) - { - _objectCodec = null; - _factoryFeatures = src._factoryFeatures; - _parserFeatures = src._parserFeatures; - _generatorFeatures = src._generatorFeatures; - _characterEscapes = src._characterEscapes; - _inputDecorator = src._inputDecorator; - _outputDecorator = src._outputDecorator; - _rootValueSeparator = src._rootValueSeparator; - - /* 27-Apr-2013, tatu: How about symbol table; should we try to - * reuse shared symbol tables? Could be more efficient that way; - * although can slightly add to concurrency overhead. - */ - } - - /** - * Method for constructing a new {@link JsonFactory} that has - * the same settings as this instance, but is otherwise - * independent (i.e. nothing is actually shared, symbol tables - * are separate). - * Note that {@link ObjectCodec} reference is not copied but is - * set to null; caller typically needs to set it after calling - * this method. Reason for this is that the codec is used for - * callbacks, and assumption is that there is strict 1-to-1 - * mapping between codec, factory. Caller has to, then, explicitly - * set codec after making the copy. - * - * @since 2.1 - */ - public JsonFactory copy() - { - _checkInvalidCopy(JsonFactory.class); - // as per above, do clear ObjectCodec - return new JsonFactory(this, null); - } - - /** - * @since 2.1 - * @param exp - */ - protected void _checkInvalidCopy(Class exp) - { - if (getClass() != exp) { - throw new IllegalStateException("Failed copy(): "+getClass().getName() - +" (version: "+version()+") does not override copy(); it has to"); - } - } - - /* - /********************************************************** - /* Serializable overrides - /********************************************************** - */ - - /** - * Method that we need to override to actually make restoration go - * through constructors etc. - * Also: must be overridden by sub-classes as well. - */ - protected Object readResolve() { - return new JsonFactory(this, _objectCodec); - } - - /* - /********************************************************** - /* Capability introspection - /********************************************************** - */ - - /** - * Introspection method that higher-level functionality may call - * to see whether underlying data format requires a stable ordering - * of object properties or not. - * This is usually used for determining - * whether to force a stable ordering (like alphabetic ordering by name) - * if no ordering if explicitly specified. - *

- * Default implementation returns false as JSON does NOT - * require stable ordering. Formats that require ordering include positional - * textual formats like CSV, and schema-based binary formats - * like Avro. - * - * @since 2.3 - */ - public boolean requiresPropertyOrdering() { return false; } - - /** - * Introspection method that higher-level functionality may call - * to see whether underlying data format can read and write binary - * data natively; that is, embeded it as-is without using encodings - * such as Base64. - *

- * Default implementation returns false as JSON does not - * support native access: all binary content must use Base64 encoding. - * Most binary formats (like Smile and Avro) support native binary content. - * - * @since 2.3 - */ - public boolean canHandleBinaryNatively() { return false; } - - /** - * Introspection method that can be used by base factory to check - * whether access using char[] is something that actual - * parser implementations can take advantage of, over having to - * use {@link java.io.Reader}. Sub-types are expected to override - * definition; default implementation (suitable for JSON) alleges - * that optimization are possible; and thereby is likely to try - * to access {@link java.lang.String} content by first copying it into - * recyclable intermediate buffer. - * - * @since 2.4 - */ - public boolean canUseCharArrays() { return true; } - - /** - * Method for accessing kind of {@link FormatFeature} that a parser - * {@link JsonParser} produced by this factory would accept, if any; - * null returned if none. - * - * @since 2.6 - */ - public Class getFormatReadFeatureType() { - return null; - } - - /** - * Method for accessing kind of {@link FormatFeature} that a parser - * {@link JsonGenerator} produced by this factory would accept, if any; - * null returned if none. - * - * @since 2.6 - */ - public Class getFormatWriteFeatureType() { - return null; - } - /* - /********************************************************** - /* Format detection functionality - /********************************************************** - */ - - /** - * Method that can be used to quickly check whether given schema - * is something that parsers and/or generators constructed by this - * factory could use. Note that this means possible use, at the level - * of data format (i.e. schema is for same data format as parsers and - * generators this factory constructs); individual schema instances - * may have further usage restrictions. - * - * @since 2.1 - */ - public boolean canUseSchema(FormatSchema schema) { - if (schema == null){ - return false; - } - String ourFormat = getFormatName(); - return (ourFormat != null) && ourFormat.equals(schema.getSchemaType()); - } - - /** - * Method that returns short textual id identifying format - * this factory supports. - *

- * Note: sub-classes should override this method; default - * implementation will return null for all sub-classes - */ - public String getFormatName() - { - /* Somewhat nasty check: since we can't make this abstract - * (due to backwards compatibility concerns), need to prevent - * format name "leakage" - */ - if (getClass() == JsonFactory.class) { - return FORMAT_NAME_JSON; - } - return null; - } - - /** - * Convenience method for trying to determine whether input via given accessor - * is of format type supported by this factory. - */ - public MatchStrength hasFormat(InputAccessor acc) throws IOException - { - // since we can't keep this abstract, only implement for "vanilla" instance - if (getClass() == JsonFactory.class) { - return hasJSONFormat(acc); - } - return null; - } - - /** - * Method that can be called to determine if a custom - * {@link ObjectCodec} is needed for binding data parsed - * using {@link JsonParser} constructed by this factory - * (which typically also implies the same for serialization - * with {@link JsonGenerator}). - * - * @return True if custom codec is needed with parsers and - * generators created by this factory; false if a general - * {@link ObjectCodec} is enough - * - * @since 2.1 - */ - public boolean requiresCustomCodec() { - return false; - } - - /** - * Helper method that can be called to determine if content accessed - * using given accessor seems to be JSON content. - */ - protected MatchStrength hasJSONFormat(InputAccessor acc) throws IOException - { - return ByteSourceJsonBootstrapper.hasJSONFormat(acc); - } - - /* - /********************************************************** - /* Versioned - /********************************************************** - */ - - @Override - public Version version() { - return Version.unknownVersion(); - } - - /* - /********************************************************** - /* Configuration, factory features - /********************************************************** - */ - - /** - * Method for enabling or disabling specified parser feature - * (check {@link JsonParser.Feature} for list of features) - */ - public final JsonFactory configure(JsonFactory.Feature f, boolean state) { - return state ? enable(f) : disable(f); - } - - /** - * Method for enabling specified parser feature - * (check {@link JsonFactory.Feature} for list of features) - */ - public JsonFactory enable(JsonFactory.Feature f) { - _factoryFeatures |= f.getMask(); - return this; - } - - /** - * Method for disabling specified parser features - * (check {@link JsonFactory.Feature} for list of features) - */ - public JsonFactory disable(JsonFactory.Feature f) { - _factoryFeatures &= ~f.getMask(); - return this; - } - - /** - * Checked whether specified parser feature is enabled. - */ - public final boolean isEnabled(JsonFactory.Feature f) { - return (_factoryFeatures & f.getMask()) != 0; - } - - /* - /********************************************************** - /* Configuration, parser configuration - /********************************************************** - */ - - /** - * Method for enabling or disabling specified parser feature - * (check {@link JsonParser.Feature} for list of features) - */ - public final JsonFactory configure(JsonParser.Feature f, boolean state) { - return state ? enable(f) : disable(f); - } - - /** - * Method for enabling specified parser feature - * (check {@link JsonParser.Feature} for list of features) - */ - public JsonFactory enable(JsonParser.Feature f) { - _parserFeatures |= f.getMask(); - return this; - } - - /** - * Method for disabling specified parser features - * (check {@link JsonParser.Feature} for list of features) - */ - public JsonFactory disable(JsonParser.Feature f) { - _parserFeatures &= ~f.getMask(); - return this; - } - - /** - * Checked whether specified parser feature is enabled. - */ - public final boolean isEnabled(JsonParser.Feature f) { - return (_parserFeatures & f.getMask()) != 0; - } - - /** - * Method for getting currently configured input decorator (if any; - * there is no default decorator). - */ - public InputDecorator getInputDecorator() { - return _inputDecorator; - } - - /** - * Method for overriding currently configured input decorator - */ - public JsonFactory setInputDecorator(InputDecorator d) { - _inputDecorator = d; - return this; - } - - /* - /********************************************************** - /* Configuration, generator settings - /********************************************************** - */ - - /** - * Method for enabling or disabling specified generator feature - * (check {@link JsonGenerator.Feature} for list of features) - */ - public final JsonFactory configure(JsonGenerator.Feature f, boolean state) { - return state ? enable(f) : disable(f); - } - - - /** - * Method for enabling specified generator features - * (check {@link JsonGenerator.Feature} for list of features) - */ - public JsonFactory enable(JsonGenerator.Feature f) { - _generatorFeatures |= f.getMask(); - return this; - } - - /** - * Method for disabling specified generator feature - * (check {@link JsonGenerator.Feature} for list of features) - */ - public JsonFactory disable(JsonGenerator.Feature f) { - _generatorFeatures &= ~f.getMask(); - return this; - } - - /** - * Check whether specified generator feature is enabled. - */ - public final boolean isEnabled(JsonGenerator.Feature f) { - return (_generatorFeatures & f.getMask()) != 0; - } - - /** - * Method for accessing custom escapes factory uses for {@link JsonGenerator}s - * it creates. - */ - public CharacterEscapes getCharacterEscapes() { return _characterEscapes; } - - /** - * Method for defining custom escapes factory uses for {@link JsonGenerator}s - * it creates. - */ - public JsonFactory setCharacterEscapes(CharacterEscapes esc) { - _characterEscapes = esc; - return this; - } - - /** - * Method for getting currently configured output decorator (if any; - * there is no default decorator). - */ - public OutputDecorator getOutputDecorator() { - return _outputDecorator; - } - - /** - * Method for overriding currently configured output decorator - */ - public JsonFactory setOutputDecorator(OutputDecorator d) { - _outputDecorator = d; - return this; - } - - /** - * Method that allows overriding String used for separating root-level - * JSON values (default is single space character) - * - * @param sep Separator to use, if any; null means that no separator is - * automatically added - * - * @since 2.1 - */ - public JsonFactory setRootValueSeparator(String sep) { - _rootValueSeparator = (sep == null) ? null : new SerializedString(sep); - return this; - } - - /** - * @since 2.1 - */ - public String getRootValueSeparator() { - return (_rootValueSeparator == null) ? null : _rootValueSeparator.getValue(); - } - - /* - /********************************************************** - /* Configuration, other - /********************************************************** - */ - - /** - * Method for associating a {@link ObjectCodec} (typically - * a com.fasterxml.jackson.databind.ObjectMapper) - * with this factory (and more importantly, parsers and generators - * it constructs). This is needed to use data-binding methods - * of {@link JsonParser} and {@link JsonGenerator} instances. - */ - public JsonFactory setCodec(ObjectCodec oc) { - _objectCodec = oc; - return this; - } - - public ObjectCodec getCodec() { return _objectCodec; } - - /* - /********************************************************** - /* Parser factories (new ones, as per [Issue-25]) - /********************************************************** - */ - - /** - * Method for constructing JSON parser instance to parse - * contents of specified file. - * - *

- * Encoding is auto-detected from contents according to JSON - * specification recommended mechanism. Json specification - * supports only UTF-8, UTF-16 and UTF-32 as valid encodings, - * so auto-detection implemented only for this charsets. - * For other charsets use {@link #createParser(java.io.Reader)}. - * - *

- * Underlying input stream (needed for reading contents) - * will be owned (and managed, i.e. closed as need be) by - * the parser, since caller has no access to it. - * - * @param f File that contains JSON content to parse - * - * @since 2.1 - */ - public JsonParser createParser(File f) throws IOException, JsonParseException { - // true, since we create InputStream from File - IOContext ctxt = _createContext(f, true); - InputStream in = new FileInputStream(f); - return _createParser(_decorate(in, ctxt), ctxt); - } - - /** - * Method for constructing JSON parser instance to parse - * contents of resource reference by given URL. - * - *

- * Encoding is auto-detected from contents according to JSON - * specification recommended mechanism. Json specification - * supports only UTF-8, UTF-16 and UTF-32 as valid encodings, - * so auto-detection implemented only for this charsets. - * For other charsets use {@link #createParser(java.io.Reader)}. - * - *

- * Underlying input stream (needed for reading contents) - * will be owned (and managed, i.e. closed as need be) by - * the parser, since caller has no access to it. - * - * @param url URL pointing to resource that contains JSON content to parse - * - * @since 2.1 - */ - public JsonParser createParser(URL url) throws IOException, JsonParseException { - // true, since we create InputStream from URL - IOContext ctxt = _createContext(url, true); - InputStream in = _optimizedStreamFromURL(url); - return _createParser(_decorate(in, ctxt), ctxt); - } - - /** - * Method for constructing JSON parser instance to parse - * the contents accessed via specified input stream. - *

- * The input stream will not be owned by - * the parser, it will still be managed (i.e. closed if - * end-of-stream is reacher, or parser close method called) - * if (and only if) {@link autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser.Feature#AUTO_CLOSE_SOURCE} - * is enabled. - *

- * - * Note: no encoding argument is taken since it can always be - * auto-detected as suggested by JSON RFC. Json specification - * supports only UTF-8, UTF-16 and UTF-32 as valid encodings, - * so auto-detection implemented only for this charsets. - * For other charsets use {@link #createParser(java.io.Reader)}. - * - * @param in InputStream to use for reading JSON content to parse - * - * @since 2.1 - */ - public JsonParser createParser(InputStream in) throws IOException, JsonParseException { - IOContext ctxt = _createContext(in, false); - return _createParser(_decorate(in, ctxt), ctxt); - } - - /** - * Method for constructing parser for parsing - * the contents accessed via specified Reader. -

- * The read stream will not be owned by - * the parser, it will still be managed (i.e. closed if - * end-of-stream is reacher, or parser close method called) - * if (and only if) {@link autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser.Feature#AUTO_CLOSE_SOURCE} - * is enabled. - * - * @param r Reader to use for reading JSON content to parse - * - * @since 2.1 - */ - public JsonParser createParser(Reader r) throws IOException, JsonParseException { - // false -> we do NOT own Reader (did not create it) - IOContext ctxt = _createContext(r, false); - return _createParser(_decorate(r, ctxt), ctxt); - } - - /** - * Method for constructing parser for parsing - * the contents of given byte array. - * - * @since 2.1 - */ - public JsonParser createParser(byte[] data) throws IOException, JsonParseException { - IOContext ctxt = _createContext(data, true); - if (_inputDecorator != null) { - InputStream in = _inputDecorator.decorate(ctxt, data, 0, data.length); - if (in != null) { - return _createParser(in, ctxt); - } - } - return _createParser(data, 0, data.length, ctxt); - } - - /** - * Method for constructing parser for parsing - * the contents of given byte array. - * - * @param data Buffer that contains data to parse - * @param offset Offset of the first data byte within buffer - * @param len Length of contents to parse within buffer - * - * @since 2.1 - */ - public JsonParser createParser(byte[] data, int offset, int len) throws IOException, JsonParseException { - IOContext ctxt = _createContext(data, true); - // [JACKSON-512]: allow wrapping with InputDecorator - if (_inputDecorator != null) { - InputStream in = _inputDecorator.decorate(ctxt, data, offset, len); - if (in != null) { - return _createParser(in, ctxt); - } - } - return _createParser(data, offset, len, ctxt); - } - - /** - * Method for constructing parser for parsing - * contents of given String. - * - * @since 2.1 - */ - public JsonParser createParser(String content) throws IOException, JsonParseException { - final int strLen = content.length(); - // Actually, let's use this for medium-sized content, up to 64kB chunk (32kb char) - if ((_inputDecorator != null) || (strLen > 0x8000) || !canUseCharArrays()) { - // easier to just wrap in a Reader than extend InputDecorator; or, if content - // is too long for us to copy it over - return createParser(new StringReader(content)); - } - IOContext ctxt = _createContext(content, true); - char[] buf = ctxt.allocTokenBuffer(strLen); - content.getChars(0, strLen, buf, 0); - return _createParser(buf, 0, strLen, ctxt, true); - } - - /** - * Method for constructing parser for parsing - * contents of given char array. - * - * @since 2.4 - */ - public JsonParser createParser(char[] content) throws IOException { - return createParser(content, 0, content.length); - } - - /** - * Method for constructing parser for parsing contents of given char array. - * - * @since 2.4 - */ - public JsonParser createParser(char[] content, int offset, int len) throws IOException { - if (_inputDecorator != null) { // easier to just wrap in a Reader than extend InputDecorator - return createParser(new CharArrayReader(content, offset, len)); - } - return _createParser(content, offset, len, _createContext(content, true), - // important: buffer is NOT recyclable, as it's from caller - false); - } - - /** - * @since 2.8 - */ - public JsonParser createParser(DataInput in) throws IOException { - IOContext ctxt = _createContext(in, false); - return _createParser(_decorate(in, ctxt), ctxt); - } - - /* - /********************************************************** - /* Parser factories (old ones, pre-2.2) - /********************************************************** - */ - - /** - * Method for constructing JSON parser instance to parse - * contents of specified file. - *

- * Encoding is auto-detected from contents according to JSON - * specification recommended mechanism. Json specification - * supports only UTF-8, UTF-16 and UTF-32 as valid encodings, - * so auto-detection implemented only for this charsets. - * For other charsets use {@link #createParser(java.io.Reader)}. - * - *

- * Underlying input stream (needed for reading contents) - * will be owned (and managed, i.e. closed as need be) by - * the parser, since caller has no access to it. - * - * @param f File that contains JSON content to parse - * - * @deprecated Since 2.2, use {@link #createParser(File)} instead. - */ - @Deprecated - public JsonParser createJsonParser(File f) throws IOException, JsonParseException { - return createParser(f); - } - - /** - * Method for constructing JSON parser instance to parse - * contents of resource reference by given URL. - * - *

- * Encoding is auto-detected from contents according to JSON - * specification recommended mechanism. Json specification - * supports only UTF-8, UTF-16 and UTF-32 as valid encodings, - * so auto-detection implemented only for this charsets. - * For other charsets use {@link #createParser(java.io.Reader)}. - * - *

- * Underlying input stream (needed for reading contents) - * will be owned (and managed, i.e. closed as need be) by - * the parser, since caller has no access to it. - * - * @param url URL pointing to resource that contains JSON content to parse - * - * @deprecated Since 2.2, use {@link #createParser(URL)} instead. - */ - @Deprecated - public JsonParser createJsonParser(URL url) throws IOException, JsonParseException { - return createParser(url); - } - - /** - * Method for constructing JSON parser instance to parse - * the contents accessed via specified input stream. - *

- * The input stream will not be owned by - * the parser, it will still be managed (i.e. closed if - * end-of-stream is reacher, or parser close method called) - * if (and only if) {@link autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser.Feature#AUTO_CLOSE_SOURCE} - * is enabled. - *

- * - * Note: no encoding argument is taken since it can always be - * auto-detected as suggested by JSON RFC. Json specification - * supports only UTF-8, UTF-16 and UTF-32 as valid encodings, - * so auto-detection implemented only for this charsets. - * For other charsets use {@link #createParser(java.io.Reader)}. - * - * @param in InputStream to use for reading JSON content to parse - * - * @deprecated Since 2.2, use {@link #createParser(InputStream)} instead. - */ - @Deprecated - public JsonParser createJsonParser(InputStream in) throws IOException, JsonParseException { - return createParser(in); - } - - /** - * Method for constructing parser for parsing - * the contents accessed via specified Reader. -

- * The read stream will not be owned by - * the parser, it will still be managed (i.e. closed if - * end-of-stream is reacher, or parser close method called) - * if (and only if) {@link autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser.Feature#AUTO_CLOSE_SOURCE} - * is enabled. - * - * @param r Reader to use for reading JSON content to parse - * - * @deprecated Since 2.2, use {@link #createParser(Reader)} instead. - */ - @Deprecated - public JsonParser createJsonParser(Reader r) throws IOException, JsonParseException { - return createParser(r); - } - - /** - * Method for constructing parser for parsing the contents of given byte array. - * - * @deprecated Since 2.2, use {@link #createParser(byte[])} instead. - */ - @Deprecated - public JsonParser createJsonParser(byte[] data) throws IOException, JsonParseException { - return createParser(data); - } - - /** - * Method for constructing parser for parsing - * the contents of given byte array. - * - * @param data Buffer that contains data to parse - * @param offset Offset of the first data byte within buffer - * @param len Length of contents to parse within buffer - * - * @deprecated Since 2.2, use {@link #createParser(byte[],int,int)} instead. - */ - @Deprecated - public JsonParser createJsonParser(byte[] data, int offset, int len) throws IOException, JsonParseException { - return createParser(data, offset, len); - } - - /** - * Method for constructing parser for parsing - * contents of given String. - * - * @deprecated Since 2.2, use {@link #createParser(String)} instead. - */ - @Deprecated - public JsonParser createJsonParser(String content) throws IOException, JsonParseException { - return createParser(content); - } - - /* - /********************************************************** - /* Generator factories, new (as per [Issue-25] - /********************************************************** - */ - - /** - * Method for constructing JSON generator for writing JSON content - * using specified output stream. - * Encoding to use must be specified, and needs to be one of available - * types (as per JSON specification). - *

- * Underlying stream is NOT owned by the generator constructed, - * so that generator will NOT close the output stream when - * {@link JsonGenerator#close} is called (unless auto-closing - * feature, - * {@link autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator.Feature#AUTO_CLOSE_TARGET} - * is enabled). - * Using application needs to close it explicitly if this is the case. - *

- * Note: there are formats that use fixed encoding (like most binary data formats) - * and that ignore passed in encoding. - * - * @param out OutputStream to use for writing JSON content - * @param enc Character encoding to use - * - * @since 2.1 - */ - public JsonGenerator createGenerator(OutputStream out, JsonEncoding enc) - throws IOException - { - // false -> we won't manage the stream unless explicitly directed to - IOContext ctxt = _createContext(out, false); - ctxt.setEncoding(enc); - if (enc == JsonEncoding.UTF8) { - return _createUTF8Generator(_decorate(out, ctxt), ctxt); - } - Writer w = _createWriter(out, enc, ctxt); - return _createGenerator(_decorate(w, ctxt), ctxt); - } - - /** - * Convenience method for constructing generator that uses default - * encoding of the format (UTF-8 for JSON and most other data formats). - *

- * Note: there are formats that use fixed encoding (like most binary data formats). - * - * @since 2.1 - */ - public JsonGenerator createGenerator(OutputStream out) throws IOException { - return createGenerator(out, JsonEncoding.UTF8); - } - - /** - * Method for constructing JSON generator for writing JSON content - * using specified Writer. - *

- * Underlying stream is NOT owned by the generator constructed, - * so that generator will NOT close the Reader when - * {@link JsonGenerator#close} is called (unless auto-closing - * feature, - * {@link autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator.Feature#AUTO_CLOSE_TARGET} is enabled). - * Using application needs to close it explicitly. - * - * @since 2.1 - * - * @param w Writer to use for writing JSON content - */ - public JsonGenerator createGenerator(Writer w) throws IOException { - IOContext ctxt = _createContext(w, false); - return _createGenerator(_decorate(w, ctxt), ctxt); - } - - /** - * Method for constructing JSON generator for writing JSON content - * to specified file, overwriting contents it might have (or creating - * it if such file does not yet exist). - * Encoding to use must be specified, and needs to be one of available - * types (as per JSON specification). - *

- * Underlying stream is owned by the generator constructed, - * i.e. generator will handle closing of file when - * {@link JsonGenerator#close} is called. - * - * @param f File to write contents to - * @param enc Character encoding to use - * - * @since 2.1 - */ - public JsonGenerator createGenerator(File f, JsonEncoding enc) throws IOException - { - OutputStream out = new FileOutputStream(f); - // true -> yes, we have to manage the stream since we created it - IOContext ctxt = _createContext(out, true); - ctxt.setEncoding(enc); - if (enc == JsonEncoding.UTF8) { - return _createUTF8Generator(_decorate(out, ctxt), ctxt); - } - Writer w = _createWriter(out, enc, ctxt); - return _createGenerator(_decorate(w, ctxt), ctxt); - } - - /** - * Method for constructing generator for writing content using specified - * {@link DataOutput} instance. - * - * @since 2.8 - */ - public JsonGenerator createGenerator(DataOutput out, JsonEncoding enc) throws IOException { - return createGenerator(_createDataOutputWrapper(out), enc); - } - - /** - * Convenience method for constructing generator that uses default - * encoding of the format (UTF-8 for JSON and most other data formats). - *

- * Note: there are formats that use fixed encoding (like most binary data formats). - * - * @since 2.8 - */ - public JsonGenerator createGenerator(DataOutput out) throws IOException { - return createGenerator(_createDataOutputWrapper(out), JsonEncoding.UTF8); - } - - /* - /********************************************************** - /* Generator factories, old (pre-2.2) - /********************************************************** - */ - - /** - * Method for constructing JSON generator for writing JSON content - * using specified output stream. - * Encoding to use must be specified, and needs to be one of available - * types (as per JSON specification). - *

- * Underlying stream is NOT owned by the generator constructed, - * so that generator will NOT close the output stream when - * {@link JsonGenerator#close} is called (unless auto-closing - * feature, - * {@link autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator.Feature#AUTO_CLOSE_TARGET} - * is enabled). - * Using application needs to close it explicitly if this is the case. - *

- * Note: there are formats that use fixed encoding (like most binary data formats) - * and that ignore passed in encoding. - * - * @param out OutputStream to use for writing JSON content - * @param enc Character encoding to use - * - * @deprecated Since 2.2, use {@link #createGenerator(OutputStream, JsonEncoding)} instead. - */ - @Deprecated - public JsonGenerator createJsonGenerator(OutputStream out, JsonEncoding enc) throws IOException { - return createGenerator(out, enc); - } - - /** - * Method for constructing JSON generator for writing JSON content - * using specified Writer. - *

- * Underlying stream is NOT owned by the generator constructed, - * so that generator will NOT close the Reader when - * {@link JsonGenerator#close} is called (unless auto-closing - * feature, - * {@link autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator.Feature#AUTO_CLOSE_TARGET} is enabled). - * Using application needs to close it explicitly. - * - * @param out Writer to use for writing JSON content - * - * @deprecated Since 2.2, use {@link #createGenerator(Writer)} instead. - */ - @Deprecated - public JsonGenerator createJsonGenerator(Writer out) throws IOException { - return createGenerator(out); - } - - /** - * Convenience method for constructing generator that uses default - * encoding of the format (UTF-8 for JSON and most other data formats). - *

- * Note: there are formats that use fixed encoding (like most binary data formats). - * - * @deprecated Since 2.2, use {@link #createGenerator(OutputStream)} instead. - */ - @Deprecated - public JsonGenerator createJsonGenerator(OutputStream out) throws IOException { - return createGenerator(out, JsonEncoding.UTF8); - } - - /* - /********************************************************** - /* Factory methods used by factory for creating parser instances, - /* overridable by sub-classes - /********************************************************** - */ - - /** - * Overridable factory method that actually instantiates desired parser - * given {@link InputStream} and context object. - *

- * This method is specifically designed to remain - * compatible between minor versions so that sub-classes can count - * on it being called as expected. That is, it is part of official - * interface from sub-class perspective, although not a public - * method available to users of factory implementations. - * - * @since 2.1 - */ - protected JsonParser _createParser(InputStream in, IOContext ctxt) throws IOException { - // As per [JACKSON-259], may want to fully disable canonicalization: - return new ByteSourceJsonBootstrapper(ctxt, in).constructParser(_parserFeatures, - _objectCodec, _byteSymbolCanonicalizer, _rootCharSymbols, _factoryFeatures); - } - - /** - * Overridable factory method that actually instantiates parser - * using given {@link Reader} object for reading content. - *

- * This method is specifically designed to remain - * compatible between minor versions so that sub-classes can count - * on it being called as expected. That is, it is part of official - * interface from sub-class perspective, although not a public - * method available to users of factory implementations. - * - * @since 2.1 - */ - protected JsonParser _createParser(Reader r, IOContext ctxt) throws IOException { - return new ReaderBasedJsonParser(ctxt, _parserFeatures, r, _objectCodec, - _rootCharSymbols.makeChild(_factoryFeatures)); - } - - /** - * Overridable factory method that actually instantiates parser - * using given char[] object for accessing content. - * - * @since 2.4 - */ - protected JsonParser _createParser(char[] data, int offset, int len, IOContext ctxt, - boolean recyclable) throws IOException { - return new ReaderBasedJsonParser(ctxt, _parserFeatures, null, _objectCodec, - _rootCharSymbols.makeChild(_factoryFeatures), - data, offset, offset+len, recyclable); - } - - /** - * Overridable factory method that actually instantiates parser - * using given {@link Reader} object for reading content - * passed as raw byte array. - *

- * This method is specifically designed to remain - * compatible between minor versions so that sub-classes can count - * on it being called as expected. That is, it is part of official - * interface from sub-class perspective, although not a public - * method available to users of factory implementations. - */ - protected JsonParser _createParser(byte[] data, int offset, int len, IOContext ctxt) throws IOException - { - return new ByteSourceJsonBootstrapper(ctxt, data, offset, len).constructParser(_parserFeatures, - _objectCodec, _byteSymbolCanonicalizer, _rootCharSymbols, _factoryFeatures); - } - - /** - * @since 2.8 - */ - protected JsonParser _createParser(DataInput input, IOContext ctxt) throws IOException - { - // 13-May-2016, tatu: Need to take care not to accidentally create JSON parser for - // non-JSON input. So, bit unclean but... - String format = getFormatName(); - if (format != FORMAT_NAME_JSON) { // NOTE: only ensure override; full equality NOT needed - throw new UnsupportedOperationException(String.format( - "InputData source not (yet?) support for this format (%s)", format)); - } - // Also: while we can't do full bootstrapping (due to read-ahead limitations), should - // at least handle possible UTF-8 BOM - int firstByte = ByteSourceJsonBootstrapper.skipUTF8BOM(input); - ByteQuadsCanonicalizer can = _byteSymbolCanonicalizer.makeChild(_factoryFeatures); - return new UTF8DataInputJsonParser(ctxt, _parserFeatures, input, - _objectCodec, can, firstByte); - } - - /* - /********************************************************** - /* Factory methods used by factory for creating generator instances, - /* overridable by sub-classes - /********************************************************** - */ - - /** - * Overridable factory method that actually instantiates generator for - * given {@link Writer} and context object. - *

- * This method is specifically designed to remain - * compatible between minor versions so that sub-classes can count - * on it being called as expected. That is, it is part of official - * interface from sub-class perspective, although not a public - * method available to users of factory implementations. - */ - protected JsonGenerator _createGenerator(Writer out, IOContext ctxt) throws IOException - { - WriterBasedJsonGenerator gen = new WriterBasedJsonGenerator(ctxt, - _generatorFeatures, _objectCodec, out); - if (_characterEscapes != null) { - gen.setCharacterEscapes(_characterEscapes); - } - SerializableString rootSep = _rootValueSeparator; - if (rootSep != DEFAULT_ROOT_VALUE_SEPARATOR) { - gen.setRootValueSeparator(rootSep); - } - return gen; - } - - /** - * Overridable factory method that actually instantiates generator for - * given {@link OutputStream} and context object, using UTF-8 encoding. - *

- * This method is specifically designed to remain - * compatible between minor versions so that sub-classes can count - * on it being called as expected. That is, it is part of official - * interface from sub-class perspective, although not a public - * method available to users of factory implementations. - */ - protected JsonGenerator _createUTF8Generator(OutputStream out, IOContext ctxt) throws IOException { - UTF8JsonGenerator gen = new UTF8JsonGenerator(ctxt, - _generatorFeatures, _objectCodec, out); - if (_characterEscapes != null) { - gen.setCharacterEscapes(_characterEscapes); - } - SerializableString rootSep = _rootValueSeparator; - if (rootSep != DEFAULT_ROOT_VALUE_SEPARATOR) { - gen.setRootValueSeparator(rootSep); - } - return gen; - } - - protected Writer _createWriter(OutputStream out, JsonEncoding enc, IOContext ctxt) throws IOException - { - // note: this should not get called any more (caller checks, dispatches) - if (enc == JsonEncoding.UTF8) { // We have optimized writer for UTF-8 - return new UTF8Writer(ctxt, out); - } - // not optimal, but should do unless we really care about UTF-16/32 encoding speed - return new OutputStreamWriter(out, enc.getJavaName()); - } - - /* - /********************************************************** - /* Internal factory methods, decorator handling - /********************************************************** - */ - - /** - * @since 2.4 - */ - protected final InputStream _decorate(InputStream in, IOContext ctxt) throws IOException { - if (_inputDecorator != null) { - InputStream in2 = _inputDecorator.decorate(ctxt, in); - if (in2 != null) { - return in2; - } - } - return in; - } - - /** - * @since 2.4 - */ - protected final Reader _decorate(Reader in, IOContext ctxt) throws IOException { - if (_inputDecorator != null) { - Reader in2 = _inputDecorator.decorate(ctxt, in); - if (in2 != null) { - return in2; - } - } - return in; - } - - /** - * @since 2.8 - */ - protected final DataInput _decorate(DataInput in, IOContext ctxt) throws IOException { - if (_inputDecorator != null) { - DataInput in2 = _inputDecorator.decorate(ctxt, in); - if (in2 != null) { - return in2; - } - } - return in; - } - - /** - * @since 2.4 - */ - protected final OutputStream _decorate(OutputStream out, IOContext ctxt) throws IOException { - if (_outputDecorator != null) { - OutputStream out2 = _outputDecorator.decorate(ctxt, out); - if (out2 != null) { - return out2; - } - } - return out; - } - - /** - * @since 2.4 - */ - protected final Writer _decorate(Writer out, IOContext ctxt) throws IOException { - if (_outputDecorator != null) { - Writer out2 = _outputDecorator.decorate(ctxt, out); - if (out2 != null) { - return out2; - } - } - return out; - } - - /* - /********************************************************** - /* Internal factory methods, other - /********************************************************** - */ - - /** - * Method used by factory to create buffer recycler instances - * for parsers and generators. - *

- * Note: only public to give access for ObjectMapper - */ - public BufferRecycler _getBufferRecycler() - { - /* 23-Apr-2015, tatu: Let's allow disabling of buffer recycling - * scheme, for cases where it is considered harmful (possibly - * on Android, for example) - */ - if (isEnabled(Feature.USE_THREAD_LOCAL_FOR_BUFFER_RECYCLING)) { - SoftReference ref = _recyclerRef.get(); - BufferRecycler br = (ref == null) ? null : ref.get(); - - if (br == null) { - br = new BufferRecycler(); - _recyclerRef.set(new SoftReference(br)); - } - return br; - } - return new BufferRecycler(); - } - - /** - * Overridable factory method that actually instantiates desired - * context object. - */ - protected IOContext _createContext(Object srcRef, boolean resourceManaged) { - return new IOContext(_getBufferRecycler(), srcRef, resourceManaged); - } - - /** - * @since 2.8 - */ - protected OutputStream _createDataOutputWrapper(DataOutput out) { - return new DataOutputAsStream(out); - } - - /** - * Helper methods used for constructing an optimal stream for - * parsers to use, when input is to be read from an URL. - * This helps when reading file content via URL. - */ - protected InputStream _optimizedStreamFromURL(URL url) throws IOException { - if ("file".equals(url.getProtocol())) { - /* Can not do this if the path refers - * to a network drive on windows. This fixes the problem; - * might not be needed on all platforms (NFS?), but should not - * matter a lot: performance penalty of extra wrapping is more - * relevant when accessing local file system. - */ - String host = url.getHost(); - if (host == null || host.length() == 0) { - // [core#48]: Let's try to avoid probs with URL encoded stuff - String path = url.getPath(); - if (path.indexOf('%') < 0) { - return new FileInputStream(url.getPath()); - - } - // otherwise, let's fall through and let URL decoder do its magic - } - } - return url.openStream(); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonGenerationException.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonGenerationException.java deleted file mode 100644 index d1026209..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonGenerationException.java +++ /dev/null @@ -1,73 +0,0 @@ -/* Jackson JSON-processor. - * - * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi - */ - -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -/** - * Exception type for exceptions during JSON writing, such as trying - * to output content in wrong context (non-matching end-array or end-object, - * for example). - */ -public class JsonGenerationException - extends JsonProcessingException -{ - private final static long serialVersionUID = 123; // Stupid eclipse... - - // transient since 2.7.4 - protected transient JsonGenerator _processor; - - @Deprecated // since 2.7 - public JsonGenerationException(Throwable rootCause) { - super(rootCause); - } - - @Deprecated // since 2.7 - public JsonGenerationException(String msg) { - super(msg, (JsonLocation)null); - } - - @Deprecated // since 2.7 - public JsonGenerationException(String msg, Throwable rootCause) { - super(msg, null, rootCause); - } - - /** - * @since 2.7 - */ - public JsonGenerationException(Throwable rootCause, JsonGenerator g) { - super(rootCause); - _processor = g; - } - - /** - * @since 2.7 - */ - public JsonGenerationException(String msg, JsonGenerator g) { - super(msg, (JsonLocation) null); - _processor = g; - } - - /** - * @since 2.7 - */ - public JsonGenerationException(String msg, Throwable rootCause, JsonGenerator g) { - super(msg, null, rootCause); - _processor = g; - } - - /** - * Fluent method that may be used to assign originating {@link JsonGenerator}, - * to be accessed using {@link #getProcessor()}. - * - * @since 2.7 - */ - public JsonGenerationException withGenerator(JsonGenerator g) { - _processor = g; - return this; - } - - @Override - public JsonGenerator getProcessor() { return _processor; } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonGenerator.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonGenerator.java deleted file mode 100644 index b4fa8160..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonGenerator.java +++ /dev/null @@ -1,2004 +0,0 @@ -/* Jackson JSON-processor. - * - * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi - */ -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_EMBEDDED_OBJECT; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_END_ARRAY; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_END_OBJECT; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_FALSE; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_FIELD_NAME; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_NOT_AVAILABLE; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_NULL; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_NUMBER_FLOAT; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_NUMBER_INT; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_START_ARRAY; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_START_OBJECT; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_STRING; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_TRUE; - -import java.io.Closeable; -import java.io.Flushable; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Writer; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser.NumberType; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.CharacterEscapes; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.VersionUtil; - -/** - * Base class that defines public API for writing JSON content. - * Instances are created using factory methods of - * a {@link JsonFactory} instance. - * - * @author Tatu Saloranta - */ -public abstract class JsonGenerator - implements Closeable, Flushable, Versioned -{ - /** - * Enumeration that defines all togglable features for generators. - */ - public enum Feature { - // // Low-level I/O / content features - - /** - * Feature that determines whether generator will automatically - * close underlying output target that is NOT owned by the - * generator. - * If disabled, calling application has to separately - * close the underlying {@link OutputStream} and {@link Writer} - * instances used to create the generator. If enabled, generator - * will handle closing, as long as generator itself gets closed: - * this happens when end-of-input is encountered, or generator - * is closed by a call to {@link JsonGenerator#close}. - *

- * Feature is enabled by default. - */ - AUTO_CLOSE_TARGET(true), - - /** - * Feature that determines what happens when the generator is - * closed while there are still unmatched - * {@link JsonToken#START_ARRAY} or {@link JsonToken#START_OBJECT} - * entries in output content. If enabled, such Array(s) and/or - * Object(s) are automatically closed; if disabled, nothing - * specific is done. - *

- * Feature is enabled by default. - */ - AUTO_CLOSE_JSON_CONTENT(true), - - /** - * Feature that specifies that calls to {@link #flush} will cause - * matching flush() to underlying {@link OutputStream} - * or {@link Writer}; if disabled this will not be done. - * Main reason to disable this feature is to prevent flushing at - * generator level, if it is not possible to prevent method being - * called by other code (like ObjectMapper or third - * party libraries). - *

- * Feature is enabled by default. - */ - FLUSH_PASSED_TO_STREAM(true), - - // // Quoting-related features - - /** - * Feature that determines whether JSON Object field names are - * quoted using double-quotes, as specified by JSON specification - * or not. Ability to disable quoting was added to support use - * cases where they are not usually expected, which most commonly - * occurs when used straight from Javascript. - *

- * Feature is enabled by default (since it is required by JSON specification). - */ - QUOTE_FIELD_NAMES(true), - - /** - * Feature that determines whether "exceptional" (not real number) - * float/double values are output as quoted strings. - * The values checked are Double.Nan, - * Double.POSITIVE_INFINITY and Double.NEGATIVE_INIFINTY (and - * associated Float values). - * If feature is disabled, these numbers are still output using - * associated literal values, resulting in non-conformant - * output. - *

- * Feature is enabled by default. - */ - QUOTE_NON_NUMERIC_NUMBERS(true), - - /** - * Feature that forces all Java numbers to be written as JSON strings. - * Default state is 'false', meaning that Java numbers are to - * be serialized using basic numeric serialization (as JSON - * numbers, integral or floating point). If enabled, all such - * numeric values are instead written out as JSON Strings. - *

- * One use case is to avoid problems with Javascript limitations: - * since Javascript standard specifies that all number handling - * should be done using 64-bit IEEE 754 floating point values, - * result being that some 64-bit integer values can not be - * accurately represent (as mantissa is only 51 bit wide). - *

- * Feature is disabled by default. - */ - WRITE_NUMBERS_AS_STRINGS(false), - - /** - * Feature that determines whether {@link java.math.BigDecimal} entries are - * serialized using {@link java.math.BigDecimal#toPlainString()} to prevent - * values to be written using scientific notation. - *

- * Feature is disabled by default, so default output mode is used; this generally - * depends on how {@link BigDecimal} has been created. - * - * @since 2.3 - */ - WRITE_BIGDECIMAL_AS_PLAIN(false), - - /** - * Feature that specifies that all characters beyond 7-bit ASCII - * range (i.e. code points of 128 and above) need to be output - * using format-specific escapes (for JSON, backslash escapes), - * if format uses escaping mechanisms (which is generally true - * for textual formats but not for binary formats). - *

- * Note that this setting may not necessarily make sense for all - * data formats (for example, binary formats typically do not use - * any escaping mechanisms; and some textual formats do not have - * general-purpose escaping); if so, settings is simply ignored. - * Put another way, effects of this feature are data-format specific. - *

- * Feature is disabled by default. - */ - ESCAPE_NON_ASCII(false), - -// 23-Nov-2015, tatu: for [core#223], if and when it gets implemented - /** - * Feature that specifies handling of UTF-8 content that contains - * characters beyond BMP (Basic Multilingual Plane), which are - * represented in UCS-2 (Java internal character encoding) as two - * "surrogate" characters. If feature is enabled, these surrogate - * pairs are separately escaped using backslash escapes; if disabled, - * native output (4-byte UTF-8 sequence, or, with char-backed output - * targets, writing of surrogates as is which is typically converted - * by {@link java.io.Writer} into 4-byte UTF-8 sequence eventually) - * is used. - *

- * Note that the original JSON specification suggests use of escaping; - * but that this is not correct from standard UTF-8 handling perspective. - * Because of two competing goals, this feature was added to allow either - * behavior to be used, but defaulting to UTF-8 specification compliant - * mode. - *

- * Feature is disabled by default. - * - * @since Xxx - */ -// ESCAPE_UTF8_SURROGATES(false), - - // // Schema/Validity support features - - /** - * Feature that determines whether {@link JsonGenerator} will explicitly - * check that no duplicate JSON Object field names are written. - * If enabled, generator will check all names within context and report - * duplicates by throwing a {@link JsonGenerationException}; if disabled, - * no such checking will be done. Assumption in latter case is - * that caller takes care of not trying to write duplicate names. - *

- * Note that enabling this feature will incur performance overhead - * due to having to store and check additional information. - *

- * Feature is disabled by default. - * - * @since 2.3 - */ - STRICT_DUPLICATE_DETECTION(false), - - /** - * Feature that determines what to do if the underlying data format requires knowledge - * of all properties to output, and if no definition is found for a property that - * caller tries to write. If enabled, such properties will be quietly ignored; - * if disabled, a {@link JsonProcessingException} will be thrown to indicate the - * problem. - * Typically most textual data formats do NOT require schema information (although - * some do, such as CSV), whereas many binary data formats do require definitions - * (such as Avro, protobuf), although not all (Smile, CBOR, BSON and MessagePack do not). - *

- * Note that support for this feature is implemented by individual data format - * module, if (and only if) it makes sense for the format in question. For JSON, - * for example, this feature has no effect as properties need not be pre-defined. - *

- * Feature is disabled by default, meaning that if the underlying data format - * requires knowledge of all properties to output, attempts to write an unknown - * property will result in a {@link JsonProcessingException} - * - * @since 2.5 - */ - IGNORE_UNKNOWN(false), - ; - - private final boolean _defaultState; - private final int _mask; - - /** - * Method that calculates bit set (flags) of all features that - * are enabled by default. - */ - public static int collectDefaults() - { - int flags = 0; - for (Feature f : values()) { - if (f.enabledByDefault()) { - flags |= f.getMask(); - } - } - return flags; - } - - private Feature(boolean defaultState) { - _defaultState = defaultState; - _mask = (1 << ordinal()); - } - - public boolean enabledByDefault() { return _defaultState; } - - /** - * @since 2.3 - */ - public boolean enabledIn(int flags) { return (flags & _mask) != 0; } - - public int getMask() { return _mask; } - } - - /* - /********************************************************** - /* Configuration - /********************************************************** - */ - - /** - * Object that handles pretty-printing (usually additional - * white space to make results more human-readable) during - * output. If null, no pretty-printing is done. - */ - protected PrettyPrinter _cfgPrettyPrinter; - - /* - /********************************************************** - /* Construction, initialization - /********************************************************** - */ - - protected JsonGenerator() { } - - /** - * Method that can be called to set or reset the object to - * use for writing Java objects as JsonContent - * (using method {@link #writeObject}). - * - * @return Generator itself (this), to allow chaining - */ - public abstract JsonGenerator setCodec(ObjectCodec oc); - - /** - * Method for accessing the object used for writing Java - * object as JSON content - * (using method {@link #writeObject}). - */ - public abstract ObjectCodec getCodec(); - - /** - * Accessor for finding out version of the bundle that provided this generator instance. - */ - @Override - public abstract Version version(); - - /* - /********************************************************** - /* Public API, Feature configuration - /********************************************************** - */ - - /** - * Method for enabling specified parser features: - * check {@link Feature} for list of available features. - * - * @return Generator itself (this), to allow chaining - */ - public abstract JsonGenerator enable(Feature f); - - /** - * Method for disabling specified features - * (check {@link Feature} for list of features) - * - * @return Generator itself (this), to allow chaining - */ - public abstract JsonGenerator disable(Feature f); - - /** - * Method for enabling or disabling specified feature: - * check {@link Feature} for list of available features. - * - * @return Generator itself (this), to allow chaining - */ - public final JsonGenerator configure(Feature f, boolean state) { - if (state) enable(f); else disable(f); - return this; - } - - /** - * Method for checking whether given feature is enabled. - * Check {@link Feature} for list of available features. - */ - public abstract boolean isEnabled(Feature f); - - /** - * Bulk access method for getting state of all standard (non-dataformat-specific) - * {@link JsonGenerator.Feature}s. - * - * @return Bit mask that defines current states of all standard {@link JsonGenerator.Feature}s. - * - * @since 2.3 - */ - public abstract int getFeatureMask(); - - /** - * Bulk set method for (re)setting states of all standard {@link Feature}s - * - * @since 2.3 - * - * @param values Bitmask that defines which {@link Feature}s are enabled - * and which disabled - * - * @return This parser object, to allow chaining of calls - * - * @deprecated Since 2.7, use {@link #overrideStdFeatures(int, int)} instead -- remove from 2.9 - */ - @Deprecated - public abstract JsonGenerator setFeatureMask(int values); - - /** - * Bulk set method for (re)setting states of features specified by mask. - * Functionally equivalent to - * - * int oldState = getFeatureMask(); - * int newState = (oldState & ~mask) | (values & mask); - * setFeatureMask(newState); - * - * but preferred as this lets caller more efficiently specify actual changes made. - * - * @param values Bit mask of set/clear state for features to change - * @param mask Bit mask of features to change - * - * @since 2.6 - */ - public JsonGenerator overrideStdFeatures(int values, int mask) { - int oldState = getFeatureMask(); - int newState = (oldState & ~mask) | (values & mask); - return setFeatureMask(newState); - } - - /** - * Bulk access method for getting state of all {@link FormatFeature}s, format-specific - * on/off configuration settings. - * - * @return Bit mask that defines current states of all standard {@link FormatFeature}s. - * - * @since 2.6 - */ - public int getFormatFeatures() { - return 0; - } - - /** - * Bulk set method for (re)setting states of {@link FormatFeature}s, - * by specifying values (set / clear) along with a mask, to determine - * which features to change, if any. - *

- * Default implementation will simply throw an exception to indicate that - * the generator implementation does not support any {@link FormatFeature}s. - * - * @param values Bit mask of set/clear state for features to change - * @param mask Bit mask of features to change - * - * @since 2.6 - */ - public JsonGenerator overrideFormatFeatures(int values, int mask) { - throw new IllegalArgumentException("No FormatFeatures defined for generator of type "+getClass().getName()); - /* - int oldState = getFeatureMask(); - int newState = (oldState & ~mask) | (values & mask); - return setFeatureMask(newState); - */ - } - - /* - /********************************************************** - /* Public API, Schema configuration - /********************************************************** - */ - - /** - * Method to call to make this generator use specified schema. - * Method must be called before generating any content, right after instance - * has been created. - * Note that not all generators support schemas; and those that do usually only - * accept specific types of schemas: ones defined for data format this generator - * produces. - *

- * If generator does not support specified schema, {@link UnsupportedOperationException} - * is thrown. - * - * @param schema Schema to use - * - * @throws UnsupportedOperationException if generator does not support schema - */ - public void setSchema(FormatSchema schema) { - throw new UnsupportedOperationException("Generator of type "+getClass().getName()+" does not support schema of type '" - +schema.getSchemaType()+"'"); - } - - /** - * Method for accessing Schema that this parser uses, if any. - * Default implementation returns null. - * - * @since 2.1 - */ - public FormatSchema getSchema() { return null; } - - /* - /********************************************************** - /* Public API, other configuration - /********************************************************** - */ - - /** - * Method for setting a custom pretty printer, which is usually - * used to add indentation for improved human readability. - * By default, generator does not do pretty printing. - *

- * To use the default pretty printer that comes with core - * Jackson distribution, call {@link #useDefaultPrettyPrinter} - * instead. - * - * @return Generator itself (this), to allow chaining - */ - public JsonGenerator setPrettyPrinter(PrettyPrinter pp) { - _cfgPrettyPrinter = pp; - return this; - } - - /** - * Accessor for checking whether this generator has a configured - * {@link PrettyPrinter}; returns it if so, null if none configured. - * - * @since 2.1 - */ - public PrettyPrinter getPrettyPrinter() { - return _cfgPrettyPrinter; - } - - /** - * Convenience method for enabling pretty-printing using - * the default pretty printer - * ({@link autosaveworld.zlibs.com.fasterxml.jackson.core.util.DefaultPrettyPrinter}). - * - * @return Generator itself (this), to allow chaining - */ - public abstract JsonGenerator useDefaultPrettyPrinter(); - - /** - * Method that can be called to request that generator escapes - * all character codes above specified code point (if positive value); - * or, to not escape any characters except for ones that must be - * escaped for the data format (if -1). - * To force escaping of all non-ASCII characters, for example, - * this method would be called with value of 127. - *

- * Note that generators are NOT required to support setting of value - * higher than 127, because there are other ways to affect quoting - * (or lack thereof) of character codes between 0 and 127. - * Not all generators support concept of escaping, either; if so, - * calling this method will have no effect. - *

- * Default implementation does nothing; sub-classes need to redefine - * it according to rules of supported data format. - * - * @param charCode Either -1 to indicate that no additional escaping - * is to be done; or highest code point not to escape (meaning higher - * ones will be), if positive value. - */ - public JsonGenerator setHighestNonEscapedChar(int charCode) { return this; } - - /** - * Accessor method for testing what is the highest unescaped character - * configured for this generator. This may be either positive value - * (when escaping configuration has been set and is in effect), or - * 0 to indicate that no additional escaping is in effect. - * Some generators may not support additional escaping: for example, - * generators for binary formats that do not use escaping should - * simply return 0. - * - * @return Currently active limitation for highest non-escaped character, - * if defined; or -1 to indicate no additional escaping is performed. - */ - public int getHighestEscapedChar() { return 0; } - - /** - * Method for accessing custom escapes factory uses for {@link JsonGenerator}s - * it creates. - */ - public CharacterEscapes getCharacterEscapes() { return null; } - - /** - * Method for defining custom escapes factory uses for {@link JsonGenerator}s - * it creates. - *

- * Default implementation does nothing and simply returns this instance. - */ - public JsonGenerator setCharacterEscapes(CharacterEscapes esc) { return this; } - - /** - * Method that allows overriding String used for separating root-level - * JSON values (default is single space character) - *

- * Default implementation throws {@link UnsupportedOperationException}. - * - * @param sep Separator to use, if any; null means that no separator is - * automatically added - * - * @since 2.1 - */ - public JsonGenerator setRootValueSeparator(SerializableString sep) { - throw new UnsupportedOperationException(); - } - - /* - /********************************************************** - /* Public API, output state access - /********************************************************** - */ - - /** - * Method that can be used to get access to object that is used - * as target for generated output; this is usually either - * {@link OutputStream} or {@link Writer}, depending on what - * generator was constructed with. - * Note that returned value may be null in some cases; including - * case where implementation does not want to exposed raw - * source to caller. - * In cases where output has been decorated, object returned here - * is the decorated version; this allows some level of interaction - * between users of generator and decorator object. - *

- * In general use of this accessor should be considered as - * "last effort", i.e. only used if no other mechanism is applicable. - */ - public Object getOutputTarget() { - return null; - } - - /** - * Method for verifying amount of content that is buffered by generator - * but not yet flushed to the underlying target (stream, writer), - * in units (byte, char) that the generator implementation uses for buffering; - * or -1 if this information is not available. - * Unit used is often the same as the unit of underlying target (that is, - * `byte` for {@link java.io.OutputStream}, `char` for {@link java.io.Writer}), - * but may differ if buffering is done before encoding. - * Default JSON-backed implementations do use matching units. - *

- * Note: non-JSON implementations will be retrofitted for 2.6 and beyond; - * please report if you see -1 (missing override) - * - * @return Amount of content buffered in internal units, if amount known and - * accessible; -1 if not accessible. - * - * @since 2.6 - */ - public int getOutputBuffered() { - return -1; - } - - /** - * Helper method, usually equivalent to: - * - * getOutputContext().getCurrentValue(); - * - *

- * Note that "current value" is NOT populated (or used) by Streaming parser; - * it is only used by higher-level data-binding functionality. - * The reason it is included here is that it can be stored and accessed hierarchically, - * and gets passed through data-binding. - * - * @since 2.5 - */ - public Object getCurrentValue() { - JsonStreamContext ctxt = getOutputContext(); - return (ctxt == null) ? null : ctxt.getCurrentValue(); - } - - /** - * Helper method, usually equivalent to: - * - * getOutputContext().setCurrentValue(v); - * - * - * @since 2.5 - */ - public void setCurrentValue(Object v) { - JsonStreamContext ctxt = getOutputContext(); - if (ctxt != null) { - ctxt.setCurrentValue(v); - } - } - - /* - /********************************************************** - /* Public API, capability introspection methods - /********************************************************** - */ - - /** - * Method that can be used to verify that given schema can be used with - * this generator (using {@link #setSchema}). - * - * @param schema Schema to check - * - * @return True if this generator can use given schema; false if not - */ - public boolean canUseSchema(FormatSchema schema) { return false; } - - /** - * Introspection method that may be called to see if the underlying - * data format supports some kind of Object Ids natively (many do not; - * for example, JSON doesn't). - * This method must be called prior to calling - * {@link #writeObjectId} or {@link #writeObjectRef}. - *

- * Default implementation returns false; overridden by data formats - * that do support native Object Ids. Caller is expected to either - * use a non-native notation (explicit property or such), or fail, - * in case it can not use native object ids. - * - * @since 2.3 - */ - public boolean canWriteObjectId() { return false; } - - /** - * Introspection method that may be called to see if the underlying - * data format supports some kind of Type Ids natively (many do not; - * for example, JSON doesn't). - * This method must be called prior to calling - * {@link #writeTypeId}. - *

- * Default implementation returns false; overridden by data formats - * that do support native Type Ids. Caller is expected to either - * use a non-native notation (explicit property or such), or fail, - * in case it can not use native type ids. - * - * @since 2.3 - */ - public boolean canWriteTypeId() { return false; } - - /** - * Introspection method that may be called to see if the underlying - * data format supports "native" binary data; that is, an efficient - * output of binary content without encoding. - *

- * Default implementation returns false; overridden by data formats - * that do support native binary content. - * - * @since 2.3 - */ - public boolean canWriteBinaryNatively() { return false; } - - /** - * Introspection method to call to check whether it is ok to omit - * writing of Object fields or not. Most formats do allow omission, - * but certain positional formats (such as CSV) require output of - * placeholders, even if no real values are to be emitted. - * - * @since 2.3 - */ - public boolean canOmitFields() { return true; } - - /** - * Introspection method to call to check whether it is possible - * to write numbers using {@link #writeNumber(java.lang.String)} - * using possible custom format, or not. Typically textual formats - * allow this (and JSON specifically does), whereas binary formats - * do not allow this (except by writing them as Strings). - * Usual reason for calling this method is to check whether custom - * formatting of numbers may be applied by higher-level code (databinding) - * or not. - * - * @since 2.8 - */ - public boolean canWriteFormattedNumbers() { return false; } - - /* - /********************************************************** - /* Public API, write methods, structural - /********************************************************** - */ - - /** - * Method for writing starting marker of a Array value - * (for JSON this is character '['; plus possible white space decoration - * if pretty-printing is enabled). - *

- * Array values can be written in any context where values - * are allowed: meaning everywhere except for when - * a field name is expected. - */ - public abstract void writeStartArray() throws IOException; - - /** - * Method for writing start marker of an Array value, similar - * to {@link #writeStartArray()}, but also specifying how many - * elements will be written for the array before calling - * {@link #writeEndArray()}. - *

- * Default implementation simply calls {@link #writeStartArray()}. - * - * @param size Number of elements this array will have: actual - * number of values written (before matching call to - * {@link #writeEndArray()} MUST match; generator MAY verify - * this is the case. - * - * @since 2.4 - */ - public void writeStartArray(int size) throws IOException { - writeStartArray(); - } - - /** - * Method for writing closing marker of a JSON Array value - * (character ']'; plus possible white space decoration - * if pretty-printing is enabled). - *

- * Marker can be written if the innermost structured type - * is Array. - */ - public abstract void writeEndArray() throws IOException; - - /** - * Method for writing starting marker of a JSON Object value - * (character '{'; plus possible white space decoration - * if pretty-printing is enabled). - *

- * Object values can be written in any context where values - * are allowed: meaning everywhere except for when - * a field name is expected. - */ - public abstract void writeStartObject() throws IOException; - - /** - * Method for writing starting marker of a JSON Object value - * (character '{'; plus possible white space decoration - * if pretty-printing is enabled), to represent Java given - * as the argument. Argument is offered as metadata, but more - * importantly it should be assigned as the "current value" - * for the Object content that gets constructed and initialized. - *

- * Object values can be written in any context where values - * are allowed: meaning everywhere except for when - * a field name is expected. - * - * @since 2.8. - */ - public void writeStartObject(Object forValue) throws IOException - { - writeStartObject(); - setCurrentValue(forValue); - } - - /** - * Method for writing closing marker of a JSON Object value - * (character '}'; plus possible white space decoration - * if pretty-printing is enabled). - *

- * Marker can be written if the innermost structured type - * is Object, and the last written event was either a - * complete value, or START-OBJECT marker (see JSON specification - * for more details). - */ - public abstract void writeEndObject() throws IOException; - - /** - * Method for writing a field name (JSON String surrounded by - * double quotes: syntactically identical to a JSON String value), - * possibly decorated by white space if pretty-printing is enabled. - *

- * Field names can only be written in Object context (check out - * JSON specification for details), when field name is expected - * (field names alternate with values). - */ - public abstract void writeFieldName(String name) throws IOException; - - /** - * Method similar to {@link #writeFieldName(String)}, main difference - * being that it may perform better as some of processing (such as - * quoting of certain characters, or encoding into external encoding - * if supported by generator) can be done just once and reused for - * later calls. - *

- * Default implementation simple uses unprocessed name container in - * serialized String; implementations are strongly encouraged to make - * use of more efficient methods argument object has. - */ - public abstract void writeFieldName(SerializableString name) throws IOException; - - /** - * Alternative to {@link #writeFieldName(String)} that may be used - * in cases where property key is of numeric type; either where - * underlying format supports such notion (some binary formats do, - * unlike JSON), or for convenient conversion into String presentation. - * Default implementation will simply convert id into String - * and call {@link #writeFieldName(String)}. - * - * @since 2.8 - */ - public void writeFieldId(long id) throws IOException { - writeFieldName(Long.toString(id)); - } - - /* - /********************************************************** - /* Public API, write methods, scalar arrays (2.8) - /********************************************************** - */ - - /** - * Value write method that can be called to write a single - * array (sequence of {@link JsonToken#START_ARRAY}, zero or - * more {@link JsonToken#VALUE_NUMBER_INT}, {@link JsonToken#END_ARRAY}) - * - * @since 2.8 - * - * @param array Array that contains values to write - * @param offset Offset of the first element to write, within array - * @param length Number of elements in array to write, from `offset` to `offset + len - 1` - */ - public void writeArray(int[] array, int offset, int length) throws IOException - { - if (array == null) { - throw new IllegalArgumentException("null array"); - } - _verifyOffsets(array.length, offset, length); - writeStartArray(); - for (int i = offset, end = offset+length; i < end; ++i) { - writeNumber(array[i]); - } - writeEndArray(); - } - - /** - * Value write method that can be called to write a single - * array (sequence of {@link JsonToken#START_ARRAY}, zero or - * more {@link JsonToken#VALUE_NUMBER_INT}, {@link JsonToken#END_ARRAY}) - * - * @since 2.8 - * - * @param array Array that contains values to write - * @param offset Offset of the first element to write, within array - * @param length Number of elements in array to write, from `offset` to `offset + len - 1` - */ - public void writeArray(long[] array, int offset, int length) throws IOException - { - if (array == null) { - throw new IllegalArgumentException("null array"); - } - _verifyOffsets(array.length, offset, length); - writeStartArray(); - for (int i = offset, end = offset+length; i < end; ++i) { - writeNumber(array[i]); - } - writeEndArray(); - } - - /** - * Value write method that can be called to write a single - * array (sequence of {@link JsonToken#START_ARRAY}, zero or - * more {@link JsonToken#VALUE_NUMBER_FLOAT}, {@link JsonToken#END_ARRAY}) - * - * @since 2.8 - * - * @param array Array that contains values to write - * @param offset Offset of the first element to write, within array - * @param length Number of elements in array to write, from `offset` to `offset + len - 1` - */ - public void writeArray(double[] array, int offset, int length) throws IOException - { - if (array == null) { - throw new IllegalArgumentException("null array"); - } - _verifyOffsets(array.length, offset, length); - writeStartArray(); - for (int i = offset, end = offset+length; i < end; ++i) { - writeNumber(array[i]); - } - writeEndArray(); - } - - /* - /********************************************************** - /* Public API, write methods, text/String values - /********************************************************** - */ - - /** - * Method for outputting a String value. Depending on context - * this means either array element, (object) field value or - * a stand alone String; but in all cases, String will be - * surrounded in double quotes, and contents will be properly - * escaped as required by JSON specification. - */ - public abstract void writeString(String text) throws IOException; - - /** - * Method for outputting a String value. Depending on context - * this means either array element, (object) field value or - * a stand alone String; but in all cases, String will be - * surrounded in double quotes, and contents will be properly - * escaped as required by JSON specification. - */ - public abstract void writeString(char[] text, int offset, int len) throws IOException; - - /** - * Method similar to {@link #writeString(String)}, but that takes - * {@link SerializableString} which can make this potentially - * more efficient to call as generator may be able to reuse - * quoted and/or encoded representation. - *

- * Default implementation just calls {@link #writeString(String)}; - * sub-classes should override it with more efficient implementation - * if possible. - */ - public abstract void writeString(SerializableString text) throws IOException; - - /** - * Method similar to {@link #writeString(String)} but that takes as - * its input a UTF-8 encoded String that is to be output as-is, without additional - * escaping (type of which depends on data format; backslashes for JSON). - * However, quoting that data format requires (like double-quotes for JSON) will be added - * around the value if and as necessary. - *

- * Note that some backends may choose not to support this method: for - * example, if underlying destination is a {@link java.io.Writer} - * using this method would require UTF-8 decoding. - * If so, implementation may instead choose to throw a - * {@link UnsupportedOperationException} due to ineffectiveness - * of having to decode input. - */ - public abstract void writeRawUTF8String(byte[] text, int offset, int length) - throws IOException; - - /** - * Method similar to {@link #writeString(String)} but that takes as its input - * a UTF-8 encoded String which has not been escaped using whatever - * escaping scheme data format requires (for JSON that is backslash-escaping - * for control characters and double-quotes; for other formats something else). - * This means that textual JSON backends need to check if value needs - * JSON escaping, but otherwise can just be copied as is to output. - * Also, quoting that data format requires (like double-quotes for JSON) will be added - * around the value if and as necessary. - *

- * Note that some backends may choose not to support this method: for - * example, if underlying destination is a {@link java.io.Writer} - * using this method would require UTF-8 decoding. - * In this case - * generator implementation may instead choose to throw a - * {@link UnsupportedOperationException} due to ineffectiveness - * of having to decode input. - */ - public abstract void writeUTF8String(byte[] text, int offset, int length) - throws IOException; - - /* - /********************************************************** - /* Public API, write methods, binary/raw content - /********************************************************** - */ - - /** - * Method that will force generator to copy - * input text verbatim with no modifications (including - * that no escaping is done and no separators are added even - * if context [array, object] would otherwise require such). - * If such separators are desired, use - * {@link #writeRawValue(String)} instead. - *

- * Note that not all generator implementations necessarily support - * such by-pass methods: those that do not will throw - * {@link UnsupportedOperationException}. - */ - public abstract void writeRaw(String text) throws IOException; - - /** - * Method that will force generator to copy - * input text verbatim with no modifications (including - * that no escaping is done and no separators are added even - * if context [array, object] would otherwise require such). - * If such separators are desired, use - * {@link #writeRawValue(String)} instead. - *

- * Note that not all generator implementations necessarily support - * such by-pass methods: those that do not will throw - * {@link UnsupportedOperationException}. - */ - public abstract void writeRaw(String text, int offset, int len) throws IOException; - - /** - * Method that will force generator to copy - * input text verbatim with no modifications (including - * that no escaping is done and no separators are added even - * if context [array, object] would otherwise require such). - * If such separators are desired, use - * {@link #writeRawValue(String)} instead. - *

- * Note that not all generator implementations necessarily support - * such by-pass methods: those that do not will throw - * {@link UnsupportedOperationException}. - */ - public abstract void writeRaw(char[] text, int offset, int len) throws IOException; - - /** - * Method that will force generator to copy - * input text verbatim with no modifications (including - * that no escaping is done and no separators are added even - * if context [array, object] would otherwise require such). - * If such separators are desired, use - * {@link #writeRawValue(String)} instead. - *

- * Note that not all generator implementations necessarily support - * such by-pass methods: those that do not will throw - * {@link UnsupportedOperationException}. - */ - public abstract void writeRaw(char c) throws IOException; - - /** - * Method that will force generator to copy - * input text verbatim with no modifications (including - * that no escaping is done and no separators are added even - * if context [array, object] would otherwise require such). - * If such separators are desired, use - * {@link #writeRawValue(String)} instead. - *

- * Note that not all generator implementations necessarily support - * such by-pass methods: those that do not will throw - * {@link UnsupportedOperationException}. - *

- * The default implementation delegates to {@link #writeRaw(String)}; - * other backends that support raw inclusion of text are encouraged - * to implement it in more efficient manner (especially if they - * use UTF-8 encoding). - * - * @since 2.1 - */ - public void writeRaw(SerializableString raw) throws IOException { - writeRaw(raw.getValue()); - } - - /** - * Method that will force generator to copy - * input text verbatim without any modifications, but assuming - * it must constitute a single legal JSON value (number, string, - * boolean, null, Array or List). Assuming this, proper separators - * are added if and as needed (comma or colon), and generator - * state updated to reflect this. - */ - public abstract void writeRawValue(String text) throws IOException; - - public abstract void writeRawValue(String text, int offset, int len) throws IOException; - - public abstract void writeRawValue(char[] text, int offset, int len) throws IOException; - - /** - * Method similar to {@link #writeRawValue(String)}, but potentially more - * efficient as it may be able to use pre-encoded content (similar to - * {@link #writeRaw(SerializableString)}. - * - * @since 2.5 - */ - public void writeRawValue(SerializableString raw) throws IOException { - writeRawValue(raw.getValue()); - } - - /** - * Method that will output given chunk of binary data as base64 - * encoded, as a complete String value (surrounded by double quotes). - * This method defaults - *

- * Note: because JSON Strings can not contain unescaped linefeeds, - * if linefeeds are included (as per last argument), they must be - * escaped. This adds overhead for decoding without improving - * readability. - * Alternatively if linefeeds are not included, - * resulting String value may violate the requirement of base64 - * RFC which mandates line-length of 76 characters and use of - * linefeeds. However, all {@link JsonParser} implementations - * are required to accept such "long line base64"; as do - * typical production-level base64 decoders. - * - * @param bv Base64 variant to use: defines details such as - * whether padding is used (and if so, using which character); - * what is the maximum line length before adding linefeed, - * and also the underlying alphabet to use. - */ - public abstract void writeBinary(Base64Variant bv, - byte[] data, int offset, int len) throws IOException; - - /** - * Similar to {@link #writeBinary(Base64Variant,byte[],int,int)}, - * but default to using the Jackson default Base64 variant - * (which is {@link Base64Variants#MIME_NO_LINEFEEDS}). - */ - public void writeBinary(byte[] data, int offset, int len) throws IOException { - writeBinary(Base64Variants.getDefaultVariant(), data, offset, len); - } - - /** - * Similar to {@link #writeBinary(Base64Variant,byte[],int,int)}, - * but assumes default to using the Jackson default Base64 variant - * (which is {@link Base64Variants#MIME_NO_LINEFEEDS}). Also - * assumes that whole byte array is to be output. - */ - public void writeBinary(byte[] data) throws IOException { - writeBinary(Base64Variants.getDefaultVariant(), data, 0, data.length); - } - - /** - * Similar to {@link #writeBinary(Base64Variant,InputStream,int)}, - * but assumes default to using the Jackson default Base64 variant - * (which is {@link Base64Variants#MIME_NO_LINEFEEDS}). - * - * @param data InputStream to use for reading binary data to write. - * Will not be closed after successful write operation - * @param dataLength (optional) number of bytes that will be available; - * or -1 to be indicate it is not known. Note that implementations - * need not support cases where length is not known in advance; this - * depends on underlying data format: JSON output does NOT require length, - * other formats may - */ - public int writeBinary(InputStream data, int dataLength) - throws IOException { - return writeBinary(Base64Variants.getDefaultVariant(), data, dataLength); - } - - /** - * Method similar to {@link #writeBinary(Base64Variant,byte[],int,int)}, - * but where input is provided through a stream, allowing for incremental - * writes without holding the whole input in memory. - * - * @param bv Base64 variant to use - * @param data InputStream to use for reading binary data to write. - * Will not be closed after successful write operation - * @param dataLength (optional) number of bytes that will be available; - * or -1 to be indicate it is not known. - * If a positive length is given, data MUST provide at least - * that many bytes: if not, an exception will be thrown. - * Note that implementations - * need not support cases where length is not known in advance; this - * depends on underlying data format: JSON output does NOT require length, - * other formats may. - * - * @return Number of bytes read from data and written as binary payload - * - * @since 2.1 - */ - public abstract int writeBinary(Base64Variant bv, - InputStream data, int dataLength) throws IOException; - - /* - /********************************************************** - /* Public API, write methods, numeric - /********************************************************** - */ - - /** - * Method for outputting given value as JSON number. - * Can be called in any context where a value is expected - * (Array value, Object field value, root-level value). - * Additional white space may be added around the value - * if pretty-printing is enabled. - * - * @param v Number value to write - * - * @since 2.2 - */ - public void writeNumber(short v) throws IOException { writeNumber((int) v); } - - /** - * Method for outputting given value as JSON number. - * Can be called in any context where a value is expected - * (Array value, Object field value, root-level value). - * Additional white space may be added around the value - * if pretty-printing is enabled. - * - * @param v Number value to write - */ - public abstract void writeNumber(int v) throws IOException; - - /** - * Method for outputting given value as JSON number. - * Can be called in any context where a value is expected - * (Array value, Object field value, root-level value). - * Additional white space may be added around the value - * if pretty-printing is enabled. - * - * @param v Number value to write - */ - public abstract void writeNumber(long v) throws IOException; - - /** - * Method for outputting given value as JSON number. - * Can be called in any context where a value is expected - * (Array value, Object field value, root-level value). - * Additional white space may be added around the value - * if pretty-printing is enabled. - * - * @param v Number value to write - */ - public abstract void writeNumber(BigInteger v) throws IOException; - - /** - * Method for outputting indicate JSON numeric value. - * Can be called in any context where a value is expected - * (Array value, Object field value, root-level value). - * Additional white space may be added around the value - * if pretty-printing is enabled. - * - * @param v Number value to write - */ - public abstract void writeNumber(double v) throws IOException; - - /** - * Method for outputting indicate JSON numeric value. - * Can be called in any context where a value is expected - * (Array value, Object field value, root-level value). - * Additional white space may be added around the value - * if pretty-printing is enabled. - * - * @param v Number value to write - */ - public abstract void writeNumber(float v) throws IOException; - - /** - * Method for outputting indicate JSON numeric value. - * Can be called in any context where a value is expected - * (Array value, Object field value, root-level value). - * Additional white space may be added around the value - * if pretty-printing is enabled. - * - * @param v Number value to write - */ - public abstract void writeNumber(BigDecimal v) throws IOException; - - /** - * Write method that can be used for custom numeric types that can - * not be (easily?) converted to "standard" Java number types. - * Because numbers are not surrounded by double quotes, regular - * {@link #writeString} method can not be used; nor - * {@link #writeRaw} because that does not properly handle - * value separators needed in Array or Object contexts. - *

- * Note: because of lack of type safety, some generator - * implementations may not be able to implement this - * method. For example, if a binary JSON format is used, - * it may require type information for encoding; similarly - * for generator-wrappers around Java objects or JSON nodes. - * If implementation does not implement this method, - * it needs to throw {@link UnsupportedOperationException}. - * - * @throws UnsupportedOperationException If underlying data format does not - * support numbers serialized textually AND if generator is not allowed - * to just output a String instead (Schema-based formats may require actual - * number, for example) - */ - public abstract void writeNumber(String encodedValue) throws IOException; - - /* - /********************************************************** - /* Public API, write methods, other value types - /********************************************************** - */ - - /** - * Method for outputting literal JSON boolean value (one of - * Strings 'true' and 'false'). - * Can be called in any context where a value is expected - * (Array value, Object field value, root-level value). - * Additional white space may be added around the value - * if pretty-printing is enabled. - */ - public abstract void writeBoolean(boolean state) throws IOException; - - /** - * Method for outputting literal JSON null value. - * Can be called in any context where a value is expected - * (Array value, Object field value, root-level value). - * Additional white space may be added around the value - * if pretty-printing is enabled. - */ - public abstract void writeNull() throws IOException; - - /** - * Method that can be called on backends that support passing opaque datatypes of - * non-JSON formats - * - * @since 2.8 - */ - public void writeEmbeddedObject(Object object) throws IOException { - // 01-Sep-2016, tatu: As per [core#318], handle small number of cases - if (object == null) { - writeNull(); - return; - } - if (object instanceof byte[]) { - writeBinary((byte[]) object); - return; - } - throw new JsonGenerationException("No native support for writing embedded objects of type " - +object.getClass().getName(), - this); - } - - /* - /********************************************************** - /* Public API, write methods, Native Ids (type, object) - /********************************************************** - */ - - /** - * Method that can be called to output so-called native Object Id. - * Note that it may only be called after ensuring this is legal - * (with {@link #canWriteObjectId()}), as not all data formats - * have native type id support; and some may only allow them in - * certain positions or locations. - * If output is not allowed by the data format in this position, - * a {@link JsonGenerationException} will be thrown. - * - * @since 2.3 - */ - public void writeObjectId(Object id) throws IOException { - throw new JsonGenerationException("No native support for writing Object Ids", this); - } - - /** - * Method that can be called to output references to native Object Ids. - * Note that it may only be called after ensuring this is legal - * (with {@link #canWriteObjectId()}), as not all data formats - * have native type id support; and some may only allow them in - * certain positions or locations. - * If output is not allowed by the data format in this position, - * a {@link JsonGenerationException} will be thrown. - */ - public void writeObjectRef(Object id) throws IOException { - throw new JsonGenerationException("No native support for writing Object Ids", this); - } - - /** - * Method that can be called to output so-called native Type Id. - * Note that it may only be called after ensuring this is legal - * (with {@link #canWriteTypeId()}), as not all data formats - * have native type id support; and some may only allow them in - * certain positions or locations. - * If output is not allowed by the data format in this position, - * a {@link JsonGenerationException} will be thrown. - * - * @since 2.3 - */ - public void writeTypeId(Object id) throws IOException { - throw new JsonGenerationException("No native support for writing Type Ids", this); - } - - // 24-May-2016, tatu: Looks like this won't quite make it in 2.8... too - // many open questions on whether return value may be used and such to - // really close the loop. But leaving code sample in, in case we can resolve it - // it for 2.9. - - /* - * Replacement method for {@link #writeTypeId(Object)} which is called - * regardless of whether format has native type ids. If it does have native - * type ids, those are to be used (if configuration allows this), if not, - * structural type id inclusion is to be used. For JSON, for example, no - * native type ids exist and structural inclusion is always used. - *

- * NOTE: from databind perspective, only "as-wrapper-array", "as-wrapper-object" and - * "as-property" inclusion styles call this method; the remaining "as-external-property" - * mechanism always uses writes type id value as simple property. - * - * @param inclStyle Kind of inclusion; {@link JsonToken#START_ARRAY} for "as-wrapper-array", - * {@link JsonToken#START_OBJECT} for "as-wrapper-object" and {@link JsonToken#FIELD_NAME} - * for "as-property" - * @param forValue Java object for which type is being written; not used by standard mechanism - * @param valueShape Expected shape of the value to write, as expressed by the first token (for - * structural type), or any of scalar types for non-structured values (typically - * just {@link JsonToken#VALUE_STRING} -- exact token not required, just the fact it's scalar) - * @param typeId Type id to write - * @param propertyName Name of property to use, in case of "as-property" inclusion style - * - * @since 2.8 - */ - /* - public Object writeTypeSuffix(JsonToken inclStyle, Object forValue, JsonToken valueShape, - String typeId, String propertyName) throws IOException - { - if (inclStyle == JsonToken.FIELD_NAME) { // as-property - if (typeId == null) { // should not include `null` type id in any form with this style - writeStartObject(); - } else if (valueShape == JsonToken.START_OBJECT) { - if (canWriteTypeId()) { - writeTypeId(typeId); - writeStartObject(); - } else { - writeStartObject(); - writeStringField(propertyName, typeId); - } - } else if (valueShape == JsonToken.START_ARRAY) { - if (canWriteTypeId()) { - writeTypeId(typeId); - writeStartArray(); - } else { - writeStartArray(); - writeString(typeId); - } - } else { // any scalar - if (canWriteTypeId()) { - writeTypeId(typeId); - } - } - return JsonToken.END_OBJECT; - } - if (inclStyle == JsonToken.START_ARRAY) { // as-wrapper-array - } else if (inclStyle == JsonToken.START_OBJECT) { // as-wrapper-object - - } else { - throw new JsonGenerationException("Unrecognized inclusion style: "+inclStyle, this); - } - } - */ - - /* - /********************************************************** - /* Public API, write methods, serializing Java objects - /********************************************************** - */ - - /** - * Method for writing given Java object (POJO) as Json. - * Exactly how the object gets written depends on object - * in question (ad on codec, its configuration); for most - * beans it will result in JSON Object, but for others JSON - * Array, or String or numeric value (and for nulls, JSON - * null literal. - * NOTE: generator must have its object codec - * set to non-null value; for generators created by a mapping - * factory this is the case, for others not. - */ - public abstract void writeObject(Object pojo) throws IOException; - - /** - * Method for writing given JSON tree (expressed as a tree - * where given JsonNode is the root) using this generator. - * This will generally just call - * {@link #writeObject} with given node, but is added - * for convenience and to make code more explicit in cases - * where it deals specifically with trees. - */ - public abstract void writeTree(TreeNode rootNode) throws IOException; - - /* - /********************************************************** - /* Public API, convenience field write methods - /********************************************************** - */ - - /** - * Convenience method for outputting a field entry ("member") - * that has a String value. Equivalent to: - *

-     *  writeFieldName(fieldName);
-     *  writeString(value);
-     *
- *

- * Note: many performance-sensitive implementations override this method - */ - public void writeStringField(String fieldName, String value) throws IOException { - writeFieldName(fieldName); - writeString(value); - } - - /** - * Convenience method for outputting a field entry ("member") - * that has a boolean value. Equivalent to: - *

-     *  writeFieldName(fieldName);
-     *  writeBoolean(value);
-     *
- */ - public final void writeBooleanField(String fieldName, boolean value) throws IOException { - writeFieldName(fieldName); - writeBoolean(value); - } - - /** - * Convenience method for outputting a field entry ("member") - * that has JSON literal value null. Equivalent to: - *
-     *  writeFieldName(fieldName);
-     *  writeNull();
-     *
- */ - public final void writeNullField(String fieldName) throws IOException { - writeFieldName(fieldName); - writeNull(); - } - - /** - * Convenience method for outputting a field entry ("member") - * that has the specified numeric value. Equivalent to: - *
-     *  writeFieldName(fieldName);
-     *  writeNumber(value);
-     *
- */ - public final void writeNumberField(String fieldName, int value) throws IOException { - writeFieldName(fieldName); - writeNumber(value); - } - - /** - * Convenience method for outputting a field entry ("member") - * that has the specified numeric value. Equivalent to: - *
-     *  writeFieldName(fieldName);
-     *  writeNumber(value);
-     *
- */ - public final void writeNumberField(String fieldName, long value) throws IOException { - writeFieldName(fieldName); - writeNumber(value); - } - - /** - * Convenience method for outputting a field entry ("member") - * that has the specified numeric value. Equivalent to: - *
-     *  writeFieldName(fieldName);
-     *  writeNumber(value);
-     *
- */ - public final void writeNumberField(String fieldName, double value) throws IOException { - writeFieldName(fieldName); - writeNumber(value); - } - - /** - * Convenience method for outputting a field entry ("member") - * that has the specified numeric value. Equivalent to: - *
-     *  writeFieldName(fieldName);
-     *  writeNumber(value);
-     *
- */ - public final void writeNumberField(String fieldName, float value) throws IOException { - writeFieldName(fieldName); - writeNumber(value); - } - - /** - * Convenience method for outputting a field entry ("member") - * that has the specified numeric value. - * Equivalent to: - *
-     *  writeFieldName(fieldName);
-     *  writeNumber(value);
-     *
- */ - public final void writeNumberField(String fieldName, BigDecimal value) throws IOException { - writeFieldName(fieldName); - writeNumber(value); - } - - /** - * Convenience method for outputting a field entry ("member") - * that contains specified data in base64-encoded form. - * Equivalent to: - *
-     *  writeFieldName(fieldName);
-     *  writeBinary(value);
-     *
- */ - public final void writeBinaryField(String fieldName, byte[] data) throws IOException { - writeFieldName(fieldName); - writeBinary(data); - } - - /** - * Convenience method for outputting a field entry ("member") - * (that will contain a JSON Array value), and the START_ARRAY marker. - * Equivalent to: - *
-     *  writeFieldName(fieldName);
-     *  writeStartArray();
-     *
- *

- * Note: caller still has to take care to close the array - * (by calling {#link #writeEndArray}) after writing all values - * of the value Array. - */ - public final void writeArrayFieldStart(String fieldName) throws IOException { - writeFieldName(fieldName); - writeStartArray(); - } - - /** - * Convenience method for outputting a field entry ("member") - * (that will contain a JSON Object value), and the START_OBJECT marker. - * Equivalent to: - *

-     *  writeFieldName(fieldName);
-     *  writeStartObject();
-     *
- *

- * Note: caller still has to take care to close the Object - * (by calling {#link #writeEndObject}) after writing all - * entries of the value Object. - */ - public final void writeObjectFieldStart(String fieldName) throws IOException { - writeFieldName(fieldName); - writeStartObject(); - } - - /** - * Convenience method for outputting a field entry ("member") - * that has contents of specific Java object as its value. - * Equivalent to: - *

-     *  writeFieldName(fieldName);
-     *  writeObject(pojo);
-     *
- */ - public final void writeObjectField(String fieldName, Object pojo) throws IOException { - writeFieldName(fieldName); - writeObject(pojo); - } - - /** - * Method called to indicate that a property in this position was - * skipped. It is usually only called for generators that return - * false from {@link #canOmitFields()}. - *

- * Default implementation does nothing. - * - * @since 2.3 - */ - public void writeOmittedField(String fieldName) throws IOException { } - - /* - /********************************************************** - /* Public API, copy-through methods - /********************************************************** - */ - - /** - * Method for copying contents of the current event that - * the given parser instance points to. - * Note that the method will not copy any other events, - * such as events contained within JSON Array or Object structures. - *

- * Calling this method will not advance the given - * parser, although it may cause parser to internally process - * more data (if it lazy loads contents of value events, for example) - */ - public void copyCurrentEvent(JsonParser p) throws IOException - { - JsonToken t = p.currentToken(); - // sanity check; what to do? - if (t == null) { - _reportError("No current event to copy"); - } - switch (t.id()) { - case ID_NOT_AVAILABLE: - _reportError("No current event to copy"); - break; // never gets here - case ID_START_OBJECT: - writeStartObject(); - break; - case ID_END_OBJECT: - writeEndObject(); - break; - case ID_START_ARRAY: - writeStartArray(); - break; - case ID_END_ARRAY: - writeEndArray(); - break; - case ID_FIELD_NAME: - writeFieldName(p.getCurrentName()); - break; - case ID_STRING: - if (p.hasTextCharacters()) { - writeString(p.getTextCharacters(), p.getTextOffset(), p.getTextLength()); - } else { - writeString(p.getText()); - } - break; - case ID_NUMBER_INT: - { - NumberType n = p.getNumberType(); - if (n == NumberType.INT) { - writeNumber(p.getIntValue()); - } else if (n == NumberType.BIG_INTEGER) { - writeNumber(p.getBigIntegerValue()); - } else { - writeNumber(p.getLongValue()); - } - break; - } - case ID_NUMBER_FLOAT: - { - NumberType n = p.getNumberType(); - if (n == NumberType.BIG_DECIMAL) { - writeNumber(p.getDecimalValue()); - } else if (n == NumberType.FLOAT) { - writeNumber(p.getFloatValue()); - } else { - writeNumber(p.getDoubleValue()); - } - break; - } - case ID_TRUE: - writeBoolean(true); - break; - case ID_FALSE: - writeBoolean(false); - break; - case ID_NULL: - writeNull(); - break; - case ID_EMBEDDED_OBJECT: - writeObject(p.getEmbeddedObject()); - break; - default: - _throwInternal(); - } - } - - /** - * Method for copying contents of the current event - * and following events that it encloses - * the given parser instance points to. - *

- * So what constitutes enclosing? Here is the list of - * events that have associated enclosed events that will - * get copied: - *

    - *
  • {@link JsonToken#START_OBJECT}: - * all events up to and including matching (closing) - * {@link JsonToken#END_OBJECT} will be copied - *
  • - *
  • {@link JsonToken#START_ARRAY} - * all events up to and including matching (closing) - * {@link JsonToken#END_ARRAY} will be copied - *
  • - *
  • {@link JsonToken#FIELD_NAME} the logical value (which - * can consist of a single scalar value; or a sequence of related - * events for structured types (JSON Arrays, Objects)) will - * be copied along with the name itself. So essentially the - * whole field entry (name and value) will be copied. - *
  • - *
- *

- * After calling this method, parser will point to the - * last event that was copied. This will either be - * the event parser already pointed to (if there were no - * enclosed events), or the last enclosed event copied. - */ - public void copyCurrentStructure(JsonParser p) throws IOException - { - JsonToken t = p.currentToken(); - if (t == null) { - _reportError("No current event to copy"); - } - // Let's handle field-name separately first - int id = t.id(); - if (id == ID_FIELD_NAME) { - writeFieldName(p.getCurrentName()); - t = p.nextToken(); - id = t.id(); - // fall-through to copy the associated value - } - switch (id) { - case ID_START_OBJECT: - writeStartObject(); - while (p.nextToken() != JsonToken.END_OBJECT) { - copyCurrentStructure(p); - } - writeEndObject(); - break; - case ID_START_ARRAY: - writeStartArray(); - while (p.nextToken() != JsonToken.END_ARRAY) { - copyCurrentStructure(p); - } - writeEndArray(); - break; - default: - copyCurrentEvent(p); - } - } - - /* - /********************************************************** - /* Public API, context access - /********************************************************** - */ - - /** - * @return Context object that can give information about logical - * position within generated json content. - */ - public abstract JsonStreamContext getOutputContext(); - - /* - /********************************************************** - /* Public API, buffer handling - /********************************************************** - */ - - /** - * Method called to flush any buffered content to the underlying - * target (output stream, writer), and to flush the target itself - * as well. - */ - @Override - public abstract void flush() throws IOException; - - /** - * Method that can be called to determine whether this generator - * is closed or not. If it is closed, no more output can be done. - */ - public abstract boolean isClosed(); - - /* - /********************************************************** - /* Closeable implementation - /********************************************************** - */ - - /** - * Method called to close this generator, so that no more content - * can be written. - *

- * Whether the underlying target (stream, writer) gets closed depends - * on whether this generator either manages the target (i.e. is the - * only one with access to the target -- case if caller passes a - * reference to the resource such as File, but not stream); or - * has feature {@link Feature#AUTO_CLOSE_TARGET} enabled. - * If either of above is true, the target is also closed. Otherwise - * (not managing, feature not enabled), target is not closed. - */ - @Override - public abstract void close() throws IOException; - - /* - /********************************************************** - /* Helper methods for sub-classes - /********************************************************** - */ - - /** - * Helper method used for constructing and throwing - * {@link JsonGenerationException} with given base message. - *

- * Note that sub-classes may override this method to add more detail - * or use a {@link JsonGenerationException} sub-class. - */ - protected void _reportError(String msg) throws JsonGenerationException { - throw new JsonGenerationException(msg, this); - } - - protected final void _throwInternal() { VersionUtil.throwInternal(); } - - protected void _reportUnsupportedOperation() { - throw new UnsupportedOperationException("Operation not supported by generator of type "+getClass().getName()); - } - - /** - * @since 2.8 - */ - protected final void _verifyOffsets(int arrayLength, int offset, int length) - { - if ((offset < 0) || (offset + length) > arrayLength) { - throw new IllegalArgumentException(String.format( - "invalid argument(s) (offset=%d, length=%d) for input array of %d element", - offset, length, arrayLength)); - } - } - - /** - * Helper method to try to call appropriate write method for given - * untyped Object. At this point, no structural conversions should be done, - * only simple basic types are to be coerced as necessary. - * - * @param value Non-null value to write - */ - protected void _writeSimpleObject(Object value) throws IOException - { - /* 31-Dec-2009, tatu: Actually, we could just handle some basic - * types even without codec. This can improve interoperability, - * and specifically help with TokenBuffer. - */ - if (value == null) { - writeNull(); - return; - } - if (value instanceof String) { - writeString((String) value); - return; - } - if (value instanceof Number) { - Number n = (Number) value; - if (n instanceof Integer) { - writeNumber(n.intValue()); - return; - } else if (n instanceof Long) { - writeNumber(n.longValue()); - return; - } else if (n instanceof Double) { - writeNumber(n.doubleValue()); - return; - } else if (n instanceof Float) { - writeNumber(n.floatValue()); - return; - } else if (n instanceof Short) { - writeNumber(n.shortValue()); - return; - } else if (n instanceof Byte) { - writeNumber(n.byteValue()); - return; - } else if (n instanceof BigInteger) { - writeNumber((BigInteger) n); - return; - } else if (n instanceof BigDecimal) { - writeNumber((BigDecimal) n); - return; - - // then Atomic types - } else if (n instanceof AtomicInteger) { - writeNumber(((AtomicInteger) n).get()); - return; - } else if (n instanceof AtomicLong) { - writeNumber(((AtomicLong) n).get()); - return; - } - } else if (value instanceof byte[]) { - writeBinary((byte[]) value); - return; - } else if (value instanceof Boolean) { - writeBoolean((Boolean) value); - return; - } else if (value instanceof AtomicBoolean) { - writeBoolean(((AtomicBoolean) value).get()); - return; - } - throw new IllegalStateException("No ObjectCodec defined for the generator, can only serialize simple wrapper types (type passed " - +value.getClass().getName()+")"); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonLocation.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonLocation.java deleted file mode 100644 index a74af4c4..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonLocation.java +++ /dev/null @@ -1,139 +0,0 @@ -/* Jackson JSON-processor. - * - * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi - */ - -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -/** - * Object that encapsulates Location information used for reporting - * parsing (or potentially generation) errors, as well as current location - * within input streams. - */ -public class JsonLocation - implements java.io.Serializable -{ - private static final long serialVersionUID = 1L; - - /** - * Shared immutable "N/A location" that can be returned to indicate - * that no location information is available - */ - public final static JsonLocation NA = new JsonLocation("N/A", -1L, -1L, -1, -1); - - final long _totalBytes; - final long _totalChars; - - final int _lineNr; - final int _columnNr; - - /** - * Displayable description for input source: file path, URL. - *

- * NOTE: transient since 2.2 so that Location itself is Serializable. - */ - final transient Object _sourceRef; - - public JsonLocation(Object srcRef, long totalChars, int lineNr, int colNr) - { - /* Unfortunately, none of legal encodings are straight single-byte - * encodings. Could determine offset for UTF-16/UTF-32, but the - * most important one is UTF-8... - * so for now, we'll just not report any real byte count - */ - this(srcRef, -1L, totalChars, lineNr, colNr); - } - - public JsonLocation(Object sourceRef, long totalBytes, long totalChars, - int lineNr, int columnNr) - { - _sourceRef = sourceRef; - _totalBytes = totalBytes; - _totalChars = totalChars; - _lineNr = lineNr; - _columnNr = columnNr; - } - - /** - * Reference to the original resource being read, if one available. - * For example, when a parser has been constructed by passing - * a {@link java.io.File} instance, this method would return - * that File. Will return null if no such reference is available, - * for example when {@link java.io.InputStream} was used to - * construct the parser instance. - */ - public Object getSourceRef() { return _sourceRef; } - - /** - * @return Line number of the location (1-based) - */ - public int getLineNr() { return _lineNr; } - - /** - * @return Column number of the location (1-based) - */ - public int getColumnNr() { return _columnNr; } - - /** - * @return Character offset within underlying stream, reader or writer, - * if available; -1 if not. - */ - public long getCharOffset() { return _totalChars; } - - /** - * @return Byte offset within underlying stream, reader or writer, - * if available; -1 if not. - */ - public long getByteOffset() - { - return _totalBytes; - } - - @Override - public String toString() - { - StringBuilder sb = new StringBuilder(80); - sb.append("[Source: "); - if (_sourceRef == null) { - sb.append("UNKNOWN"); - } else { - sb.append(_sourceRef.toString()); - } - sb.append("; line: "); - sb.append(_lineNr); - sb.append(", column: "); - sb.append(_columnNr); - sb.append(']'); - return sb.toString(); - } - - @Override - public int hashCode() - { - int hash = (_sourceRef == null) ? 1 : _sourceRef.hashCode(); - hash ^= _lineNr; - hash += _columnNr; - hash ^= (int) _totalChars; - hash += (int) _totalBytes; - return hash; - } - - @Override - public boolean equals(Object other) - { - if (other == this) return true; - if (other == null) return false; - if (!(other instanceof JsonLocation)) return false; - JsonLocation otherLoc = (JsonLocation) other; - - if (_sourceRef == null) { - if (otherLoc._sourceRef != null) return false; - } else if (!_sourceRef.equals(otherLoc._sourceRef)) return false; - - return (_lineNr == otherLoc._lineNr) - && (_columnNr == otherLoc._columnNr) - && (_totalChars == otherLoc._totalChars) - && (getByteOffset() == otherLoc.getByteOffset()) - ; - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonParseException.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonParseException.java deleted file mode 100644 index 1cf6766b..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonParseException.java +++ /dev/null @@ -1,143 +0,0 @@ -/* Jackson JSON-processor. - * - * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi - */ - -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.RequestPayload; - -/** - * Exception type for parsing problems, used when non-well-formed content - * (content that does not conform to JSON syntax as per specification) - * is encountered. - */ -public class JsonParseException extends JsonProcessingException { - private static final long serialVersionUID = 2L; // 2.7 - - // transient since 2.7.4 - protected transient JsonParser _processor; - - /** - * Optional payload that can be assigned to pass along for error reporting - * or handling purposes. Core streaming parser implementations DO NOT - * initialize this; it is up to using applications and frameworks to - * populate it. - * - * @since 2.8 - */ - protected RequestPayload _requestPayload; - - @Deprecated // since 2.7 - public JsonParseException(String msg, JsonLocation loc) { - super(msg, loc); - } - - @Deprecated // since 2.7 - public JsonParseException(String msg, JsonLocation loc, Throwable root) { - super(msg, loc, root); - } - - /** - * Constructor that uses current parsing location as location, and - * sets processor (accessible via {@link #getProcessor()}) to - * specified parser. - * - * @since 2.7 - */ - public JsonParseException(JsonParser p, String msg) { - super(msg, (p == null) ? null : p.getCurrentLocation()); - _processor = p; - } - - /** - * @since 2.7 - */ - public JsonParseException(JsonParser p, String msg, Throwable root) { - super(msg, (p == null) ? null : p.getCurrentLocation(), root); - _processor = p; - } - - /** - * @since 2.7 - */ - public JsonParseException(JsonParser p, String msg, JsonLocation loc) { - super(msg, loc); - _processor = p; - } - - /** - * @since 2.7 - */ - public JsonParseException(JsonParser p, String msg, JsonLocation loc, Throwable root) { - super(msg, loc, root); - _processor = p; - } - - /** - * Fluent method that may be used to assign originating {@link JsonParser}, - * to be accessed using {@link #getProcessor()}. - *

- * NOTE: `this` instance is modified and no new instance is constructed. - * - * @since 2.7 - */ - public JsonParseException withParser(JsonParser p) { - _processor = p; - return this; - } - - /** - * Fluent method that may be used to assign payload to this exception, - * to let recipient access it for diagnostics purposes. - *

- * NOTE: `this` instance is modified and no new instance is constructed. - * - * @since 2.8 - */ - public JsonParseException withRequestPayload(RequestPayload p) { - _requestPayload = p; - return this; - } - - @Override - public JsonParser getProcessor() { - return _processor; - } - - /** - * Method that may be called to find payload that was being parsed, if - * one was specified for parser that threw this Exception. - * - * @return request body, if payload was specified; `null` otherwise - * - * @since 2.8 - */ - public RequestPayload getRequestPayload() { - return _requestPayload; - } - - /** - * The method returns the String representation of the request payload if - * one was specified for parser that threw this Exception. - * - * @return request body as String, if payload was specified; `null` otherwise - * - * @since 2.8 - */ - public String getRequestPayloadAsString() { - return (_requestPayload != null) ? _requestPayload.toString() : null; - } - - /** - * Overriding the getMessage() to include the request body - */ - @Override - public String getMessage() { - String msg = super.getMessage(); - if (_requestPayload != null) { - msg += "\nRequest payload : " + _requestPayload.toString(); - } - return msg; - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonParser.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonParser.java deleted file mode 100644 index 00f6bc4f..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonParser.java +++ /dev/null @@ -1,1743 +0,0 @@ -/* Jackson JSON-processor. - * - * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi - */ - -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -import java.io.Closeable; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.Iterator; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.type.TypeReference; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.RequestPayload; - -/** - * Base class that defines public API for reading JSON content. - * Instances are created using factory methods of - * a {@link JsonFactory} instance. - * - * @author Tatu Saloranta - */ -public abstract class JsonParser - implements Closeable, Versioned -{ - private final static int MIN_BYTE_I = (int) Byte.MIN_VALUE; - // as per [JACKSON-804], allow range up to and including 255 - private final static int MAX_BYTE_I = (int) 255; - - private final static int MIN_SHORT_I = (int) Short.MIN_VALUE; - private final static int MAX_SHORT_I = (int) Short.MAX_VALUE; - - /** - * Enumeration of possible "native" (optimal) types that can be - * used for numbers. - */ - public enum NumberType { - INT, LONG, BIG_INTEGER, FLOAT, DOUBLE, BIG_DECIMAL - }; - - /** - * Enumeration that defines all on/off features for parsers. - */ - public enum Feature { - - // // // Low-level I/O handling features: - - /** - * Feature that determines whether parser will automatically - * close underlying input source that is NOT owned by the - * parser. If disabled, calling application has to separately - * close the underlying {@link InputStream} and {@link Reader} - * instances used to create the parser. If enabled, parser - * will handle closing, as long as parser itself gets closed: - * this happens when end-of-input is encountered, or parser - * is closed by a call to {@link JsonParser#close}. - *

- * Feature is enabled by default. - */ - AUTO_CLOSE_SOURCE(true), - - // // // Support for non-standard data format constructs - - /** - * Feature that determines whether parser will allow use - * of Java/C++ style comments (both '/'+'*' and - * '//' varieties) within parsed content or not. - *

- * Since JSON specification does not mention comments as legal - * construct, - * this is a non-standard feature; however, in the wild - * this is extensively used. As such, feature is - * disabled by default for parsers and must be - * explicitly enabled. - */ - ALLOW_COMMENTS(false), - - /** - * Feature that determines whether parser will allow use - * of YAML comments, ones starting with '#' and continuing - * until the end of the line. This commenting style is common - * with scripting languages as well. - *

- * Since JSON specification does not mention comments as legal - * construct, - * this is a non-standard feature. As such, feature is - * disabled by default for parsers and must be - * explicitly enabled. - */ - ALLOW_YAML_COMMENTS(false), - - /** - * Feature that determines whether parser will allow use - * of unquoted field names (which is allowed by Javascript, - * but not by JSON specification). - *

- * Since JSON specification requires use of double quotes for - * field names, - * this is a non-standard feature, and as such disabled by default. - */ - ALLOW_UNQUOTED_FIELD_NAMES(false), - - /** - * Feature that determines whether parser will allow use - * of single quotes (apostrophe, character '\'') for - * quoting Strings (names and String values). If so, - * this is in addition to other acceptable markers. - * but not by JSON specification). - *

- * Since JSON specification requires use of double quotes for - * field names, - * this is a non-standard feature, and as such disabled by default. - */ - ALLOW_SINGLE_QUOTES(false), - - /** - * Feature that determines whether parser will allow - * JSON Strings to contain unquoted control characters - * (ASCII characters with value less than 32, including - * tab and line feed characters) or not. - * If feature is set false, an exception is thrown if such a - * character is encountered. - *

- * Since JSON specification requires quoting for all control characters, - * this is a non-standard feature, and as such disabled by default. - */ - ALLOW_UNQUOTED_CONTROL_CHARS(false), - - /** - * Feature that can be enabled to accept quoting of all character - * using backslash quoting mechanism: if not enabled, only characters - * that are explicitly listed by JSON specification can be thus - * escaped (see JSON spec for small list of these characters) - *

- * Since JSON specification requires quoting for all control characters, - * this is a non-standard feature, and as such disabled by default. - */ - ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER(false), - - /** - * Feature that determines whether parser will allow - * JSON integral numbers to start with additional (ignorable) - * zeroes (like: 000001). If enabled, no exception is thrown, and extra - * nulls are silently ignored (and not included in textual representation - * exposed via {@link JsonParser#getText}). - *

- * Since JSON specification does not allow leading zeroes, - * this is a non-standard feature, and as such disabled by default. - */ - ALLOW_NUMERIC_LEADING_ZEROS(false), - - /** - * Feature that allows parser to recognize set of - * "Not-a-Number" (NaN) tokens as legal floating number - * values (similar to how many other data formats and - * programming language source code allows it). - * Specific subset contains values that - * XML Schema - * (see section 3.2.4.1, Lexical Representation) - * allows (tokens are quoted contents, not including quotes): - *

    - *
  • "INF" (for positive infinity), as well as alias of "Infinity" - *
  • "-INF" (for negative infinity), alias "-Infinity" - *
  • "NaN" (for other not-a-numbers, like result of division by zero) - *
- *

- * Since JSON specification does not allow use of such values, - * this is a non-standard feature, and as such disabled by default. - */ - ALLOW_NON_NUMERIC_NUMBERS(false), - - /** - * Feature that determines whether {@link JsonParser} will explicitly - * check that no duplicate JSON Object field names are encountered. - * If enabled, parser will check all names within context and report - * duplicates by throwing a {@link JsonParseException}; if disabled, - * parser will not do such checking. Assumption in latter case is - * that caller takes care of handling duplicates at a higher level: - * data-binding, for example, has features to specify detection to - * be done there. - *

- * Note that enabling this feature will incur performance overhead - * due to having to store and check additional information: this typically - * adds 20-30% to execution time for basic parsing. - * - * @since 2.3 - */ - STRICT_DUPLICATE_DETECTION(false), - - /** - * Feature that determines what to do if the underlying data format requires knowledge - * of all properties to decode (usually via a Schema), and if no definition is - * found for a property that input content contains. - * Typically most textual data formats do NOT require schema information (although - * some do, such as CSV), whereas many binary data formats do require definitions - * (such as Avro, protobuf), although not all (Smile, CBOR, BSON and MessagePack do not). - * Further note that some formats that do require schema information will not be able - * to ignore undefined properties: for example, Avro is fully positional and there is - * no possibility of undefined data. This leaves formats like Protobuf that have identifiers - * that may or may not map; and as such Protobuf format does make use of this feature. - *

- * Note that support for this feature is implemented by individual data format - * module, if (and only if) it makes sense for the format in question. For JSON, - * for example, this feature has no effect as properties need not be pre-defined. - *

- * Feature is disabled by default, meaning that if the underlying data format - * requires knowledge of all properties to output, attempts to read an unknown - * property will result in a {@link JsonProcessingException} - * - * @since 2.6 - */ - IGNORE_UNDEFINED(false), - - /** - * Feature allows the support for "missing" values in a JSON array: missing - * value meaning sequence of two commas, without value in-between but only - * optional white space. - * Enabling this feature will expose "missing" values as {@link JsonToken#VALUE_NULL} - * tokens, which typically become Java nulls in arrays and {@link java.util.Collection} - * in data-binding. - *

- * For example, enabling this feature will represent a JSON array ["value1",,"value3",] - * as ["value1", null, "value3", null] - *

- * Since the JSON specification does not allow missing values this is a non-compliant JSON - * feature and is disabled by default. - * - * @since 2.8 - */ - ALLOW_MISSING_VALUES(false), - - /** - * Feature that determines whether {@link JsonParser} will allow for a single trailing - * comma following the final value (in an Array) or member (in an Object). These commas - * will simply be ignored. - *

- * For example, when this feature is enabled, [true,true,] is equivalent to - * [true, true] and {"a": true,} is equivalent to - * {"a": true}. - *

- * When combined with ALLOW_MISSING_VALUES, this feature takes priority, and - * the final trailing comma in an array declaration does not imply a missing - * (null) value. For example, when both ALLOW_MISSING_VALUES - * and ALLOW_TRAILING_COMMA are enabled, [true,true,] is - * equivalent to [true, true], and [true,true,,] is equivalent to - * [true, true, null]. - *

- * Since the JSON specification does not permit trailing commas, this is a non-standard - * feature, and as such disabled by default. - * - * @since 2.9 - */ - ALLOW_TRAILING_COMMA(false) - ; - - /** - * Whether feature is enabled or disabled by default. - */ - private final boolean _defaultState; - - private final int _mask; - - /** - * Method that calculates bit set (flags) of all features that - * are enabled by default. - */ - public static int collectDefaults() - { - int flags = 0; - for (Feature f : values()) { - if (f.enabledByDefault()) { - flags |= f.getMask(); - } - } - return flags; - } - - private Feature(boolean defaultState) { - _mask = (1 << ordinal()); - _defaultState = defaultState; - } - - public boolean enabledByDefault() { return _defaultState; } - - /** - * @since 2.3 - */ - public boolean enabledIn(int flags) { return (flags & _mask) != 0; } - - public int getMask() { return _mask; } - } - - /* - /********************************************************** - /* Minimal configuration state - /********************************************************** - */ - - /** - * Bit flag composed of bits that indicate which - * {@link autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser.Feature}s - * are enabled. - */ - protected int _features; - - /** - * Optional container that holds the request payload which will be displayed on JSON parsing error. - * - * @since 2.8 - */ - protected transient RequestPayload _requestPayload; - - /* - /********************************************************** - /* Construction, configuration, initialization - /********************************************************** - */ - - protected JsonParser() { } - protected JsonParser(int features) { _features = features; } - - /** - * Accessor for {@link ObjectCodec} associated with this - * parser, if any. Codec is used by {@link #readValueAs(Class)} - * method (and its variants). - */ - public abstract ObjectCodec getCodec(); - - /** - * Setter that allows defining {@link ObjectCodec} associated with this - * parser, if any. Codec is used by {@link #readValueAs(Class)} - * method (and its variants). - */ - public abstract void setCodec(ObjectCodec c); - - /** - * Method that can be used to get access to object that is used - * to access input being parsed; this is usually either - * {@link InputStream} or {@link Reader}, depending on what - * parser was constructed with. - * Note that returned value may be null in some cases; including - * case where parser implementation does not want to exposed raw - * source to caller. - * In cases where input has been decorated, object returned here - * is the decorated version; this allows some level of interaction - * between users of parser and decorator object. - *

- * In general use of this accessor should be considered as - * "last effort", i.e. only used if no other mechanism is applicable. - */ - public Object getInputSource() { return null; } - - /** - * Helper method, usually equivalent to: - * - * getParsingContext().getCurrentValue(); - * - *

- * Note that "current value" is NOT populated (or used) by Streaming parser; - * it is only used by higher-level data-binding functionality. - * The reason it is included here is that it can be stored and accessed hierarchically, - * and gets passed through data-binding. - * - * @since 2.5 - */ - public Object getCurrentValue() { - JsonStreamContext ctxt = getParsingContext(); - return (ctxt == null) ? null : ctxt.getCurrentValue(); - } - - /** - * Helper method, usually equivalent to: - * - * getParsingContext().setCurrentValue(v); - * - * - * @since 2.5 - */ - public void setCurrentValue(Object v) { - JsonStreamContext ctxt = getParsingContext(); - if (ctxt != null) { - ctxt.setCurrentValue(v); - } - } - - /** - * Sets the payload to be passed if {@link JsonParseException} is thrown. - * - * @since 2.8 - */ - public void setRequestPayloadOnError(RequestPayload payload) { - _requestPayload = payload; - } - - /** - * Sets the byte[] request payload and the charset - * - * @since 2.8 - */ - public void setRequestPayloadOnError(byte[] payload, String charset) { - _requestPayload = (payload == null) ? null : new RequestPayload(payload, charset); - } - - /** - * Sets the String request payload - * - * @since 2.8 - */ - public void setRequestPayloadOnError(String payload) { - _requestPayload = (payload == null) ? null : new RequestPayload(payload); - } - - /* - /********************************************************** - /* Format support - /********************************************************** - */ - - /** - * Method to call to make this parser use specified schema. Method must - * be called before trying to parse any content, right after parser instance - * has been created. - * Note that not all parsers support schemas; and those that do usually only - * accept specific types of schemas: ones defined for data format parser can read. - *

- * If parser does not support specified schema, {@link UnsupportedOperationException} - * is thrown. - * - * @param schema Schema to use - * - * @throws UnsupportedOperationException if parser does not support schema - */ - public void setSchema(FormatSchema schema) { - throw new UnsupportedOperationException("Parser of type "+getClass().getName()+" does not support schema of type '" - +schema.getSchemaType()+"'"); - } - - /** - * Method for accessing Schema that this parser uses, if any. - * Default implementation returns null. - * - * @since 2.1 - */ - public FormatSchema getSchema() { return null; } - - /** - * Method that can be used to verify that given schema can be used with - * this parser (using {@link #setSchema}). - * - * @param schema Schema to check - * - * @return True if this parser can use given schema; false if not - */ - public boolean canUseSchema(FormatSchema schema) { return false; } - - /* - /********************************************************** - /* Capability introspection - /********************************************************** - */ - - /** - * Method that can be called to determine if a custom - * {@link ObjectCodec} is needed for binding data parsed - * using {@link JsonParser} constructed by this factory - * (which typically also implies the same for serialization - * with {@link JsonGenerator}). - * - * @return True if custom codec is needed with parsers and - * generators created by this factory; false if a general - * {@link ObjectCodec} is enough - * - * @since 2.1 - */ - public boolean requiresCustomCodec() { return false;} - - /* - /********************************************************** - /* Versioned - /********************************************************** - */ - - /** - * Accessor for getting version of the core package, given a parser instance. - * Left for sub-classes to implement. - */ - @Override - public abstract Version version(); - - /* - /********************************************************** - /* Closeable implementation - /********************************************************** - */ - - /** - * Closes the parser so that no further iteration or data access - * can be made; will also close the underlying input source - * if parser either owns the input source, or feature - * {@link Feature#AUTO_CLOSE_SOURCE} is enabled. - * Whether parser owns the input source depends on factory - * method that was used to construct instance (so check - * {@link autosaveworld.zlibs.com.fasterxml.jackson.core.JsonFactory} for details, - * but the general - * idea is that if caller passes in closable resource (such - * as {@link InputStream} or {@link Reader}) parser does NOT - * own the source; but if it passes a reference (such as - * {@link java.io.File} or {@link java.net.URL} and creates - * stream or reader it does own them. - */ - @Override - public abstract void close() throws IOException; - - /* - /********************************************************** - /* Buffer handling - /********************************************************** - */ - - /** - * Method that can be called to push back any content that - * has been read but not consumed by the parser. This is usually - * done after reading all content of interest using parser. - * Content is released by writing it to given stream if possible; - * if underlying input is byte-based it can released, if not (char-based) - * it can not. - * - * @return -1 if the underlying content source is not byte based - * (that is, input can not be sent to {@link OutputStream}; - * otherwise number of bytes released (0 if there was nothing to release) - * - * @throws IOException if write to stream threw exception - */ - public int releaseBuffered(OutputStream out) throws IOException { - return -1; - } - - /** - * Method that can be called to push back any content that - * has been read but not consumed by the parser. - * This is usually - * done after reading all content of interest using parser. - * Content is released by writing it to given writer if possible; - * if underlying input is char-based it can released, if not (byte-based) - * it can not. - * - * @return -1 if the underlying content source is not char-based - * (that is, input can not be sent to {@link Writer}; - * otherwise number of chars released (0 if there was nothing to release) - * - * @throws IOException if write using Writer threw exception - */ - public int releaseBuffered(Writer w) throws IOException { return -1; } - - /* - /*************************************************** - /* Public API, configuration - /*************************************************** - */ - - /** - * Method for enabling specified parser feature - * (check {@link Feature} for list of features) - */ - public JsonParser enable(Feature f) { - _features |= f.getMask(); - return this; - } - - /** - * Method for disabling specified feature - * (check {@link Feature} for list of features) - */ - public JsonParser disable(Feature f) { - _features &= ~f.getMask(); - return this; - } - - /** - * Method for enabling or disabling specified feature - * (check {@link Feature} for list of features) - */ - public JsonParser configure(Feature f, boolean state) { - if (state) enable(f); else disable(f); - return this; - } - - /** - * Method for checking whether specified {@link Feature} is enabled. - */ - public boolean isEnabled(Feature f) { return f.enabledIn(_features); } - - /** - * Bulk access method for getting state of all standard {@link Feature}s. - * - * @return Bit mask that defines current states of all standard {@link Feature}s. - * - * @since 2.3 - */ - public int getFeatureMask() { return _features; } - - /** - * Bulk set method for (re)setting states of all standard {@link Feature}s - * - * @return This parser object, to allow chaining of calls - * - * @since 2.3 - * - * @deprecated Since 2.7, use {@link #overrideStdFeatures(int, int)} instead - */ - @Deprecated - public JsonParser setFeatureMask(int mask) { - _features = mask; - return this; - } - - /** - * Bulk set method for (re)setting states of features specified by mask. - * Functionally equivalent to - * - * int oldState = getFeatureMask(); - * int newState = (oldState & ~mask) | (values & mask); - * setFeatureMask(newState); - * - * but preferred as this lets caller more efficiently specify actual changes made. - * - * @param values Bit mask of set/clear state for features to change - * @param mask Bit mask of features to change - * - * @since 2.6 - */ - public JsonParser overrideStdFeatures(int values, int mask) { - int newState = (_features & ~mask) | (values & mask); - return setFeatureMask(newState); - } - - /** - * Bulk access method for getting state of all {@link FormatFeature}s, format-specific - * on/off configuration settings. - * - * @return Bit mask that defines current states of all standard {@link FormatFeature}s. - * - * @since 2.6 - */ - public int getFormatFeatures() { - return 0; - } - - /** - * Bulk set method for (re)setting states of {@link FormatFeature}s, - * by specifying values (set / clear) along with a mask, to determine - * which features to change, if any. - *

- * Default implementation will simply throw an exception to indicate that - * the generator implementation does not support any {@link FormatFeature}s. - * - * @param values Bit mask of set/clear state for features to change - * @param mask Bit mask of features to change - * - * @since 2.6 - */ - public JsonParser overrideFormatFeatures(int values, int mask) { - throw new IllegalArgumentException("No FormatFeatures defined for parser of type "+getClass().getName()); - /* - _formatFeatures = (_formatFeatures & ~mask) | (values & mask); - */ - } - - /* - /********************************************************** - /* Public API, traversal - /********************************************************** - */ - - /** - * Main iteration method, which will advance stream enough - * to determine type of the next token, if any. If none - * remaining (stream has no content other than possible - * white space before ending), null will be returned. - * - * @return Next token from the stream, if any found, or null - * to indicate end-of-input - */ - public abstract JsonToken nextToken() throws IOException; - - /** - * Iteration method that will advance stream enough - * to determine type of the next token that is a value type - * (including JSON Array and Object start/end markers). - * Or put another way, nextToken() will be called once, - * and if {@link JsonToken#FIELD_NAME} is returned, another - * time to get the value for the field. - * Method is most useful for iterating over value entries - * of JSON objects; field name will still be available - * by calling {@link #getCurrentName} when parser points to - * the value. - * - * @return Next non-field-name token from the stream, if any found, - * or null to indicate end-of-input (or, for non-blocking - * parsers, {@link JsonToken#NOT_AVAILABLE} if no tokens were - * available yet) - */ - public abstract JsonToken nextValue() throws IOException; - - /** - * Method that fetches next token (as if calling {@link #nextToken}) and - * verifies whether it is {@link JsonToken#FIELD_NAME} with specified name - * and returns result of that comparison. - * It is functionally equivalent to: - *

-     *  return (nextToken() == JsonToken.FIELD_NAME) && str.getValue().equals(getCurrentName());
-     *
- * but may be faster for parser to verify, and can therefore be used if caller - * expects to get such a property name from input next. - * - * @param str Property name to compare next token to (if next token is - * JsonToken.FIELD_NAME) - */ - public boolean nextFieldName(SerializableString str) throws IOException { - return (nextToken() == JsonToken.FIELD_NAME) && str.getValue().equals(getCurrentName()); - } - - /** - * Method that fetches next token (as if calling {@link #nextToken}) and - * verifies whether it is {@link JsonToken#FIELD_NAME}; if it is, - * returns same as {@link #getCurrentName()}, otherwise null. - * - * @since 2.5 - */ - public String nextFieldName() throws IOException { - return (nextToken() == JsonToken.FIELD_NAME) ? getCurrentName() : null; - } - - /** - * Method that fetches next token (as if calling {@link #nextToken}) and - * if it is {@link JsonToken#VALUE_STRING} returns contained String value; - * otherwise returns null. - * It is functionally equivalent to: - *
-     *  return (nextToken() == JsonToken.VALUE_STRING) ? getText() : null;
-     *
- * but may be faster for parser to process, and can therefore be used if caller - * expects to get a String value next from input. - */ - public String nextTextValue() throws IOException { - return (nextToken() == JsonToken.VALUE_STRING) ? getText() : null; - } - - /** - * Method that fetches next token (as if calling {@link #nextToken}) and - * if it is {@link JsonToken#VALUE_NUMBER_INT} returns 32-bit int value; - * otherwise returns specified default value - * It is functionally equivalent to: - *
-     *  return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getIntValue() : defaultValue;
-     *
- * but may be faster for parser to process, and can therefore be used if caller - * expects to get an int value next from input. - */ - public int nextIntValue(int defaultValue) throws IOException { - return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getIntValue() : defaultValue; - } - - /** - * Method that fetches next token (as if calling {@link #nextToken}) and - * if it is {@link JsonToken#VALUE_NUMBER_INT} returns 64-bit long value; - * otherwise returns specified default value - * It is functionally equivalent to: - *
-     *  return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getLongValue() : defaultValue;
-     *
- * but may be faster for parser to process, and can therefore be used if caller - * expects to get a long value next from input. - */ - public long nextLongValue(long defaultValue) throws IOException { - return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getLongValue() : defaultValue; - } - - /** - * Method that fetches next token (as if calling {@link #nextToken}) and - * if it is {@link JsonToken#VALUE_TRUE} or {@link JsonToken#VALUE_FALSE} - * returns matching Boolean value; otherwise return null. - * It is functionally equivalent to: - *
-     *  JsonToken t = nextToken();
-     *  if (t == JsonToken.VALUE_TRUE) return Boolean.TRUE;
-     *  if (t == JsonToken.VALUE_FALSE) return Boolean.FALSE;
-     *  return null;
-     *
- * but may be faster for parser to process, and can therefore be used if caller - * expects to get a Boolean value next from input. - */ - public Boolean nextBooleanValue() throws IOException { - JsonToken t = nextToken(); - if (t == JsonToken.VALUE_TRUE) { return Boolean.TRUE; } - if (t == JsonToken.VALUE_FALSE) { return Boolean.FALSE; } - return null; - } - - /** - * Method that will skip all child tokens of an array or - * object token that the parser currently points to, - * iff stream points to - * {@link JsonToken#START_OBJECT} or {@link JsonToken#START_ARRAY}. - * If not, it will do nothing. - * After skipping, stream will point to matching - * {@link JsonToken#END_OBJECT} or {@link JsonToken#END_ARRAY} - * (possibly skipping nested pairs of START/END OBJECT/ARRAY tokens - * as well as value tokens). - * The idea is that after calling this method, application - * will call {@link #nextToken} to point to the next - * available token, if any. - */ - public abstract JsonParser skipChildren() throws IOException; - - /** - * Method that may be used to force full handling of the current token - * so that even if lazy processing is enabled, the whole contents are - * read for possible retrieval. This is usually used to ensure that - * the token end location is available, as well as token contents - * (similar to what calling, say {@link #getTextCharacters()}, would - * achieve). - *

- * Note that for many dataformat implementations this method - * will not do anything; this is the default implementation unless - * overridden by sub-classes. - * - * @since 2.8 - */ - public void finishToken() throws IOException { - ; // nothing - } - - /** - * Method that can be called to determine whether this parser - * is closed or not. If it is closed, no new tokens can be - * retrieved by calling {@link #nextToken} (and the underlying - * stream may be closed). Closing may be due to an explicit - * call to {@link #close} or because parser has encountered - * end of input. - */ - public abstract boolean isClosed(); - - /* - /********************************************************** - /* Public API, token accessors - /********************************************************** - */ - - /** - * Accessor to find which token parser currently points to, if any; - * null will be returned if none. - * If return value is non-null, data associated with the token - * is available via other accessor methods. - * - * @return Type of the token this parser currently points to, - * if any: null before any tokens have been read, and - * after end-of-input has been encountered, as well as - * if the current token has been explicitly cleared. - * - * @since 2.8 - */ - public JsonToken currentToken() { - return getCurrentToken(); - } - - /** - * Method similar to {@link #getCurrentToken()} but that returns an - * int instead of {@link JsonToken} (enum value). - *

- * Use of int directly is typically more efficient on switch statements, - * so this method may be useful when building low-overhead codecs. - * Note, however, that effect may not be big enough to matter: make sure - * to profile performance before deciding to use this method. - * - * @since 2.8 - * - * @return int matching one of constants from {@link JsonTokenId}. - */ - public int currentTokenId() { - return getCurrentTokenId(); - } - - /** - * Alias for {@link #currentToken()}, will be deprecated in Jackson 2.9 - */ - public abstract JsonToken getCurrentToken(); - - /** - * Alias for {@link #currentTokenId()}, will be deprecated in Jackson 2.9 - */ - public abstract int getCurrentTokenId(); - - /** - * Method for checking whether parser currently points to - * a token (and data for that token is available). - * Equivalent to check for parser.getCurrentToken() != null. - * - * @return True if the parser just returned a valid - * token via {@link #nextToken}; false otherwise (parser - * was just constructed, encountered end-of-input - * and returned null from {@link #nextToken}, or the token - * has been consumed) - */ - public abstract boolean hasCurrentToken(); - - /** - * Method that is functionally equivalent to: - * - * return currentTokenId() == id - * - * but may be more efficiently implemented. - *

- * Note that no traversal or conversion is performed; so in some - * cases calling method like {@link #isExpectedStartArrayToken()} - * is necessary instead. - * - * @since 2.5 - */ - public abstract boolean hasTokenId(int id); - - /** - * Method that is functionally equivalent to: - * - * return currentToken() == t - * - * but may be more efficiently implemented. - *

- * Note that no traversal or conversion is performed; so in some - * cases calling method like {@link #isExpectedStartArrayToken()} - * is necessary instead. - * - * @since 2.6 - */ - public abstract boolean hasToken(JsonToken t); - - /** - * Method that can be called to get the name associated with - * the current token: for {@link JsonToken#FIELD_NAME}s it will - * be the same as what {@link #getText} returns; - * for field values it will be preceding field name; - * and for others (array values, root-level values) null. - */ - public abstract String getCurrentName() throws IOException; - - /** - * Method that can be used to access current parsing context reader - * is in. There are 3 different types: root, array and object contexts, - * with slightly different available information. Contexts are - * hierarchically nested, and can be used for example for figuring - * out part of the input document that correspond to specific - * array or object (for highlighting purposes, or error reporting). - * Contexts can also be used for simple xpath-like matching of - * input, if so desired. - */ - public abstract JsonStreamContext getParsingContext(); - - /** - * Method that return the starting location of the current - * token; that is, position of the first character from input - * that starts the current token. - */ - public abstract JsonLocation getTokenLocation(); - - /** - * Method that returns location of the last processed character; - * usually for error reporting purposes. - */ - public abstract JsonLocation getCurrentLocation(); - - /** - * Specialized accessor that can be used to verify that the current - * token indicates start array (usually meaning that current token - * is {@link JsonToken#START_ARRAY}) when start array is expected. - * For some specialized parsers this can return true for other cases - * as well; this is usually done to emulate arrays in cases underlying - * format is ambiguous (XML, for example, has no format-level difference - * between Objects and Arrays; it just has elements). - *

- * Default implementation is equivalent to: - *

-     *   currentToken() == JsonToken.START_ARRAY
-     *
- * but may be overridden by custom parser implementations. - * - * @return True if the current token can be considered as a - * start-array marker (such {@link JsonToken#START_ARRAY}); - * false if not. - */ - public boolean isExpectedStartArrayToken() { return currentToken() == JsonToken.START_ARRAY; } - - /** - * Similar to {@link #isExpectedStartArrayToken()}, but checks whether stream - * currently points to {@link JsonToken#START_OBJECT}. - * - * @since 2.5 - */ - public boolean isExpectedStartObjectToken() { return currentToken() == JsonToken.START_OBJECT; } - - /* - /********************************************************** - /* Public API, token state overrides - /********************************************************** - */ - - /** - * Method called to "consume" the current token by effectively - * removing it so that {@link #hasCurrentToken} returns false, and - * {@link #getCurrentToken} null). - * Cleared token value can still be accessed by calling - * {@link #getLastClearedToken} (if absolutely needed), but - * usually isn't. - *

- * Method was added to be used by the optional data binder, since - * it has to be able to consume last token used for binding (so that - * it will not be used again). - */ - public abstract void clearCurrentToken(); - - /** - * Method that can be called to get the last token that was - * cleared using {@link #clearCurrentToken}. This is not necessarily - * the latest token read. - * Will return null if no tokens have been cleared, - * or if parser has been closed. - */ - public abstract JsonToken getLastClearedToken(); - - /** - * Method that can be used to change what is considered to be - * the current (field) name. - * May be needed to support non-JSON data formats or unusual binding - * conventions; not needed for typical processing. - *

- * Note that use of this method should only be done as sort of last - * resort, as it is a work-around for regular operation. - * - * @param name Name to use as the current name; may be null. - */ - public abstract void overrideCurrentName(String name); - - /* - /********************************************************** - /* Public API, access to token information, text - /********************************************************** - */ - - /** - * Method for accessing textual representation of the current token; - * if no current token (before first call to {@link #nextToken}, or - * after encountering end-of-input), returns null. - * Method can be called for any token type. - */ - public abstract String getText() throws IOException; - - /** - * Method to read the textual representation of the current token in chunks and - * pass it to the given Writer. - * Conceptually same as calling: - *

-     *  writer.write(parser.getText());
-     *
- * but should typically be more efficient as longer content does need to - * be combined into a single String to return, and write - * can occur directly from intermediate buffers Jackson uses. - * - * @return The number of characters written to the Writer - * - * @since 2.8 - */ - public int getText(Writer writer) throws IOException, UnsupportedOperationException - { - String str = getText(); - if (str == null) { - return 0; - } - writer.write(str); - return str.length(); - } - - /** - * Method similar to {@link #getText}, but that will return - * underlying (unmodifiable) character array that contains - * textual value, instead of constructing a String object - * to contain this information. - * Note, however, that: - *
    - *
  • Textual contents are not guaranteed to start at - * index 0 (rather, call {@link #getTextOffset}) to - * know the actual offset - *
  • - *
  • Length of textual contents may be less than the - * length of returned buffer: call {@link #getTextLength} - * for actual length of returned content. - *
  • - *
- *

- * Note that caller MUST NOT modify the returned - * character array in any way -- doing so may corrupt - * current parser state and render parser instance useless. - *

- * The only reason to call this method (over {@link #getText}) - * is to avoid construction of a String object (which - * will make a copy of contents). - */ - public abstract char[] getTextCharacters() throws IOException; - - /** - * Accessor used with {@link #getTextCharacters}, to know length - * of String stored in returned buffer. - * - * @return Number of characters within buffer returned - * by {@link #getTextCharacters} that are part of - * textual content of the current token. - */ - public abstract int getTextLength() throws IOException; - - /** - * Accessor used with {@link #getTextCharacters}, to know offset - * of the first text content character within buffer. - * - * @return Offset of the first character within buffer returned - * by {@link #getTextCharacters} that is part of - * textual content of the current token. - */ - public abstract int getTextOffset() throws IOException; - - /** - * Method that can be used to determine whether calling of - * {@link #getTextCharacters} would be the most efficient - * way to access textual content for the event parser currently - * points to. - *

- * Default implementation simply returns false since only actual - * implementation class has knowledge of its internal buffering - * state. - * Implementations are strongly encouraged to properly override - * this method, to allow efficient copying of content by other - * code. - * - * @return True if parser currently has character array that can - * be efficiently returned via {@link #getTextCharacters}; false - * means that it may or may not exist - */ - public abstract boolean hasTextCharacters(); - - /* - /********************************************************** - /* Public API, access to token information, numeric - /********************************************************** - */ - - /** - * Generic number value accessor method that will work for - * all kinds of numeric values. It will return the optimal - * (simplest/smallest possible) wrapper object that can - * express the numeric value just parsed. - */ - public abstract Number getNumberValue() throws IOException; - - /** - * If current token is of type - * {@link JsonToken#VALUE_NUMBER_INT} or - * {@link JsonToken#VALUE_NUMBER_FLOAT}, returns - * one of {@link NumberType} constants; otherwise returns null. - */ - public abstract NumberType getNumberType() throws IOException; - - /** - * Numeric accessor that can be called when the current - * token is of type {@link JsonToken#VALUE_NUMBER_INT} and - * it can be expressed as a value of Java byte primitive type. - * It can also be called for {@link JsonToken#VALUE_NUMBER_FLOAT}; - * if so, it is equivalent to calling {@link #getDoubleValue} - * and then casting; except for possible overflow/underflow - * exception. - *

- * Note: if the resulting integer value falls outside range of - * Java byte, a {@link JsonParseException} - * will be thrown to indicate numeric overflow/underflow. - */ - public byte getByteValue() throws IOException { - int value = getIntValue(); - // So far so good: but does it fit? - // [JACKSON-804]: Let's actually allow range of [-128, 255], as those are uniquely mapped - // (instead of just signed range of [-128, 127]) - if (value < MIN_BYTE_I || value > MAX_BYTE_I) { - throw _constructError("Numeric value ("+getText()+") out of range of Java byte"); - } - return (byte) value; - } - - /** - * Numeric accessor that can be called when the current - * token is of type {@link JsonToken#VALUE_NUMBER_INT} and - * it can be expressed as a value of Java short primitive type. - * It can also be called for {@link JsonToken#VALUE_NUMBER_FLOAT}; - * if so, it is equivalent to calling {@link #getDoubleValue} - * and then casting; except for possible overflow/underflow - * exception. - *

- * Note: if the resulting integer value falls outside range of - * Java short, a {@link JsonParseException} - * will be thrown to indicate numeric overflow/underflow. - */ - public short getShortValue() throws IOException - { - int value = getIntValue(); - if (value < MIN_SHORT_I || value > MAX_SHORT_I) { - throw _constructError("Numeric value ("+getText()+") out of range of Java short"); - } - return (short) value; - } - - /** - * Numeric accessor that can be called when the current - * token is of type {@link JsonToken#VALUE_NUMBER_INT} and - * it can be expressed as a value of Java int primitive type. - * It can also be called for {@link JsonToken#VALUE_NUMBER_FLOAT}; - * if so, it is equivalent to calling {@link #getDoubleValue} - * and then casting; except for possible overflow/underflow - * exception. - *

- * Note: if the resulting integer value falls outside range of - * Java int, a {@link JsonParseException} - * may be thrown to indicate numeric overflow/underflow. - */ - public abstract int getIntValue() throws IOException; - - /** - * Numeric accessor that can be called when the current - * token is of type {@link JsonToken#VALUE_NUMBER_INT} and - * it can be expressed as a Java long primitive type. - * It can also be called for {@link JsonToken#VALUE_NUMBER_FLOAT}; - * if so, it is equivalent to calling {@link #getDoubleValue} - * and then casting to int; except for possible overflow/underflow - * exception. - *

- * Note: if the token is an integer, but its value falls - * outside of range of Java long, a {@link JsonParseException} - * may be thrown to indicate numeric overflow/underflow. - */ - public abstract long getLongValue() throws IOException; - - /** - * Numeric accessor that can be called when the current - * token is of type {@link JsonToken#VALUE_NUMBER_INT} and - * it can not be used as a Java long primitive type due to its - * magnitude. - * It can also be called for {@link JsonToken#VALUE_NUMBER_FLOAT}; - * if so, it is equivalent to calling {@link #getDecimalValue} - * and then constructing a {@link BigInteger} from that value. - */ - public abstract BigInteger getBigIntegerValue() throws IOException; - - /** - * Numeric accessor that can be called when the current - * token is of type {@link JsonToken#VALUE_NUMBER_FLOAT} and - * it can be expressed as a Java float primitive type. - * It can also be called for {@link JsonToken#VALUE_NUMBER_INT}; - * if so, it is equivalent to calling {@link #getLongValue} - * and then casting; except for possible overflow/underflow - * exception. - *

- * Note: if the value falls - * outside of range of Java float, a {@link JsonParseException} - * will be thrown to indicate numeric overflow/underflow. - */ - public abstract float getFloatValue() throws IOException; - - /** - * Numeric accessor that can be called when the current - * token is of type {@link JsonToken#VALUE_NUMBER_FLOAT} and - * it can be expressed as a Java double primitive type. - * It can also be called for {@link JsonToken#VALUE_NUMBER_INT}; - * if so, it is equivalent to calling {@link #getLongValue} - * and then casting; except for possible overflow/underflow - * exception. - *

- * Note: if the value falls - * outside of range of Java double, a {@link JsonParseException} - * will be thrown to indicate numeric overflow/underflow. - */ - public abstract double getDoubleValue() throws IOException; - - /** - * Numeric accessor that can be called when the current - * token is of type {@link JsonToken#VALUE_NUMBER_FLOAT} or - * {@link JsonToken#VALUE_NUMBER_INT}. No under/overflow exceptions - * are ever thrown. - */ - public abstract BigDecimal getDecimalValue() throws IOException; - - /* - /********************************************************** - /* Public API, access to token information, other - /********************************************************** - */ - - /** - * Convenience accessor that can be called when the current - * token is {@link JsonToken#VALUE_TRUE} or - * {@link JsonToken#VALUE_FALSE}. - *

- * Note: if the token is not of above-mentioned boolean types, - an integer, but its value falls - * outside of range of Java long, a {@link JsonParseException} - * may be thrown to indicate numeric overflow/underflow. - */ - public boolean getBooleanValue() throws IOException { - JsonToken t = currentToken(); - if (t == JsonToken.VALUE_TRUE) return true; - if (t == JsonToken.VALUE_FALSE) return false; - throw new JsonParseException(this, - String.format("Current token (%s) not of boolean type", t)) - .withRequestPayload(_requestPayload); - } - - /** - * Accessor that can be called if (and only if) the current token - * is {@link JsonToken#VALUE_EMBEDDED_OBJECT}. For other token types, - * null is returned. - *

- * Note: only some specialized parser implementations support - * embedding of objects (usually ones that are facades on top - * of non-streaming sources, such as object trees). One exception - * is access to binary content (whether via base64 encoding or not) - * which typically is accessible using this method, as well as - * {@link #getBinaryValue()}. - */ - public Object getEmbeddedObject() throws IOException { return null; } - - /* - /********************************************************** - /* Public API, access to token information, binary - /********************************************************** - */ - - /** - * Method that can be used to read (and consume -- results - * may not be accessible using other methods after the call) - * base64-encoded binary data - * included in the current textual JSON value. - * It works similar to getting String value via {@link #getText} - * and decoding result (except for decoding part), - * but should be significantly more performant. - *

- * Note that non-decoded textual contents of the current token - * are not guaranteed to be accessible after this method - * is called. Current implementation, for example, clears up - * textual content during decoding. - * Decoded binary content, however, will be retained until - * parser is advanced to the next event. - * - * @param bv Expected variant of base64 encoded - * content (see {@link Base64Variants} for definitions - * of "standard" variants). - * - * @return Decoded binary data - */ - public abstract byte[] getBinaryValue(Base64Variant bv) throws IOException; - - /** - * Convenience alternative to {@link #getBinaryValue(Base64Variant)} - * that defaults to using - * {@link Base64Variants#getDefaultVariant} as the default encoding. - */ - public byte[] getBinaryValue() throws IOException { - return getBinaryValue(Base64Variants.getDefaultVariant()); - } - - /** - * Method that can be used as an alternative to {@link #getBigIntegerValue()}, - * especially when value can be large. The main difference (beyond method - * of returning content using {@link OutputStream} instead of as byte array) - * is that content will NOT remain accessible after method returns: any content - * processed will be consumed and is not buffered in any way. If caller needs - * buffering, it has to implement it. - * - * @param out Output stream to use for passing decoded binary data - * - * @return Number of bytes that were decoded and written via {@link OutputStream} - * - * @since 2.1 - */ - public int readBinaryValue(OutputStream out) throws IOException { - return readBinaryValue(Base64Variants.getDefaultVariant(), out); - } - - /** - * Similar to {@link #readBinaryValue(OutputStream)} but allows explicitly - * specifying base64 variant to use. - * - * @param bv base64 variant to use - * @param out Output stream to use for passing decoded binary data - * - * @return Number of bytes that were decoded and written via {@link OutputStream} - * - * @since 2.1 - */ - public int readBinaryValue(Base64Variant bv, OutputStream out) throws IOException { - _reportUnsupportedOperation(); - return 0; // never gets here - } - - /* - /********************************************************** - /* Public API, access to token information, coercion/conversion - /********************************************************** - */ - - /** - * Method that will try to convert value of current token to a - * int. - * Numbers are coerced using default Java rules; booleans convert to 0 (false) - * and 1 (true), and Strings are parsed using default Java language integer - * parsing rules. - *

- * If representation can not be converted to an int (including structured type - * markers like start/end Object/Array) - * default value of 0 will be returned; no exceptions are thrown. - */ - public int getValueAsInt() throws IOException { - return getValueAsInt(0); - } - - /** - * Method that will try to convert value of current token to a - * int. - * Numbers are coerced using default Java rules; booleans convert to 0 (false) - * and 1 (true), and Strings are parsed using default Java language integer - * parsing rules. - *

- * If representation can not be converted to an int (including structured type - * markers like start/end Object/Array) - * specified def will be returned; no exceptions are thrown. - */ - public int getValueAsInt(int def) throws IOException { return def; } - - /** - * Method that will try to convert value of current token to a - * long. - * Numbers are coerced using default Java rules; booleans convert to 0 (false) - * and 1 (true), and Strings are parsed using default Java language integer - * parsing rules. - *

- * If representation can not be converted to an int (including structured type - * markers like start/end Object/Array) - * default value of 0 will be returned; no exceptions are thrown. - */ - public long getValueAsLong() throws IOException { - return getValueAsLong(0); - } - - /** - * Method that will try to convert value of current token to a - * long. - * Numbers are coerced using default Java rules; booleans convert to 0 (false) - * and 1 (true), and Strings are parsed using default Java language integer - * parsing rules. - *

- * If representation can not be converted to an int (including structured type - * markers like start/end Object/Array) - * specified def will be returned; no exceptions are thrown. - */ - public long getValueAsLong(long def) throws IOException { - return def; - } - - /** - * Method that will try to convert value of current token to a Java - * double. - * Numbers are coerced using default Java rules; booleans convert to 0.0 (false) - * and 1.0 (true), and Strings are parsed using default Java language integer - * parsing rules. - *

- * If representation can not be converted to an int (including structured types - * like Objects and Arrays), - * default value of 0.0 will be returned; no exceptions are thrown. - */ - public double getValueAsDouble() throws IOException { - return getValueAsDouble(0.0); - } - - /** - * Method that will try to convert value of current token to a - * Java double. - * Numbers are coerced using default Java rules; booleans convert to 0.0 (false) - * and 1.0 (true), and Strings are parsed using default Java language integer - * parsing rules. - *

- * If representation can not be converted to an int (including structured types - * like Objects and Arrays), - * specified def will be returned; no exceptions are thrown. - */ - public double getValueAsDouble(double def) throws IOException { - return def; - } - - /** - * Method that will try to convert value of current token to a - * boolean. - * JSON booleans map naturally; integer numbers other than 0 map to true, and - * 0 maps to false - * and Strings 'true' and 'false' map to corresponding values. - *

- * If representation can not be converted to a boolean value (including structured types - * like Objects and Arrays), - * default value of false will be returned; no exceptions are thrown. - */ - public boolean getValueAsBoolean() throws IOException { - return getValueAsBoolean(false); - } - - /** - * Method that will try to convert value of current token to a - * boolean. - * JSON booleans map naturally; integer numbers other than 0 map to true, and - * 0 maps to false - * and Strings 'true' and 'false' map to corresponding values. - *

- * If representation can not be converted to a boolean value (including structured types - * like Objects and Arrays), - * specified def will be returned; no exceptions are thrown. - */ - public boolean getValueAsBoolean(boolean def) throws IOException { - return def; - } - - /** - * Method that will try to convert value of current token to a - * {@link java.lang.String}. - * JSON Strings map naturally; scalar values get converted to - * their textual representation. - * If representation can not be converted to a String value (including structured types - * like Objects and Arrays and null token), default value of - * null will be returned; no exceptions are thrown. - * - * @since 2.1 - */ - public String getValueAsString() throws IOException { - return getValueAsString(null); - } - - /** - * Method that will try to convert value of current token to a - * {@link java.lang.String}. - * JSON Strings map naturally; scalar values get converted to - * their textual representation. - * If representation can not be converted to a String value (including structured types - * like Objects and Arrays and null token), specified default value - * will be returned; no exceptions are thrown. - * - * @since 2.1 - */ - public abstract String getValueAsString(String def) throws IOException; - - /* - /********************************************************** - /* Public API, Native Ids (type, object) - /********************************************************** - */ - - /** - * Introspection method that may be called to see if the underlying - * data format supports some kind of Object Ids natively (many do not; - * for example, JSON doesn't). - *

- * Default implementation returns true; overridden by data formats - * that do support native Object Ids. Caller is expected to either - * use a non-native notation (explicit property or such), or fail, - * in case it can not use native object ids. - * - * @since 2.3 - */ - public boolean canReadObjectId() { return false; } - - /** - * Introspection method that may be called to see if the underlying - * data format supports some kind of Type Ids natively (many do not; - * for example, JSON doesn't). - *

- * Default implementation returns true; overridden by data formats - * that do support native Type Ids. Caller is expected to either - * use a non-native notation (explicit property or such), or fail, - * in case it can not use native type ids. - * - * @since 2.3 - */ - public boolean canReadTypeId() { return false; } - - /** - * Method that can be called to check whether current token - * (one that was just read) has an associated Object id, and if - * so, return it. - * Note that while typically caller should check with {@link #canReadObjectId} - * first, it is not illegal to call this method even if that method returns - * true; but if so, it will return null. This may be used to simplify calling - * code. - *

- * Default implementation will simply return null. - * - * @since 2.3 - */ - public Object getObjectId() throws IOException { return null; } - - /** - * Method that can be called to check whether current token - * (one that was just read) has an associated type id, and if - * so, return it. - * Note that while typically caller should check with {@link #canReadTypeId} - * first, it is not illegal to call this method even if that method returns - * true; but if so, it will return null. This may be used to simplify calling - * code. - *

- * Default implementation will simply return null. - * - * @since 2.3 - */ - public Object getTypeId() throws IOException { return null; } - - /* - /********************************************************** - /* Public API, optional data binding functionality - /********************************************************** - */ - - /** - * Method to deserialize JSON content into a non-container - * type (it can be an array type, however): typically a bean, array - * or a wrapper type (like {@link java.lang.Boolean}). - * Note: method can only be called if the parser has - * an object codec assigned; this is true for parsers constructed - * by MappingJsonFactory (from "jackson-databind" jar) - * but not for {@link JsonFactory} (unless its setCodec - * method has been explicitly called). - *

- * This method may advance the event stream, for structured types - * the current token will be the closing end marker (END_ARRAY, - * END_OBJECT) of the bound structure. For non-structured Json types - * (and for {@link JsonToken#VALUE_EMBEDDED_OBJECT}) - * stream is not advanced. - *

- * Note: this method should NOT be used if the result type is a - * container ({@link java.util.Collection} or {@link java.util.Map}. - * The reason is that due to type erasure, key and value types - * can not be introspected when using this method. - */ - public T readValueAs(Class valueType) throws IOException { - return _codec().readValue(this, valueType); - } - - /** - * Method to deserialize JSON content into a Java type, reference - * to which is passed as argument. Type is passed using so-called - * "super type token" - * and specifically needs to be used if the root type is a - * parameterized (generic) container type. - * Note: method can only be called if the parser has - * an object codec assigned; this is true for parsers constructed - * by MappingJsonFactory (defined in 'jackson-databind' bundle) - * but not for {@link JsonFactory} (unless its setCodec - * method has been explicitly called). - *

- * This method may advance the event stream, for structured types - * the current token will be the closing end marker (END_ARRAY, - * END_OBJECT) of the bound structure. For non-structured Json types - * (and for {@link JsonToken#VALUE_EMBEDDED_OBJECT}) - * stream is not advanced. - */ - @SuppressWarnings("unchecked") - public T readValueAs(TypeReference valueTypeRef) throws IOException { - return (T) _codec().readValue(this, valueTypeRef); - } - - /** - * Method for reading sequence of Objects from parser stream, - * all with same specified value type. - */ - public Iterator readValuesAs(Class valueType) throws IOException { - return _codec().readValues(this, valueType); - } - - /** - * Method for reading sequence of Objects from parser stream, - * all with same specified value type. - */ - public Iterator readValuesAs(TypeReference valueTypeRef) throws IOException { - return _codec().readValues(this, valueTypeRef); - } - - /** - * Method to deserialize JSON content into equivalent "tree model", - * represented by root {@link TreeNode} of resulting model. - * For JSON Arrays it will an array node (with child nodes), - * for objects object node (with child nodes), and for other types - * matching leaf node type. Empty or whitespace documents are null. - * - * @return root of the document, or null if empty or whitespace. - */ - @SuppressWarnings("unchecked") - public T readValueAsTree() throws IOException { - return (T) _codec().readTree(this); - } - - protected ObjectCodec _codec() { - ObjectCodec c = getCodec(); - if (c == null) { - throw new IllegalStateException("No ObjectCodec defined for parser, needed for deserialization"); - } - return c; - } - - /* - /********************************************************** - /* Internal methods - /********************************************************** - */ - - /** - * Helper method for constructing {@link JsonParseException}s - * based on current state of the parser - */ - protected JsonParseException _constructError(String msg) { - return new JsonParseException(this, msg) - .withRequestPayload(_requestPayload); - } - - /** - * Helper method to call for operations that are not supported by - * parser implementation. - * - * @since 2.1 - */ - protected void _reportUnsupportedOperation() { - throw new UnsupportedOperationException("Operation not supported by parser of type "+getClass().getName()); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonPointer.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonPointer.java deleted file mode 100644 index fd97c293..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonPointer.java +++ /dev/null @@ -1,413 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.NumberInput; - -/** - * Implementation of - * JSON Pointer - * specification. - * Pointer instances can be used to locate logical JSON nodes for things like - * tree traversal (see {@link TreeNode#at}). - * It may be used in future for filtering of streaming JSON content - * as well (not implemented yet for 2.3). - *

- * Instances are fully immutable and can be shared, cached. - * - * @author Tatu Saloranta - * - * @since 2.3 - */ -public class JsonPointer -{ - /** - * Character used to separate segments. - * - * @since 2.9 - */ - public final static char SEPARATOR = '/'; - - /** - * Marker instance used to represent segment that matches current - * node or position (that is, returns true for - * {@link #matches()}). - */ - protected final static JsonPointer EMPTY = new JsonPointer(); - - /** - * Reference to rest of the pointer beyond currently matching - * segment (if any); null if this pointer refers to the matching - * segment. - */ - protected final JsonPointer _nextSegment; - - /** - * Reference from currently matching segment (if any) to node - * before leaf. - * Lazily constructed if/as needed. - *

- * NOTE: we'll use `volatile` here assuming that this is unlikely to - * become a performance bottleneck. If it becomes one we can probably - * just drop it and things still should work (despite warnings as per JMM - * regarding visibility (and lack thereof) of unguarded changes). - * - * @since 2.5 - */ - protected volatile JsonPointer _head; - - /** - * We will retain representation of the pointer, as a String, - * so that {@link #toString} should be as efficient as possible. - */ - protected final String _asString; - - protected final String _matchingPropertyName; - - protected final int _matchingElementIndex; - - /* - /********************************************************** - /* Construction - /********************************************************** - */ - - /** - * Constructor used for creating "empty" instance, used to represent - * state that matches current node. - */ - protected JsonPointer() { - _nextSegment = null; - _matchingPropertyName = ""; - _matchingElementIndex = -1; - _asString = ""; - } - - /** - * Constructor used for creating non-empty Segments - */ - protected JsonPointer(String fullString, String segment, JsonPointer next) { - _asString = fullString; - _nextSegment = next; - // Ok; may always be a property - _matchingPropertyName = segment; - // but could be an index, if parsable - _matchingElementIndex = _parseIndex(segment); - } - - /** - * @since 2.5 - */ - protected JsonPointer(String fullString, String segment, int matchIndex, JsonPointer next) { - _asString = fullString; - _nextSegment = next; - _matchingPropertyName = segment; - _matchingElementIndex = matchIndex; - } - - /* - /********************************************************** - /* Factory methods - /********************************************************** - */ - - /** - * Factory method that parses given input and construct matching pointer - * instance, if it represents a valid JSON Pointer: if not, a - * {@link IllegalArgumentException} is thrown. - * - * @throws IllegalArgumentException Thrown if the input does not present a valid JSON Pointer - * expression: currently the only such expression is one that does NOT start with - * a slash ('/'). - */ - public static JsonPointer compile(String input) throws IllegalArgumentException - { - // First quick checks for well-known 'empty' pointer - if ((input == null) || input.length() == 0) { - return EMPTY; - } - // And then quick validity check: - if (input.charAt(0) != '/') { - throw new IllegalArgumentException("Invalid input: JSON Pointer expression must start with '/': "+"\""+input+"\""); - } - return _parseTail(input); - } - - /** - * Alias for {@link #compile}; added to make instances automatically - * deserializable by Jackson databind. - */ - public static JsonPointer valueOf(String input) { return compile(input); } - - /* Factory method that composes a pointer instance, given a set - * of 'raw' segments: raw meaning that no processing will be done, - * no escaping may is present. - * - * @param segments - * - * @return Constructed path instance - */ - /* TODO! - public static JsonPointer fromSegment(String... segments) - { - if (segments.length == 0) { - return EMPTY; - } - JsonPointer prev = null; - - for (String segment : segments) { - JsonPointer next = new JsonPointer() - } - } - */ - - /* - /********************************************************** - /* Public API - /********************************************************** - */ - - public boolean matches() { return _nextSegment == null; } - public String getMatchingProperty() { return _matchingPropertyName; } - public int getMatchingIndex() { return _matchingElementIndex; } - public boolean mayMatchProperty() { return _matchingPropertyName != null; } - public boolean mayMatchElement() { return _matchingElementIndex >= 0; } - - /** - * Returns the leaf of current JSON Pointer expression. - * Leaf is the last non-null segment of current JSON Pointer. - * - * @since 2.5 - */ - public JsonPointer last() { - JsonPointer current = this; - if (current == EMPTY) { - return null; - } - JsonPointer next; - while ((next = current._nextSegment) != JsonPointer.EMPTY) { - current = next; - } - return current; - } - - public JsonPointer append(JsonPointer tail) { - if (this == EMPTY) { - return tail; - } - if (tail == EMPTY) { - return this; - } - String currentJsonPointer = _asString; - if (currentJsonPointer.endsWith("/")) { - //removes final slash - currentJsonPointer = currentJsonPointer.substring(0, currentJsonPointer.length()-1); - } - return compile(currentJsonPointer + tail._asString); - } - - /** - * Method that may be called to see if the pointer would match property - * (of a JSON Object) with given name. - * - * @since 2.5 - */ - public boolean matchesProperty(String name) { - return (_nextSegment != null) && _matchingPropertyName.equals(name); - } - - public JsonPointer matchProperty(String name) { - if ((_nextSegment != null) && _matchingPropertyName.equals(name)) { - return _nextSegment; - } - return null; - } - - /** - * Method that may be called to see if the pointer would match - * array element (of a JSON Array) with given index. - * - * @since 2.5 - */ - public boolean matchesElement(int index) { - return (index == _matchingElementIndex) && (index >= 0); - } - - /** - * @since 2.6 - */ - public JsonPointer matchElement(int index) { - if ((index != _matchingElementIndex) || (index < 0)) { - return null; - } - return _nextSegment; - } - - /** - * Accessor for getting a "sub-pointer", instance where current segment - * has been removed and pointer includes rest of segments. - * For matching state, will return null. - */ - public JsonPointer tail() { - return _nextSegment; - } - - /** - * Accessor for getting a pointer instance that is identical to this - * instance except that the last segment has been dropped. - * For example, for JSON Point "/root/branch/leaf", this method would - * return pointer "/root/branch" (compared to {@link #tail()} that - * would return "/branch/leaf"). - * For leaf - * - * @since 2.5 - */ - public JsonPointer head() { - JsonPointer h = _head; - if (h == null) { - if (this != EMPTY) { - h = _constructHead(); - } - _head = h; - } - return h; - } - - /* - /********************************************************** - /* Standard method overrides - /********************************************************** - */ - - @Override public String toString() { return _asString; } - @Override public int hashCode() { return _asString.hashCode(); } - - @Override public boolean equals(Object o) { - if (o == this) return true; - if (o == null) return false; - if (!(o instanceof JsonPointer)) return false; - return _asString.equals(((JsonPointer) o)._asString); - } - - /* - /********************************************************** - /* Internal methods - /********************************************************** - */ - - private final static int _parseIndex(String str) { - final int len = str.length(); - // [core#133]: beware of super long indexes; assume we never - // have arrays over 2 billion entries so ints are fine. - if (len == 0 || len > 10) { - return -1; - } - // [core#176]: no leading zeroes allowed - char c = str.charAt(0); - if (c <= '0') { - return (len == 1 && c == '0') ? 0 : -1; - } - if (c > '9') { - return -1; - } - for (int i = 1; i < len; ++i) { - c = str.charAt(i); - if (c > '9' || c < '0') { - return -1; - } - } - if (len == 10) { - long l = NumberInput.parseLong(str); - if (l > Integer.MAX_VALUE) { - return -1; - } - } - return NumberInput.parseInt(str); - } - - protected static JsonPointer _parseTail(String input) { - final int end = input.length(); - - // first char is the contextual slash, skip - for (int i = 1; i < end; ) { - char c = input.charAt(i); - if (c == '/') { // common case, got a segment - return new JsonPointer(input, input.substring(1, i), - _parseTail(input.substring(i))); - } - ++i; - // quoting is different; offline this case - if (c == '~' && i < end) { // possibly, quote - return _parseQuotedTail(input, i); - } - // otherwise, loop on - } - // end of the road, no escapes - return new JsonPointer(input, input.substring(1), EMPTY); - } - - /** - * Method called to parse tail of pointer path, when a potentially - * escaped character has been seen. - * - * @param input Full input for the tail being parsed - * @param i Offset to character after tilde - */ - protected static JsonPointer _parseQuotedTail(String input, int i) { - final int end = input.length(); - StringBuilder sb = new StringBuilder(Math.max(16, end)); - if (i > 2) { - sb.append(input, 1, i-1); - } - _appendEscape(sb, input.charAt(i++)); - while (i < end) { - char c = input.charAt(i); - if (c == '/') { // end is nigh! - return new JsonPointer(input, sb.toString(), - _parseTail(input.substring(i))); - } - ++i; - if (c == '~' && i < end) { - _appendEscape(sb, input.charAt(i++)); - continue; - } - sb.append(c); - } - // end of the road, last segment - return new JsonPointer(input, sb.toString(), EMPTY); - } - - protected JsonPointer _constructHead() - { - // ok; find out who we are to drop - JsonPointer last = last(); - if (last == this) { - return EMPTY; - } - // and from that, length of suffix to drop - int suffixLength = last._asString.length(); - JsonPointer next = _nextSegment; - return new JsonPointer(_asString.substring(0, _asString.length() - suffixLength), _matchingPropertyName, - _matchingElementIndex, next._constructHead(suffixLength, last)); - } - - protected JsonPointer _constructHead(int suffixLength, JsonPointer last) - { - if (this == last) { - return EMPTY; - } - JsonPointer next = _nextSegment; - String str = _asString; - return new JsonPointer(str.substring(0, str.length() - suffixLength), _matchingPropertyName, - _matchingElementIndex, next._constructHead(suffixLength, last)); - } - - private static void _appendEscape(StringBuilder sb, char c) { - if (c == '0') { - c = '~'; - } else if (c == '1') { - c = '/'; - } else { - sb.append('~'); - } - sb.append(c); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonProcessingException.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonProcessingException.java deleted file mode 100644 index a1d48ae2..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonProcessingException.java +++ /dev/null @@ -1,137 +0,0 @@ -/* Jackson JSON-processor. - * - * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi - */ - -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -/** - * Intermediate base class for all problems encountered when - * processing (parsing, generating) JSON content - * that are not pure I/O problems. - * Regular {@link java.io.IOException}s will be passed through as is. - * Sub-class of {@link java.io.IOException} for convenience. - */ -public class JsonProcessingException extends java.io.IOException -{ - final static long serialVersionUID = 123; // Stupid eclipse... - - protected JsonLocation _location; - - protected JsonProcessingException(String msg, JsonLocation loc, Throwable rootCause) { - /* Argh. IOException(Throwable,String) is only available starting - * with JDK 1.6... - */ - super(msg); - if (rootCause != null) { - initCause(rootCause); - } - _location = loc; - } - - protected JsonProcessingException(String msg) { - super(msg); - } - - protected JsonProcessingException(String msg, JsonLocation loc) { - this(msg, loc, null); - } - - protected JsonProcessingException(String msg, Throwable rootCause) { - this(msg, null, rootCause); - } - - protected JsonProcessingException(Throwable rootCause) { - this(null, null, rootCause); - } - - /* - /********************************************************** - /* Extended API - /********************************************************** - */ - - public JsonLocation getLocation() { return _location; } - - /** - * Method that allows to remove context information from this exception's message. - * Useful when you are parsing security-sensitive data and don't want original data excerpts - * to be present in Jackson parser error messages. - * - * @since 2.9 - */ - public void clearLocation() { _location = null; } - - /** - * Method that allows accessing the original "message" argument, - * without additional decorations (like location information) - * that overridden {@link #getMessage} adds. - * - * @since 2.1 - */ - public String getOriginalMessage() { return super.getMessage(); } - - /** - * Method that allows accessing underlying processor that triggered - * this exception; typically either {@link JsonParser} or {@link JsonGenerator} - * for exceptions that originate from streaming API. - * Note that it is possible that `null` may be returned if code throwing - * exception either has no access to processor; or has not been retrofitted - * to set it; this means that caller needs to take care to check for nulls. - * Subtypes override this method with co-variant return type, for more - * type-safe access. - * - * @return Originating processor, if available; null if not. - * - * @since 2.7 - */ - public Object getProcessor() { return null; } - - /* - /********************************************************** - /* Methods for sub-classes to use, override - /********************************************************** - */ - - /** - * Accessor that sub-classes can override to append additional - * information right after the main message, but before - * source location information. - */ - protected String getMessageSuffix() { return null; } - - /* - /********************************************************** - /* Overrides of standard methods - /********************************************************** - */ - - /** - * Default method overridden so that we can add location information - */ - @Override public String getMessage() { - String msg = super.getMessage(); - if (msg == null) { - msg = "N/A"; - } - JsonLocation loc = getLocation(); - String suffix = getMessageSuffix(); - // mild optimization, if nothing extra is needed: - if (loc != null || suffix != null) { - StringBuilder sb = new StringBuilder(100); - sb.append(msg); - if (suffix != null) { - sb.append(suffix); - } - if (loc != null) { - sb.append('\n'); - sb.append(" at "); - sb.append(loc.toString()); - } - msg = sb.toString(); - } - return msg; - } - - @Override public String toString() { return getClass().getName()+": "+getMessage(); } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonStreamContext.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonStreamContext.java deleted file mode 100644 index 3978f7bd..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonStreamContext.java +++ /dev/null @@ -1,148 +0,0 @@ -/* Jackson JSON-processor. - * - * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi - */ - -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -/** - * Shared base class for streaming processing contexts used during - * reading and writing of Json content using Streaming API. - * This context is also exposed to applications: - * context object can be used by applications to get an idea of - * relative position of the parser/generator within json content - * being processed. This allows for some contextual processing: for - * example, output within Array context can differ from that of - * Object context. - */ -public abstract class JsonStreamContext -{ - // // // Type constants used internally - - protected final static int TYPE_ROOT = 0; - protected final static int TYPE_ARRAY = 1; - protected final static int TYPE_OBJECT = 2; - - protected int _type; - - /** - * Index of the currently processed entry. Starts with -1 to signal - * that no entries have been started, and gets advanced each - * time a new entry is started, either by encountering an expected - * separator, or with new values if no separators are expected - * (the case for root context). - */ - protected int _index; - - /* - /********************************************************** - /* Life-cycle - /********************************************************** - */ - - protected JsonStreamContext() { } - - /* - /********************************************************** - /* Public API, accessors - /********************************************************** - */ - - /** - * Accessor for finding parent context of this context; will - * return null for root context. - */ - public abstract JsonStreamContext getParent(); - - /** - * Method that returns true if this context is an Array context; - * that is, content is being read from or written to a Json Array. - */ - public final boolean inArray() { return _type == TYPE_ARRAY; } - - /** - * Method that returns true if this context is a Root context; - * that is, content is being read from or written to without - * enclosing array or object structure. - */ - public final boolean inRoot() { return _type == TYPE_ROOT; } - - /** - * Method that returns true if this context is an Object context; - * that is, content is being read from or written to a Json Object. - */ - public final boolean inObject() { return _type == TYPE_OBJECT; } - - /** - * Method for accessing simple type description of current context; - * either ROOT (for root-level values), OBJECT (for field names and - * values of JSON Objects) or ARRAY (for values of JSON Arrays) - * - * @deprecated Since 2.8 use {@link #typeDesc} instead - */ - @Deprecated // since 2.8 - public final String getTypeDesc() { - switch (_type) { - case TYPE_ROOT: return "ROOT"; - case TYPE_ARRAY: return "ARRAY"; - case TYPE_OBJECT: return "OBJECT"; - } - return "?"; - } - - /** - * @since 2.8 - */ - public String typeDesc() { - switch (_type) { - case TYPE_ROOT: return "root"; - case TYPE_ARRAY: return "Array"; - case TYPE_OBJECT: return "Object"; - } - return "?"; - } - - /** - * @return Number of entries that are complete and started. - */ - public final int getEntryCount() { return _index + 1; } - - /** - * @return Index of the currently processed entry, if any - */ - public final int getCurrentIndex() { return (_index < 0) ? 0 : _index; } - - /** - * Method for accessing name associated with the current location. - * Non-null for FIELD_NAME and value events that directly - * follow field names; null for root level and array values. - */ - public abstract String getCurrentName(); - - /** - * Method for accessing currently active value being used by data-binding - * (as the source of streaming data to write, or destination of data being - * read), at this level in hierarchy. - *

- * Note that "current value" is NOT populated (or used) by Streaming parser or generator; - * it is only used by higher-level data-binding functionality. - * The reason it is included here is that it can be stored and accessed hierarchically, - * and gets passed through data-binding. - * - * @return Currently active value, if one has been assigned. - * - * @since 2.5 - */ - public Object getCurrentValue() { - return null; - } - - /** - * Method to call to pass value to be returned via {@link #getCurrentValue}; typically - * called indirectly through {@link JsonParser#setCurrentValue} - * or {@link JsonGenerator#setCurrentValue}). - * - * @since 2.5 - */ - public void setCurrentValue(Object v) { } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonToken.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonToken.java deleted file mode 100644 index 190140ee..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonToken.java +++ /dev/null @@ -1,201 +0,0 @@ -/* Jackson JSON-processor. - * - * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi - */ - -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -/** - * Enumeration for basic token types used for returning results - * of parsing JSON content. - */ -public enum JsonToken -{ - /* Some notes on implementation: - * - * - Entries are to be ordered such that start/end array/object - * markers come first, then field name marker (if any), and - * finally scalar value tokens. This is assumed by some - * typing checks. - */ - - /** - * NOT_AVAILABLE can be returned if {@link JsonParser} - * implementation can not currently return the requested - * token (usually next one), or even if any will be - * available, but that may be able to determine this in - * future. This is the case with non-blocking parsers -- - * they can not block to wait for more data to parse and - * must return something. - */ - NOT_AVAILABLE(null, JsonTokenId.ID_NOT_AVAILABLE), - - /** - * START_OBJECT is returned when encountering '{' - * which signals starting of an Object value. - */ - START_OBJECT("{", JsonTokenId.ID_START_OBJECT), - - /** - * END_OBJECT is returned when encountering '}' - * which signals ending of an Object value - */ - END_OBJECT("}", JsonTokenId.ID_END_OBJECT), - - /** - * START_ARRAY is returned when encountering '[' - * which signals starting of an Array value - */ - START_ARRAY("[", JsonTokenId.ID_START_ARRAY), - - /** - * END_ARRAY is returned when encountering ']' - * which signals ending of an Array value - */ - END_ARRAY("]", JsonTokenId.ID_END_ARRAY), - - /** - * FIELD_NAME is returned when a String token is encountered - * as a field name (same lexical value, different function) - */ - FIELD_NAME(null, JsonTokenId.ID_FIELD_NAME), - - /** - * Placeholder token returned when the input source has a concept - * of embedded Object that are not accessible as usual structure - * (of starting with {@link #START_OBJECT}, having values, ending with - * {@link #END_OBJECT}), but as "raw" objects. - *

- * Note: this token is never returned by regular JSON readers, but - * only by readers that expose other kinds of source (like - * JsonNode-based JSON trees, Maps, Lists and such). - */ - VALUE_EMBEDDED_OBJECT(null, JsonTokenId.ID_EMBEDDED_OBJECT), - - /** - * VALUE_STRING is returned when a String token is encountered - * in value context (array element, field value, or root-level - * stand-alone value) - */ - VALUE_STRING(null, JsonTokenId.ID_STRING), - - /** - * VALUE_NUMBER_INT is returned when an integer numeric token is - * encountered in value context: that is, a number that does - * not have floating point or exponent marker in it (consists - * only of an optional sign, followed by one or more digits) - */ - VALUE_NUMBER_INT(null, JsonTokenId.ID_NUMBER_INT), - - /** - * VALUE_NUMBER_INT is returned when a numeric token other - * that is not an integer is encountered: that is, a number that does - * have floating point or exponent marker in it, in addition - * to one or more digits. - */ - VALUE_NUMBER_FLOAT(null, JsonTokenId.ID_NUMBER_FLOAT), - - /** - * VALUE_TRUE is returned when encountering literal "true" in - * value context - */ - VALUE_TRUE("true", JsonTokenId.ID_TRUE), - - /** - * VALUE_FALSE is returned when encountering literal "false" in - * value context - */ - VALUE_FALSE("false", JsonTokenId.ID_FALSE), - - /** - * VALUE_NULL is returned when encountering literal "null" in - * value context - */ - VALUE_NULL("null", JsonTokenId.ID_NULL), - ; - - final String _serialized; - - final char[] _serializedChars; - - final byte[] _serializedBytes; - - final int _id; - - final boolean _isStructStart, _isStructEnd; - - final boolean _isNumber; - - final boolean _isBoolean; - - final boolean _isScalar; - - /** - * @param token representation for this token, if there is a - * single static representation; null otherwise - */ - JsonToken(String token, int id) - { - if (token == null) { - _serialized = null; - _serializedChars = null; - _serializedBytes = null; - } else { - _serialized = token; - _serializedChars = token.toCharArray(); - // It's all in ascii, can just case... - int len = _serializedChars.length; - _serializedBytes = new byte[len]; - for (int i = 0; i < len; ++i) { - _serializedBytes[i] = (byte) _serializedChars[i]; - } - } - _id = id; - - _isBoolean = (id == JsonTokenId.ID_FALSE || id == JsonTokenId.ID_TRUE); - _isNumber = (id == JsonTokenId.ID_NUMBER_INT || id == JsonTokenId.ID_NUMBER_FLOAT); - - _isStructStart = (id == JsonTokenId.ID_START_OBJECT || id == JsonTokenId.ID_START_ARRAY); - _isStructEnd = (id == JsonTokenId.ID_END_OBJECT || id == JsonTokenId.ID_END_ARRAY); - - _isScalar = !_isStructStart && !_isStructEnd - && (id != JsonTokenId.ID_FIELD_NAME) - && (id != JsonTokenId.ID_NOT_AVAILABLE); - } - - public final int id() { return _id; } - - public final String asString() { return _serialized; } - public final char[] asCharArray() { return _serializedChars; } - public final byte[] asByteArray() { return _serializedBytes; } - - public final boolean isNumeric() { return _isNumber; } - - /** - * Accessor that is functionally equivalent to: - * - * this == JsonToken.START_OBJECT || this == JsonToken.START_ARRAY - * - * - * @since 2.3 - */ - public final boolean isStructStart() { return _isStructStart; } - - /** - * Accessor that is functionally equivalent to: - * - * this == JsonToken.END_OBJECT || this == JsonToken.END_ARRAY - * - * - * @since 2.3 - */ - public final boolean isStructEnd() { return _isStructEnd; } - - /** - * Method that can be used to check whether this token represents - * a valid non-structured value. This means all tokens other than - * Object/Array start/end markers all field names. - */ - public final boolean isScalarValue() { return _isScalar; } - public final boolean isBoolean() { return _isBoolean; } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonTokenId.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonTokenId.java deleted file mode 100644 index 283c43c5..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonTokenId.java +++ /dev/null @@ -1,87 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -/** - * Interface defined to contain ids accessible with {@link JsonToken#id()}. - * Needed because it is impossible to define these constants in - * {@link JsonToken} itself, as static constants (oddity of how Enums - * are implemented by JVM). - * - * @since 2.3 - */ -public interface JsonTokenId -{ - /** - * Id used to represent {@link JsonToken#NOT_AVAILABLE}, used in - * cases where a token may become available when more input - * is available: this occurs in non-blocking use cases. - */ - public final static int ID_NOT_AVAILABLE = -1; - - /** - * Id used to represent the case where no {@link JsonToken} - * is available: either because {@link JsonParser} has not been - * advanced to first token, or because no more tokens will be - * available (end-of-input or explicit closing of parser}. - */ - public final static int ID_NO_TOKEN = 0; - - /** - * Id used to represent {@link JsonToken#START_OBJECT} - */ - public final static int ID_START_OBJECT = 1; - - /** - * Id used to represent {@link JsonToken#END_OBJECT} - */ - public final static int ID_END_OBJECT = 2; - - /** - * Id used to represent {@link JsonToken#START_ARRAY} - */ - public final static int ID_START_ARRAY = 3; - - /** - * Id used to represent {@link JsonToken#END_ARRAY} - */ - public final static int ID_END_ARRAY = 4; - - /** - * Id used to represent {@link JsonToken#FIELD_NAME} - */ - public final static int ID_FIELD_NAME = 5; - - /** - * Id used to represent {@link JsonToken#VALUE_STRING} - */ - public final static int ID_STRING = 6; - - /** - * Id used to represent {@link JsonToken#VALUE_NUMBER_INT} - */ - public final static int ID_NUMBER_INT = 7; - - /** - * Id used to represent {@link JsonToken#VALUE_NUMBER_FLOAT} - */ - public final static int ID_NUMBER_FLOAT = 8; - - /** - * Id used to represent {@link JsonToken#VALUE_TRUE} - */ - public final static int ID_TRUE = 9; - - /** - * Id used to represent {@link JsonToken#VALUE_FALSE} - */ - public final static int ID_FALSE = 10; - /** - * Id used to represent {@link JsonToken#VALUE_NULL} - */ - - public final static int ID_NULL = 11; - - /** - * Id used to represent {@link JsonToken#VALUE_EMBEDDED_OBJECT} - */ - public final static int ID_EMBEDDED_OBJECT = 12; -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonpCharacterEscapes.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonpCharacterEscapes.java deleted file mode 100644 index 1f39b645..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/JsonpCharacterEscapes.java +++ /dev/null @@ -1,46 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.CharacterEscapes; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.SerializedString; - -/** - * Convenience {@link CharacterEscapes} implementation that escapes - * Unicode characters `0x2028` and `0x2029` (in addition to characters - * escaped otherwise), which are apparently considered linefeeds as - * per newer Javascript specifications, and consequently problematic - * when using JSONP (see https://en.wikipedia.org/wiki/JSONP). - * - * @since 2.8 - */ -public class JsonpCharacterEscapes extends CharacterEscapes -{ - private static final long serialVersionUID = 1L; - - private static final int[] asciiEscapes = CharacterEscapes.standardAsciiEscapesForJSON(); - private static final SerializedString escapeFor2028 = new SerializedString("\\u2028"); - private static final SerializedString escapeFor2029 = new SerializedString("\\u2029"); - - private static final JsonpCharacterEscapes sInstance = new JsonpCharacterEscapes(); - - public static JsonpCharacterEscapes instance() { - return sInstance; - } - - @Override - public SerializableString getEscapeSequence(int ch) - { - switch (ch) { - case 0x2028: - return escapeFor2028; - case 0x2029: - return escapeFor2029; - default: - return null; - } - } - - @Override - public int[] getEscapeCodesForAscii() { - return asciiEscapes; - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/ObjectCodec.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/ObjectCodec.java deleted file mode 100644 index fef6870b..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/ObjectCodec.java +++ /dev/null @@ -1,181 +0,0 @@ -/* Jackson JSON-processor. - * - * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi - */ - -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -import java.io.IOException; -import java.util.Iterator; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.type.ResolvedType; -import autosaveworld.zlibs.com.fasterxml.jackson.core.type.TypeReference; - -/** - * Abstract class that defines the interface that {@link JsonParser} and - * {@link JsonGenerator} use to serialize and deserialize regular - * Java objects (POJOs aka Beans). - *

- * The standard implementation of this class is - * com.fasterxml.jackson.databind.ObjectMapper, - * defined in the "jackson-databind". - */ -public abstract class ObjectCodec - extends TreeCodec // since 2.3 - implements Versioned // since 2.3 -{ - protected ObjectCodec() { } - - // Since 2.3 - @Override - public abstract Version version(); - - /* - /********************************************************** - /* API for de-serialization (JSON-to-Object) - /********************************************************** - */ - - /** - * Method to deserialize JSON content into a non-container - * type (it can be an array type, however): typically a bean, array - * or a wrapper type (like {@link java.lang.Boolean}). - *

- * Note: this method should NOT be used if the result type is a - * container ({@link java.util.Collection} or {@link java.util.Map}. - * The reason is that due to type erasure, key and value types - * can not be introspected when using this method. - */ - public abstract T readValue(JsonParser p, Class valueType) - throws IOException; - - /** - * Method to deserialize JSON content into a Java type, reference - * to which is passed as argument. Type is passed using so-called - * "super type token" - * and specifically needs to be used if the root type is a - * parameterized (generic) container type. - */ - public abstract T readValue(JsonParser p, TypeReference valueTypeRef) - throws IOException; - - /** - * Method to deserialize JSON content into a POJO, type specified - * with fully resolved type object (so it can be a generic type, - * including containers like {@link java.util.Collection} and - * {@link java.util.Map}). - */ - public abstract T readValue(JsonParser p, ResolvedType valueType) - throws IOException; - - /** - * Method for reading sequence of Objects from parser stream, - * all with same specified value type. - */ - public abstract Iterator readValues(JsonParser p, Class valueType) - throws IOException; - - /** - * Method for reading sequence of Objects from parser stream, - * all with same specified value type. - */ - public abstract Iterator readValues(JsonParser p, TypeReference valueTypeRef) - throws IOException; - - /** - * Method for reading sequence of Objects from parser stream, - * all with same specified value type. - */ - public abstract Iterator readValues(JsonParser p, ResolvedType valueType) - throws IOException; - - /* - /********************************************************** - /* API for serialization (Object-to-JSON) - /********************************************************** - */ - - /** - * Method to serialize given Java Object, using generator - * provided. - */ - public abstract void writeValue(JsonGenerator gen, Object value) throws IOException; - - /* - /********************************************************** - /* TreeCodec pass-through methods - /********************************************************** - */ - - /** - * Method to deserialize JSON content as tree expressed - * using set of {@link TreeNode} instances. Returns - * root of the resulting tree (where root can consist - * of just a single node if the current event is a - * value event, not container). Empty or whitespace - * documents return null. - * - * @return next tree from p, or null if empty. - */ - @Override - public abstract T readTree(JsonParser p) throws IOException; - - @Override - public abstract void writeTree(JsonGenerator gen, TreeNode tree) throws IOException; - - /** - * Method for construct root level Object nodes - * for Tree Model instances. - */ - @Override - public abstract TreeNode createObjectNode(); - - /** - * Method for construct root level Array nodes - * for Tree Model instances. - */ - @Override - public abstract TreeNode createArrayNode(); - - /** - * Method for constructing a {@link JsonParser} for reading - * contents of a JSON tree, as if it was external serialized - * JSON content. - */ - @Override - public abstract JsonParser treeAsTokens(TreeNode n); - - /* - /********************************************************** - /* Extended tree conversions beyond TreeCodec - /********************************************************** - */ - - /** - * Convenience method for converting given JSON tree into instance of specified - * value type. This is equivalent to first constructing a {@link JsonParser} to - * iterate over contents of the tree, and using that parser for data binding. - */ - public abstract T treeToValue(TreeNode n, Class valueType) - throws JsonProcessingException; - - /* - /********************************************************** - /* Basic accessors - /********************************************************** - */ - - /** - * @deprecated Since 2.1: Use {@link #getFactory} instead. - */ - @Deprecated - public JsonFactory getJsonFactory() { return getFactory(); } - - /** - * Accessor for finding underlying data format factory - * ({@link JsonFactory}) codec will use for data binding. - * - * @since 2.1 - */ - public JsonFactory getFactory() { return getJsonFactory(); } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/PrettyPrinter.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/PrettyPrinter.java deleted file mode 100644 index 8968f40e..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/PrettyPrinter.java +++ /dev/null @@ -1,177 +0,0 @@ -/* Jackson JSON-processor. - * - * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi - */ - -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -import java.io.IOException; - -/** - * Interface for objects that implement pretty printer functionality, such - * as indentation. - * Pretty printers are used to add white space in output JSON content, - * to make results more human readable. Usually this means things like adding - * linefeeds and indentation. - *

- * Note: since Jackson 2.1, stateful implementations MUST implement - * {@link autosaveworld.zlibs.com.fasterxml.jackson.core.util.Instantiatable} interface, - * to allow for constructing per-generation instances and avoid - * state corruption (see [JACKSON-851] for details). - * Stateless implementations need not do this; but those are less common. - */ -public interface PrettyPrinter -{ - /* - /********************************************************** - /* First methods that act both as events, and expect - /* output for correct functioning (i.e something gets - /* output even when not pretty-printing) - /********************************************************** - */ - - // // // Root-level handling: - - /** - * Method called after a root-level value has been completely - * output, and before another value is to be output. - *

- * Default - * handling (without pretty-printing) will output a space, to - * allow values to be parsed correctly. Pretty-printer is - * to output some other suitable and nice-looking separator - * (tab(s), space(s), linefeed(s) or any combination thereof). - */ - void writeRootValueSeparator(JsonGenerator jg) - throws IOException, JsonGenerationException; - - // // Object handling - - /** - * Method called when an Object value is to be output, before - * any fields are output. - *

- * Default handling (without pretty-printing) will output - * the opening curly bracket. - * Pretty-printer is - * to output a curly bracket as well, but can surround that - * with other (white-space) decoration. - */ - void writeStartObject(JsonGenerator gen) - throws IOException, JsonGenerationException; - - /** - * Method called after an Object value has been completely output - * (minus closing curly bracket). - *

- * Default handling (without pretty-printing) will output - * the closing curly bracket. - * Pretty-printer is - * to output a curly bracket as well, but can surround that - * with other (white-space) decoration. - * - * @param nrOfEntries Number of direct members of the array that - * have been output - */ - void writeEndObject(JsonGenerator gen, int nrOfEntries) - throws IOException, JsonGenerationException; - - /** - * Method called after an object entry (field:value) has been completely - * output, and before another value is to be output. - *

- * Default handling (without pretty-printing) will output a single - * comma to separate the two. Pretty-printer is - * to output a comma as well, but can surround that with other - * (white-space) decoration. - */ - void writeObjectEntrySeparator(JsonGenerator gen) - throws IOException, JsonGenerationException; - - /** - * Method called after an object field has been output, but - * before the value is output. - *

- * Default handling (without pretty-printing) will output a single - * colon to separate the two. Pretty-printer is - * to output a colon as well, but can surround that with other - * (white-space) decoration. - */ - void writeObjectFieldValueSeparator(JsonGenerator gen) - throws IOException, JsonGenerationException; - - // // // Array handling - - /** - * Method called when an Array value is to be output, before - * any member/child values are output. - *

- * Default handling (without pretty-printing) will output - * the opening bracket. - * Pretty-printer is - * to output a bracket as well, but can surround that - * with other (white-space) decoration. - */ - void writeStartArray(JsonGenerator gen) - throws IOException, JsonGenerationException; - - /** - * Method called after an Array value has been completely output - * (minus closing bracket). - *

- * Default handling (without pretty-printing) will output - * the closing bracket. - * Pretty-printer is - * to output a bracket as well, but can surround that - * with other (white-space) decoration. - * - * @param nrOfValues Number of direct members of the array that - * have been output - */ - void writeEndArray(JsonGenerator gen, int nrOfValues) - throws IOException, JsonGenerationException; - - /** - * Method called after an array value has been completely - * output, and before another value is to be output. - *

- * Default handling (without pretty-printing) will output a single - * comma to separate the two. Pretty-printer is - * to output a comma as well, but can surround that with other - * (white-space) decoration. - */ - void writeArrayValueSeparator(JsonGenerator gen) - throws IOException, JsonGenerationException; - - /* - /********************************************************** - /* Then events that by default do not produce any output - /* but that are often overridden to add white space - /* in pretty-printing mode - /********************************************************** - */ - - /** - * Method called after array start marker has been output, - * and right before the first value is to be output. - * It is not called for arrays with no values. - *

- * Default handling does not output anything, but pretty-printer - * is free to add any white space decoration. - */ - void beforeArrayValues(JsonGenerator gen) - throws IOException, JsonGenerationException; - - /** - * Method called after object start marker has been output, - * and right before the field name of the first entry is - * to be output. - * It is not called for objects without entries. - *

- * Default handling does not output anything, but pretty-printer - * is free to add any white space decoration. - */ - void beforeObjectEntries(JsonGenerator gen) - throws IOException, JsonGenerationException; -} - diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/SerializableString.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/SerializableString.java deleted file mode 100644 index f0e75efa..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/SerializableString.java +++ /dev/null @@ -1,156 +0,0 @@ -/* Jackson JSON-processor. - * - * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi - */ - -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -import java.io.IOException; -import java.io.OutputStream; -import java.nio.ByteBuffer; - -/** - * Interface that defines how Jackson package can interact with efficient - * pre-serialized or lazily-serialized and reused String representations. - * Typically implementations store possible serialized version(s) so that - * serialization of String can be done more efficiently, especially when - * used multiple times. - *

- * Note that "quoted" in methods means quoting of 'special' characters using - * JSON backlash notation (and not use of actual double quotes). - * - * @see autosaveworld.zlibs.com.fasterxml.jackson.core.io.SerializedString - */ -public interface SerializableString -{ - /** - * Returns unquoted String that this object represents (and offers - * serialized forms for) - */ - String getValue(); - - /** - * Returns length of the (unquoted) String as characters. - * Functionally equvalent to: - *

-     *   getValue().length();
-     *
- */ - int charLength(); - - /* - /********************************************************** - /* Accessors for byte sequences - /********************************************************** - */ - - /** - * Returns JSON quoted form of the String, as character array. - * Result can be embedded as-is in textual JSON as property name or JSON String. - */ - char[] asQuotedChars(); - - /** - * Returns UTF-8 encoded version of unquoted String. - * Functionally equivalent to (but more efficient than): - *
-     * getValue().getBytes("UTF-8");
-     *
- */ - byte[] asUnquotedUTF8(); - - /** - * Returns UTF-8 encoded version of JSON-quoted String. - * Functionally equivalent to (but more efficient than): - *
-     * new String(asQuotedChars()).getBytes("UTF-8");
-     *
- */ - byte[] asQuotedUTF8(); - - /* - /********************************************************** - /* Helper methods for appending byte/char sequences - /********************************************************** - */ - - /** - * Method that will append quoted UTF-8 bytes of this String into given - * buffer, if there is enough room; if not, returns -1. - * Functionally equivalent to: - *
-     *  byte[] bytes = str.asQuotedUTF8();
-     *  System.arraycopy(bytes, 0, buffer, offset, bytes.length);
-     *  return bytes.length;
-     *
- * - * @return Number of bytes appended, if successful, otherwise -1 - */ - int appendQuotedUTF8(byte[] buffer, int offset); - - /** - * Method that will append quoted characters of this String into given - * buffer. Functionally equivalent to: - *
-     *  char[] ch = str.asQuotedChars();
-     *  System.arraycopy(ch, 0, buffer, offset, ch.length);
-     *  return ch.length;
-     *
- * - * @return Number of characters appended, if successful, otherwise -1 - */ - int appendQuoted(char[] buffer, int offset); - - /** - * Method that will append unquoted ('raw') UTF-8 bytes of this String into given - * buffer. Functionally equivalent to: - *
-     *  byte[] bytes = str.asUnquotedUTF8();
-     *  System.arraycopy(bytes, 0, buffer, offset, bytes.length);
-     *  return bytes.length;
-     *
- * - * @return Number of bytes appended, if successful, otherwise -1 - */ - int appendUnquotedUTF8(byte[] buffer, int offset); - - - /** - * Method that will append unquoted characters of this String into given - * buffer. Functionally equivalent to: - *
-     *  char[] ch = str.getValue().toCharArray();
-     *  System.arraycopy(bytes, 0, buffer, offset, ch.length);
-     *  return ch.length;
-     *
- * - * @return Number of characters appended, if successful, otherwise -1 - */ - int appendUnquoted(char[] buffer, int offset); - - /* - /********************************************************** - /* Helper methods for writing out byte sequences - /********************************************************** - */ - - /** - * @return Number of bytes written - */ - int writeQuotedUTF8(OutputStream out) throws IOException; - - /** - * @return Number of bytes written - */ - int writeUnquotedUTF8(OutputStream out) throws IOException; - - /** - * @return Number of bytes put, if successful, otherwise -1 - */ - int putQuotedUTF8(ByteBuffer buffer) throws IOException; - - /** - * @return Number of bytes put, if successful, otherwise -1 - */ - int putUnquotedUTF8(ByteBuffer out) throws IOException; -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/TreeCodec.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/TreeCodec.java deleted file mode 100644 index 230a0343..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/TreeCodec.java +++ /dev/null @@ -1,18 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -import java.io.IOException; - -/** - * Interface that defines objects that can read and write - * {@link TreeNode} instances using Streaming API. - * - * @since 2.3 - */ -public abstract class TreeCodec -{ - public abstract T readTree(JsonParser p) throws IOException, JsonProcessingException; - public abstract void writeTree(JsonGenerator g, TreeNode tree) throws IOException, JsonProcessingException; - public abstract TreeNode createArrayNode(); - public abstract TreeNode createObjectNode(); - public abstract JsonParser treeAsTokens(TreeNode node); -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/TreeNode.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/TreeNode.java deleted file mode 100644 index b9c53051..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/TreeNode.java +++ /dev/null @@ -1,288 +0,0 @@ -/* Jackson JSON-processor. - * - * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi - */ - -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -import java.util.Iterator; - -/** - * Marker interface used to denote JSON Tree nodes, as far as - * the core package knows them (which is very little): mostly - * needed to allow {@link ObjectCodec} to have some level - * of interoperability. - * Most functionality is within JsonNode - * base class in mapper package. - *

- * Note that in Jackson 1.x JsonNode itself - * was part of core package: Jackson 2.x refactored this - * since conceptually Tree Model is part of mapper package, - * and so part visible to core package should - * be minimized. - *

- * NOTE: starting with Jackson 2.2, there is more functionality - * available via this class, and the intent is that this should - * form actual base for multiple alternative tree representations; - * for example, immutable trees could use different implementation - * than mutable trees. It should also be possible to move actual - * Tree Model implementation out of databind package eventually - * (Jackson 3?). - * - * @since 2.2 - */ -public interface TreeNode -{ - /* - /********************************************************** - /* Minimal introspection methods - /********************************************************** - */ - - /** - * Method that can be used for efficient type detection - * when using stream abstraction for traversing nodes. - * Will return the first {@link JsonToken} that equivalent - * stream event would produce (for most nodes there is just - * one token but for structured/container types multiple) - */ - JsonToken asToken(); - - /** - * If this node is a numeric type (as per {@link JsonToken#isNumeric}), - * returns native type that node uses to store the numeric value; - * otherwise returns null. - * - * @return Type of number contained, if any; or null if node does not - * contain numeric value. - */ - JsonParser.NumberType numberType(); - - /** - * Method that returns number of child nodes this node contains: - * for Array nodes, number of child elements, for Object nodes, - * number of fields, and for all other nodes 0. - * - * @return For non-container nodes returns 0; for arrays number of - * contained elements, and for objects number of fields. - * - * @since 2.2 - */ - int size(); - - /** - * Method that returns true for all value nodes: ones that - * are not containers, and that do not represent "missing" nodes - * in the path. Such value nodes represent String, Number, Boolean - * and null values from JSON. - *

- * Note: one and only one of methods {@link #isValueNode}, - * {@link #isContainerNode} and {@link #isMissingNode} ever - * returns true for any given node. - * - * @since 2.2 - */ - boolean isValueNode(); - - /** - * Method that returns true for container nodes: Arrays and Objects. - *

- * Note: one and only one of methods {@link #isValueNode}, - * {@link #isContainerNode} and {@link #isMissingNode} ever - * returns true for any given node. - * - * @since 2.2 - */ - boolean isContainerNode(); - - /** - * Method that returns true for "virtual" nodes which represent - * missing entries constructed by path accessor methods when - * there is no actual node matching given criteria. - *

- * Note: one and only one of methods {@link #isValueNode}, - * {@link #isContainerNode} and {@link #isMissingNode} ever - * returns true for any given node. - * - * @since 2.2 - */ - boolean isMissingNode(); - - /** - * Method that returns true if this node is an Array node, false - * otherwise. - * Note that if true is returned, {@link #isContainerNode} - * must also return true. - * - * @since 2.2 - */ - boolean isArray(); - - /** - * Method that returns true if this node is an Object node, false - * otherwise. - * Note that if true is returned, {@link #isContainerNode} - * must also return true. - * - * @since 2.2 - */ - boolean isObject(); - - /* - /********************************************************** - /* Basic traversal through structured entries (Arrays, Objects) - /********************************************************** - */ - - /** - * Method for accessing value of the specified field of - * an object node. If this node is not an object (or it - * does not have a value for specified field name), or - * if there is no field with such name, null is returned. - *

- * NOTE: handling of explicit null values may vary between - * implementations; some trees may retain explicit nulls, others - * not. - * - * @return Node that represent value of the specified field, - * if this node is an object and has value for the specified - * field. Null otherwise. - * - * @since 2.2 - */ - TreeNode get(String fieldName); - - /** - * Method for accessing value of the specified element of - * an array node. For other nodes, null is returned. - *

- * For array nodes, index specifies - * exact location within array and allows for efficient iteration - * over child elements (underlying storage is guaranteed to - * be efficiently indexable, i.e. has random-access to elements). - * If index is less than 0, or equal-or-greater than - * node.size(), null is returned; no exception is - * thrown for any index. - * - * @return Node that represent value of the specified element, - * if this node is an array and has specified element. - * Null otherwise. - * - * @since 2.2 - */ - TreeNode get(int index); - - /** - * Method for accessing value of the specified field of - * an object node. - * For other nodes, a "missing node" (virtual node - * for which {@link #isMissingNode} returns true) is returned. - * - * @return Node that represent value of the specified field, - * if this node is an object and has value for the specified field; - * otherwise "missing node" is returned. - * - * @since 2.2 - */ - TreeNode path(String fieldName); - - /** - * Method for accessing value of the specified element of - * an array node. - * For other nodes, a "missing node" (virtual node - * for which {@link #isMissingNode} returns true) is returned. - *

- * For array nodes, index specifies - * exact location within array and allows for efficient iteration - * over child elements (underlying storage is guaranteed to - * be efficiently indexable, i.e. has random-access to elements). - * If index is less than 0, or equal-or-greater than - * node.size(), "missing node" is returned; no exception is - * thrown for any index. - * - * @return Node that represent value of the specified element, - * if this node is an array and has specified element; - * otherwise "missing node" is returned. - * - * @since 2.2 - */ - TreeNode path(int index); - - /** - * Method for accessing names of all fields for this node, iff - * this node is an Object node. Number of field names accessible - * will be {@link #size}. - * - * @since 2.2 - */ - Iterator fieldNames(); - - /** - * Method for locating node specified by given JSON pointer instances. - * Method will never return null; if no matching node exists, - * will return a node for which {@link TreeNode#isMissingNode()} returns true. - * - * @return Node that matches given JSON Pointer: if no match exists, - * will return a node for which {@link TreeNode#isMissingNode()} returns true. - * - * @since 2.3 - */ - TreeNode at(JsonPointer ptr); - - /** - * Convenience method that is functionally equivalent to: - *

-     *   return at(JsonPointer.valueOf(jsonPointerExpression));
-     *
- *

- * Note that if the same expression is used often, it is preferable to construct - * {@link JsonPointer} instance once and reuse it: this method will not perform - * any caching of compiled expressions. - * - * @param jsonPointerExpression Expression to compile as a {@link JsonPointer} - * instance - * - * @return Node that matches given JSON Pointer: if no match exists, - * will return a node for which {@link TreeNode#isMissingNode()} returns true. - * - * @since 2.3 - */ - TreeNode at(String jsonPointerExpression) throws IllegalArgumentException; - - /* - /********************************************************** - /* Converting to/from Streaming API - /********************************************************** - */ - - /** - * Method for constructing a {@link JsonParser} instance for - * iterating over contents of the tree that this node is root of. - * Functionally equivalent to first serializing tree using - * {@link ObjectCodec} and then re-parsing but - * more efficient. - *

- * NOTE: constructed parser instance will NOT initially point to a token, - * so before passing it to deserializers, it is typically necessary to - * advance it to the first available token by calling {@link JsonParser#nextToken()}. - *

- * Also note that calling this method will NOT pass {@link ObjectCodec} - * reference, so data-binding callback methods like {@link JsonParser#readValueAs(Class)} - * will not work with calling {@link JsonParser#setCodec}). - * It is often better to call {@link #traverse(ObjectCodec)} to pass the codec explicitly. - */ - JsonParser traverse(); - - /** - * Same as {@link #traverse()}, but additionally passes {@link autosaveworld.zlibs.com.fasterxml.jackson.core.ObjectCodec} - * to use if {@link JsonParser#readValueAs(Class)} is used (otherwise caller must call - * {@link JsonParser#setCodec} on response explicitly). - *

- * NOTE: constructed parser instance will NOT initially point to a token, - * so before passing it to deserializers, it is typically necessary to - * advance it to the first available token by calling {@link JsonParser#nextToken()}. - * - * @since 2.1 - */ - JsonParser traverse(ObjectCodec codec); -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/Version.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/Version.java deleted file mode 100644 index 553606f5..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/Version.java +++ /dev/null @@ -1,141 +0,0 @@ -/* Jackson JSON-processor. - * - * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi - */ - -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -/** - * Object that encapsulates versioning information of a component. - * Version information includes not just version number but also - * optionally group and artifact ids of the component being versioned. - *

- * Note that optional group and artifact id properties are new with Jackson 2.0: - * if provided, they should align with Maven artifact information. - */ -public class Version - implements Comparable, java.io.Serializable -{ - private static final long serialVersionUID = 1L; - - private final static Version UNKNOWN_VERSION = new Version(0, 0, 0, null, null, null); - - protected final int _majorVersion; - - protected final int _minorVersion; - - protected final int _patchLevel; - - protected final String _groupId; - - protected final String _artifactId; - - /** - * Additional information for snapshot versions; null for non-snapshot - * (release) versions. - */ - protected final String _snapshotInfo; - - /** - * @deprecated Use variant that takes group and artifact ids - * - * @since 2.1 - */ - @Deprecated - public Version(int major, int minor, int patchLevel, String snapshotInfo) - { - this(major, minor, patchLevel, snapshotInfo, null, null); - } - - public Version(int major, int minor, int patchLevel, String snapshotInfo, - String groupId, String artifactId) - { - _majorVersion = major; - _minorVersion = minor; - _patchLevel = patchLevel; - _snapshotInfo = snapshotInfo; - _groupId = (groupId == null) ? "" : groupId; - _artifactId = (artifactId == null) ? "" : artifactId; - } - - /** - * Method returns canonical "not known" version, which is used as version - * in cases where actual version information is not known (instead of null). - */ - public static Version unknownVersion() { return UNKNOWN_VERSION; } - - /** - * @since 2.7 to replace misspelled {@link #isUknownVersion()} - */ - public boolean isUnknownVersion() { return (this == UNKNOWN_VERSION); } - - public boolean isSnapshot() { return (_snapshotInfo != null && _snapshotInfo.length() > 0); } - - /** - * @deprecated Since 2.7 use correctly spelled method {@link #isUnknownVersion()} - */ - @Deprecated - public boolean isUknownVersion() { return isUnknownVersion(); } - - public int getMajorVersion() { return _majorVersion; } - public int getMinorVersion() { return _minorVersion; } - public int getPatchLevel() { return _patchLevel; } - - public String getGroupId() { return _groupId; } - public String getArtifactId() { return _artifactId; } - - public String toFullString() { - return _groupId + '/' + _artifactId + '/' + toString(); - } - - @Override public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(_majorVersion).append('.'); - sb.append(_minorVersion).append('.'); - sb.append(_patchLevel); - if (isSnapshot()) { - sb.append('-').append(_snapshotInfo); - } - return sb.toString(); - } - - @Override public int hashCode() { - return _artifactId.hashCode() ^ _groupId.hashCode() + _majorVersion - _minorVersion + _patchLevel; - } - - @Override - public boolean equals(Object o) - { - if (o == this) return true; - if (o == null) return false; - if (o.getClass() != getClass()) return false; - Version other = (Version) o; - return (other._majorVersion == _majorVersion) - && (other._minorVersion == _minorVersion) - && (other._patchLevel == _patchLevel) - && other._artifactId.equals(_artifactId) - && other._groupId.equals(_groupId) - ; - } - - @Override - public int compareTo(Version other) - { - if (other == this) return 0; - - int diff = _groupId.compareTo(other._groupId); - if (diff == 0) { - diff = _artifactId.compareTo(other._artifactId); - if (diff == 0) { - diff = _majorVersion - other._majorVersion; - if (diff == 0) { - diff = _minorVersion - other._minorVersion; - if (diff == 0) { - diff = _patchLevel - other._patchLevel; - } - } - } - } - return diff; - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/Versioned.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/Versioned.java deleted file mode 100644 index bcecfe4d..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/Versioned.java +++ /dev/null @@ -1,23 +0,0 @@ -/* Jackson JSON-processor. - * - * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi - */ - -package autosaveworld.zlibs.com.fasterxml.jackson.core; - -/** - * Interface that those Jackson components that are explicitly versioned will implement. - * Intention is to allow both plug-in components (custom extensions) and applications and - * frameworks that use Jackson to detect exact version of Jackson in use. - * This may be useful for example for ensuring that proper Jackson version is deployed - * (beyond mechanisms that deployment system may have), as well as for possible - * workarounds. - */ -public interface Versioned { - /** - * Method called to detect version of the component that implements this interface; - * returned version should never be null, but may return specific "not available" - * instance (see {@link Version} for details). - */ - Version version(); -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/base/GeneratorBase.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/base/GeneratorBase.java deleted file mode 100644 index 41949c60..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/base/GeneratorBase.java +++ /dev/null @@ -1,486 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.base; - -import java.io.IOException; -import java.io.InputStream; -import java.math.BigDecimal; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.Base64Variant; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonStreamContext; -import autosaveworld.zlibs.com.fasterxml.jackson.core.ObjectCodec; -import autosaveworld.zlibs.com.fasterxml.jackson.core.PrettyPrinter; -import autosaveworld.zlibs.com.fasterxml.jackson.core.SerializableString; -import autosaveworld.zlibs.com.fasterxml.jackson.core.TreeNode; -import autosaveworld.zlibs.com.fasterxml.jackson.core.Version; -import autosaveworld.zlibs.com.fasterxml.jackson.core.json.DupDetector; -import autosaveworld.zlibs.com.fasterxml.jackson.core.json.JsonWriteContext; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.DefaultPrettyPrinter; - -/** - * This base class implements part of API that a JSON generator exposes - * to applications, adds shared internal methods that sub-classes - * can use and adds some abstract methods sub-classes must implement. - */ -public abstract class GeneratorBase extends JsonGenerator -{ - public final static int SURR1_FIRST = 0xD800; - public final static int SURR1_LAST = 0xDBFF; - public final static int SURR2_FIRST = 0xDC00; - public final static int SURR2_LAST = 0xDFFF; - - /** - * Set of feature masks related to features that need updates of other - * local configuration or state. - * - * @since 2.5 - */ - protected final static int DERIVED_FEATURES_MASK = - Feature.WRITE_NUMBERS_AS_STRINGS.getMask() - | Feature.ESCAPE_NON_ASCII.getMask() - | Feature.STRICT_DUPLICATE_DETECTION.getMask() - ; - - // // // Constants for validation messages (since 2.6) - - protected final static String WRITE_BINARY = "write a binary value"; - protected final static String WRITE_BOOLEAN = "write a boolean value"; - protected final static String WRITE_NULL = "write a null"; - protected final static String WRITE_NUMBER = "write a number"; - protected final static String WRITE_RAW = "write a raw (unencoded) value"; - protected final static String WRITE_STRING = "write a string"; - - /** - * This value is the limit of scale allowed for serializing {@link BigDecimal} - * in "plain" (non-engineering) notation; intent is to prevent asymmetric - * attack whereupon simple eng-notation with big scale is used to generate - * huge "plain" serialization. See [core#315] for details. - * - * @since 2.7.7 - */ - protected final static int MAX_BIG_DECIMAL_SCALE = 9999; - - /* - /********************************************************** - /* Configuration - /********************************************************** - */ - - protected ObjectCodec _objectCodec; - - /** - * Bit flag composed of bits that indicate which - * {@link autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator.Feature}s - * are enabled. - */ - protected int _features; - - /** - * Flag set to indicate that implicit conversion from number - * to JSON String is needed (as per - * {@link autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator.Feature#WRITE_NUMBERS_AS_STRINGS}). - */ - protected boolean _cfgNumbersAsStrings; - - /* - /********************************************************** - /* State - /********************************************************** - */ - - /** - * Object that keeps track of the current contextual state - * of the generator. - */ - protected JsonWriteContext _writeContext; - - /** - * Flag that indicates whether generator is closed or not. Gets - * set when it is closed by an explicit call - * ({@link #close}). - */ - protected boolean _closed; - - /* - /********************************************************** - /* Life-cycle - /********************************************************** - */ - - protected GeneratorBase(int features, ObjectCodec codec) { - super(); - _features = features; - _objectCodec = codec; - DupDetector dups = Feature.STRICT_DUPLICATE_DETECTION.enabledIn(features) - ? DupDetector.rootDetector(this) : null; - _writeContext = JsonWriteContext.createRootContext(dups); - _cfgNumbersAsStrings = Feature.WRITE_NUMBERS_AS_STRINGS.enabledIn(features); - } - - /** - * @since 2.5 - */ - protected GeneratorBase(int features, ObjectCodec codec, JsonWriteContext ctxt) { - super(); - _features = features; - _objectCodec = codec; - _writeContext = ctxt; - _cfgNumbersAsStrings = Feature.WRITE_NUMBERS_AS_STRINGS.enabledIn(features); - } - - /** - * Implemented with standard version number detection algorithm, typically using - * a simple generated class, with information extracted from Maven project file - * during build. - */ - @Override public Version version() { return Version.unknownVersion(); } - - @Override - public Object getCurrentValue() { - return _writeContext.getCurrentValue(); - } - - @Override - public void setCurrentValue(Object v) { - _writeContext.setCurrentValue(v); - } - - /* - /********************************************************** - /* Configuration - /********************************************************** - */ - - - @Override public final boolean isEnabled(Feature f) { return (_features & f.getMask()) != 0; } - @Override public int getFeatureMask() { return _features; } - - //public JsonGenerator configure(Feature f, boolean state) { } - - @Override - public JsonGenerator enable(Feature f) { - final int mask = f.getMask(); - _features |= mask; - if ((mask & DERIVED_FEATURES_MASK) != 0) { - // why not switch? Requires addition of a generated class, alas - if (f == Feature.WRITE_NUMBERS_AS_STRINGS) { - _cfgNumbersAsStrings = true; - } else if (f == Feature.ESCAPE_NON_ASCII) { - setHighestNonEscapedChar(127); - } else if (f == Feature.STRICT_DUPLICATE_DETECTION) { - if (_writeContext.getDupDetector() == null) { // but only if disabled currently - _writeContext = _writeContext.withDupDetector(DupDetector.rootDetector(this)); - } - } - } - return this; - } - - @Override - public JsonGenerator disable(Feature f) { - final int mask = f.getMask(); - _features &= ~mask; - if ((mask & DERIVED_FEATURES_MASK) != 0) { - if (f == Feature.WRITE_NUMBERS_AS_STRINGS) { - _cfgNumbersAsStrings = false; - } else if (f == Feature.ESCAPE_NON_ASCII) { - setHighestNonEscapedChar(0); - } else if (f == Feature.STRICT_DUPLICATE_DETECTION) { - _writeContext = _writeContext.withDupDetector(null); - } - } - return this; - } - - @Override - @Deprecated - public JsonGenerator setFeatureMask(int newMask) { - int changed = newMask ^ _features; - _features = newMask; - if (changed != 0) { - _checkStdFeatureChanges(newMask, changed); - } - return this; - } - - @Override // since 2.7 - public JsonGenerator overrideStdFeatures(int values, int mask) { - int oldState = _features; - int newState = (oldState & ~mask) | (values & mask); - int changed = oldState ^ newState; - if (changed != 0) { - _features = newState; - _checkStdFeatureChanges(newState, changed); - } - return this; - } - - /** - * Helper method called to verify changes to standard features. - * - * @param newFeatureFlags Bitflag of standard features after they were changed - * @param changedFeatures Bitflag of standard features for which setting - * did change - * - * @since 2.7 - */ - protected void _checkStdFeatureChanges(int newFeatureFlags, int changedFeatures) - { - if ((changedFeatures & DERIVED_FEATURES_MASK) == 0) { - return; - } - _cfgNumbersAsStrings = Feature.WRITE_NUMBERS_AS_STRINGS.enabledIn(newFeatureFlags); - if (Feature.ESCAPE_NON_ASCII.enabledIn(changedFeatures)) { - if (Feature.ESCAPE_NON_ASCII.enabledIn(newFeatureFlags)) { - setHighestNonEscapedChar(127); - } else { - setHighestNonEscapedChar(0); - } - } - if (Feature.STRICT_DUPLICATE_DETECTION.enabledIn(changedFeatures)) { - if (Feature.STRICT_DUPLICATE_DETECTION.enabledIn(newFeatureFlags)) { // enabling - if (_writeContext.getDupDetector() == null) { // but only if disabled currently - _writeContext = _writeContext.withDupDetector(DupDetector.rootDetector(this)); - } - } else { // disabling - _writeContext = _writeContext.withDupDetector(null); - } - } - } - - @Override public JsonGenerator useDefaultPrettyPrinter() { - // Should not override a pretty printer if one already assigned. - if (getPrettyPrinter() != null) { - return this; - } - return setPrettyPrinter(_constructDefaultPrettyPrinter()); - } - - @Override public JsonGenerator setCodec(ObjectCodec oc) { - _objectCodec = oc; - return this; - } - - @Override public ObjectCodec getCodec() { return _objectCodec; } - - /* - /********************************************************** - /* Public API, accessors - /********************************************************** - */ - - /** - * Note: type was co-variant until Jackson 2.7; reverted back to - * base type in 2.8 to allow for overriding by subtypes that use - * custom context type. - */ - @Override public JsonStreamContext getOutputContext() { return _writeContext; } - - /* - /********************************************************** - /* Public API, write methods, structural - /********************************************************** - */ - - //public void writeStartArray() throws IOException - //public void writeEndArray() throws IOException - //public void writeStartObject() throws IOException - //public void writeEndObject() throws IOException - - @Override // since 2.8 - public void writeStartObject(Object forValue) throws IOException - { - writeStartObject(); - if ((_writeContext != null) && (forValue != null)) { - _writeContext.setCurrentValue(forValue); - } - setCurrentValue(forValue); - } - - /* - /********************************************************** - /* Public API, write methods, textual - /********************************************************** - */ - - @Override public void writeFieldName(SerializableString name) throws IOException { - writeFieldName(name.getValue()); - } - - //public abstract void writeString(String text) throws IOException; - - //public abstract void writeString(char[] text, int offset, int len) throws IOException; - - //public abstract void writeRaw(String text) throws IOException,; - - //public abstract void writeRaw(char[] text, int offset, int len) throws IOException; - - @Override - public void writeString(SerializableString text) throws IOException { - writeString(text.getValue()); - } - - @Override public void writeRawValue(String text) throws IOException { - _verifyValueWrite("write raw value"); - writeRaw(text); - } - - @Override public void writeRawValue(String text, int offset, int len) throws IOException { - _verifyValueWrite("write raw value"); - writeRaw(text, offset, len); - } - - @Override public void writeRawValue(char[] text, int offset, int len) throws IOException { - _verifyValueWrite("write raw value"); - writeRaw(text, offset, len); - } - - @Override public void writeRawValue(SerializableString text) throws IOException { - _verifyValueWrite("write raw value"); - writeRaw(text); - } - - @Override - public int writeBinary(Base64Variant b64variant, InputStream data, int dataLength) throws IOException { - // Let's implement this as "unsupported" to make it easier to add new parser impls - _reportUnsupportedOperation(); - return 0; - } - - /* - /********************************************************** - /* Public API, write methods, primitive - /********************************************************** - */ - - // Not implemented at this level, added as placeholders - - /* - public abstract void writeNumber(int i) - public abstract void writeNumber(long l) - public abstract void writeNumber(double d) - public abstract void writeNumber(float f) - public abstract void writeNumber(BigDecimal dec) - public abstract void writeBoolean(boolean state) - public abstract void writeNull() - */ - - /* - /********************************************************** - /* Public API, write methods, POJOs, trees - /********************************************************** - */ - - @Override - public void writeObject(Object value) throws IOException { - if (value == null) { - // important: call method that does check value write: - writeNull(); - } else { - /* 02-Mar-2009, tatu: we are NOT to call _verifyValueWrite here, - * because that will be done when codec actually serializes - * contained POJO. If we did call it it would advance state - * causing exception later on - */ - if (_objectCodec != null) { - _objectCodec.writeValue(this, value); - return; - } - _writeSimpleObject(value); - } - } - - @Override - public void writeTree(TreeNode rootNode) throws IOException { - // As with 'writeObject()', we are not check if write would work - if (rootNode == null) { - writeNull(); - } else { - if (_objectCodec == null) { - throw new IllegalStateException("No ObjectCodec defined"); - } - _objectCodec.writeValue(this, rootNode); - } - } - - /* - /********************************************************** - /* Public API, low-level output handling - /********************************************************** - */ - - @Override public abstract void flush() throws IOException; - @Override public void close() throws IOException { _closed = true; } - @Override public boolean isClosed() { return _closed; } - - /* - /********************************************************** - /* Package methods for this, sub-classes - /********************************************************** - */ - - /** - * Method called to release any buffers generator may be holding, - * once generator is being closed. - */ - protected abstract void _releaseBuffers(); - - /** - * Method called before trying to write a value (scalar or structured), - * to verify that this is legal in current output state, as well as to - * output separators if and as necessary. - * - * @param typeMsg Additional message used for generating exception message - * if value output is NOT legal in current generator output state. - */ - protected abstract void _verifyValueWrite(String typeMsg) throws IOException; - - /** - * Overridable factory method called to instantiate an appropriate {@link PrettyPrinter} - * for case of "just use the default one", when {@link #useDefaultPrettyPrinter()} is called. - * - * @since 2.6 - */ - protected PrettyPrinter _constructDefaultPrettyPrinter() { - return new DefaultPrettyPrinter(); - } - - /** - * Helper method used to serialize a {@link java.math.BigDecimal} as a String, - * for serialization, taking into account configuration settings - * - * @since 2.7.7 - */ - protected String _asString(BigDecimal value) throws IOException { - if (Feature.WRITE_BIGDECIMAL_AS_PLAIN.enabledIn(_features)) { - // 24-Aug-2016, tatu: [core#315] prevent possible DoS vector - int scale = value.scale(); - if ((scale < -MAX_BIG_DECIMAL_SCALE) || (scale > MAX_BIG_DECIMAL_SCALE)) { - _reportError(String.format( -"Attempt to write plain `java.math.BigDecimal` (see JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN) with illegal scale (%d): needs to be between [-%d, %d]", -scale, MAX_BIG_DECIMAL_SCALE, MAX_BIG_DECIMAL_SCALE)); - } - return value.toPlainString(); - } - return value.toString(); - } - - /* - /********************************************************** - /* UTF-8 related helper method(s) - /********************************************************** - */ - - /** - * @since 2.5 - */ - protected final int _decodeSurrogate(int surr1, int surr2) throws IOException - { - // First is known to be valid, but how about the other? - if (surr2 < SURR2_FIRST || surr2 > SURR2_LAST) { - String msg = "Incomplete surrogate pair: first char 0x"+Integer.toHexString(surr1)+", second 0x"+Integer.toHexString(surr2); - _reportError(msg); - } - int c = 0x10000 + ((surr1 - SURR1_FIRST) << 10) + (surr2 - SURR2_FIRST); - return c; - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/base/ParserBase.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/base/ParserBase.java deleted file mode 100644 index 271d7465..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/base/ParserBase.java +++ /dev/null @@ -1,1177 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.base; - -import java.io.IOException; -import java.math.BigDecimal; -import java.math.BigInteger; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.Base64Variant; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonLocation; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; -import autosaveworld.zlibs.com.fasterxml.jackson.core.Version; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.IOContext; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.NumberInput; -import autosaveworld.zlibs.com.fasterxml.jackson.core.json.DupDetector; -import autosaveworld.zlibs.com.fasterxml.jackson.core.json.JsonReadContext; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.ByteArrayBuilder; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.TextBuffer; - -/** - * Intermediate base class used by all Jackson {@link JsonParser} - * implementations. Contains most common things that are independent - * of actual underlying input source. - */ -public abstract class ParserBase extends ParserMinimalBase -{ - /* - /********************************************************** - /* Generic I/O state - /********************************************************** - */ - - /** - * I/O context for this reader. It handles buffer allocation - * for the reader. - */ - final protected IOContext _ioContext; - - /** - * Flag that indicates whether parser is closed or not. Gets - * set when parser is either closed by explicit call - * ({@link #close}) or when end-of-input is reached. - */ - protected boolean _closed; - - /* - /********************************************************** - /* Current input data - /********************************************************** - */ - - // Note: type of actual buffer depends on sub-class, can't include - - /** - * Pointer to next available character in buffer - */ - protected int _inputPtr; - - /** - * Index of character after last available one in the buffer. - */ - protected int _inputEnd; - - /* - /********************************************************** - /* Current input location information - /********************************************************** - */ - - /** - * Number of characters/bytes that were contained in previous blocks - * (blocks that were already processed prior to the current buffer). - */ - protected long _currInputProcessed; - - /** - * Current row location of current point in input buffer, starting - * from 1, if available. - */ - protected int _currInputRow = 1; - - /** - * Current index of the first character of the current row in input - * buffer. Needed to calculate column position, if necessary; benefit - * of not having column itself is that this only has to be updated - * once per line. - */ - protected int _currInputRowStart; - - /* - /********************************************************** - /* Information about starting location of event - /* Reader is pointing to; updated on-demand - /********************************************************** - */ - - // // // Location info at point when current token was started - - /** - * Total number of bytes/characters read before start of current token. - * For big (gigabyte-sized) sizes are possible, needs to be long, - * unlike pointers and sizes related to in-memory buffers. - */ - protected long _tokenInputTotal; - - /** - * Input row on which current token starts, 1-based - */ - protected int _tokenInputRow = 1; - - /** - * Column on input row that current token starts; 0-based (although - * in the end it'll be converted to 1-based) - */ - protected int _tokenInputCol; - - /* - /********************************************************** - /* Parsing state - /********************************************************** - */ - - /** - * Information about parser context, context in which - * the next token is to be parsed (root, array, object). - */ - protected JsonReadContext _parsingContext; - - /** - * Secondary token related to the next token after current one; - * used if its type is known. This may be value token that - * follows FIELD_NAME, for example. - */ - protected JsonToken _nextToken; - - /* - /********************************************************** - /* Buffer(s) for local name(s) and text content - /********************************************************** - */ - - /** - * Buffer that contains contents of String values, including - * field names if necessary (name split across boundary, - * contains escape sequence, or access needed to char array) - */ - protected final TextBuffer _textBuffer; - - /** - * Temporary buffer that is needed if field name is accessed - * using {@link #getTextCharacters} method (instead of String - * returning alternatives) - */ - protected char[] _nameCopyBuffer; - - /** - * Flag set to indicate whether the field name is available - * from the name copy buffer or not (in addition to its String - * representation being available via read context) - */ - protected boolean _nameCopied; - - /** - * ByteArrayBuilder is needed if 'getBinaryValue' is called. If so, - * we better reuse it for remainder of content. - */ - protected ByteArrayBuilder _byteArrayBuilder; - - /** - * We will hold on to decoded binary data, for duration of - * current event, so that multiple calls to - * {@link #getBinaryValue} will not need to decode data more - * than once. - */ - protected byte[] _binaryValue; - - /* - /********************************************************** - /* Constants and fields of former 'JsonNumericParserBase' - /********************************************************** - */ - - final protected static int NR_UNKNOWN = 0; - - // First, integer types - - final protected static int NR_INT = 0x0001; - final protected static int NR_LONG = 0x0002; - final protected static int NR_BIGINT = 0x0004; - - // And then floating point types - - final protected static int NR_DOUBLE = 0x008; - final protected static int NR_BIGDECIMAL = 0x0010; - - // Also, we need some numeric constants - - final static BigInteger BI_MIN_INT = BigInteger.valueOf(Integer.MIN_VALUE); - final static BigInteger BI_MAX_INT = BigInteger.valueOf(Integer.MAX_VALUE); - - final static BigInteger BI_MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE); - final static BigInteger BI_MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE); - - final static BigDecimal BD_MIN_LONG = new BigDecimal(BI_MIN_LONG); - final static BigDecimal BD_MAX_LONG = new BigDecimal(BI_MAX_LONG); - - final static BigDecimal BD_MIN_INT = new BigDecimal(BI_MIN_INT); - final static BigDecimal BD_MAX_INT = new BigDecimal(BI_MAX_INT); - - final static long MIN_INT_L = (long) Integer.MIN_VALUE; - final static long MAX_INT_L = (long) Integer.MAX_VALUE; - - // These are not very accurate, but have to do... (for bounds checks) - - final static double MIN_LONG_D = (double) Long.MIN_VALUE; - final static double MAX_LONG_D = (double) Long.MAX_VALUE; - - final static double MIN_INT_D = (double) Integer.MIN_VALUE; - final static double MAX_INT_D = (double) Integer.MAX_VALUE; - - // Digits, numeric - final protected static int INT_0 = '0'; - final protected static int INT_9 = '9'; - - final protected static int INT_MINUS = '-'; - final protected static int INT_PLUS = '+'; - - final protected static char CHAR_NULL = '\0'; - - // Numeric value holders: multiple fields used for - // for efficiency - - /** - * Bitfield that indicates which numeric representations - * have been calculated for the current type - */ - protected int _numTypesValid = NR_UNKNOWN; - - // First primitives - - protected int _numberInt; - - protected long _numberLong; - - protected double _numberDouble; - - // And then object types - - protected BigInteger _numberBigInt; - - protected BigDecimal _numberBigDecimal; - - // And then other information about value itself - - /** - * Flag that indicates whether numeric value has a negative - * value. That is, whether its textual representation starts - * with minus character. - */ - protected boolean _numberNegative; - - /** - * Length of integer part of the number, in characters - */ - protected int _intLength; - - /** - * Length of the fractional part (not including decimal - * point or exponent), in characters. - * Not used for pure integer values. - */ - protected int _fractLength; - - /** - * Length of the exponent part of the number, if any, not - * including 'e' marker or sign, just digits. - * Not used for pure integer values. - */ - protected int _expLength; - - /* - /********************************************************** - /* Life-cycle - /********************************************************** - */ - - protected ParserBase(IOContext ctxt, int features) { - super(features); - _ioContext = ctxt; - _textBuffer = ctxt.constructTextBuffer(); - DupDetector dups = Feature.STRICT_DUPLICATE_DETECTION.enabledIn(features) - ? DupDetector.rootDetector(this) : null; - _parsingContext = JsonReadContext.createRootContext(dups); - } - - @Override public Version version() { return Version.unknownVersion(); } - - @Override - public Object getCurrentValue() { - return _parsingContext.getCurrentValue(); - } - - @Override - public void setCurrentValue(Object v) { - _parsingContext.setCurrentValue(v); - } - - /* - /********************************************************** - /* Overrides for Feature handling - /********************************************************** - */ - - @Override - public JsonParser enable(Feature f) { - _features |= f.getMask(); - if (f == Feature.STRICT_DUPLICATE_DETECTION) { // enabling dup detection? - if (_parsingContext.getDupDetector() == null) { // but only if disabled currently - _parsingContext = _parsingContext.withDupDetector(DupDetector.rootDetector(this)); - } - } - return this; - } - - @Override - public JsonParser disable(Feature f) { - _features &= ~f.getMask(); - if (f == Feature.STRICT_DUPLICATE_DETECTION) { - _parsingContext = _parsingContext.withDupDetector(null); - } - return this; - } - - @Override - @Deprecated - public JsonParser setFeatureMask(int newMask) { - int changes = (_features ^ newMask); - if (changes != 0) { - _features = newMask; - _checkStdFeatureChanges(newMask, changes); - } - return this; - } - - @Override // since 2.7 - public JsonParser overrideStdFeatures(int values, int mask) { - int oldState = _features; - int newState = (oldState & ~mask) | (values & mask); - int changed = oldState ^ newState; - if (changed != 0) { - _features = newState; - _checkStdFeatureChanges(newState, changed); - } - return this; - } - - /** - * Helper method called to verify changes to standard features. - * - * @param newFeatureFlags Bitflag of standard features after they were changed - * @param changedFeatures Bitflag of standard features for which setting - * did change - * - * @since 2.7 - */ - protected void _checkStdFeatureChanges(int newFeatureFlags, int changedFeatures) - { - int f = Feature.STRICT_DUPLICATE_DETECTION.getMask(); - - if ((changedFeatures & f) != 0) { - if ((newFeatureFlags & f) != 0) { - if (_parsingContext.getDupDetector() == null) { - _parsingContext = _parsingContext.withDupDetector(DupDetector.rootDetector(this)); - } else { // disabling - _parsingContext = _parsingContext.withDupDetector(null); - } - } - } - } - - /* - /********************************************************** - /* JsonParser impl - /********************************************************** - */ - - /** - * Method that can be called to get the name associated with - * the current event. - */ - @Override public String getCurrentName() throws IOException { - // [JACKSON-395]: start markers require information from parent - if (_currToken == JsonToken.START_OBJECT || _currToken == JsonToken.START_ARRAY) { - JsonReadContext parent = _parsingContext.getParent(); - if (parent != null) { - return parent.getCurrentName(); - } - } - return _parsingContext.getCurrentName(); - } - - @Override public void overrideCurrentName(String name) { - // Simple, but need to look for START_OBJECT/ARRAY's "off-by-one" thing: - JsonReadContext ctxt = _parsingContext; - if (_currToken == JsonToken.START_OBJECT || _currToken == JsonToken.START_ARRAY) { - ctxt = ctxt.getParent(); - } - /* 24-Sep-2013, tatu: Unfortunate, but since we did not expose exceptions, - * need to wrap this here - */ - try { - ctxt.setCurrentName(name); - } catch (IOException e) { - throw new IllegalStateException(e); - } - } - - @Override public void close() throws IOException { - if (!_closed) { - _closed = true; - try { - _closeInput(); - } finally { - // as per [JACKSON-324], do in finally block - // Also, internal buffer(s) can now be released as well - _releaseBuffers(); - } - } - } - - @Override public boolean isClosed() { return _closed; } - @Override public JsonReadContext getParsingContext() { return _parsingContext; } - - /** - * Method that return the starting location of the current - * token; that is, position of the first character from input - * that starts the current token. - */ - @Override - public JsonLocation getTokenLocation() { - return new JsonLocation(_ioContext.getSourceReference(), - -1L, getTokenCharacterOffset(), // bytes, chars - getTokenLineNr(), - getTokenColumnNr()); - } - - /** - * Method that returns location of the last processed character; - * usually for error reporting purposes - */ - @Override - public JsonLocation getCurrentLocation() { - int col = _inputPtr - _currInputRowStart + 1; // 1-based - return new JsonLocation(_ioContext.getSourceReference(), - -1L, _currInputProcessed + _inputPtr, // bytes, chars - _currInputRow, col); - } - - /* - /********************************************************** - /* Public API, access to token information, text and similar - /********************************************************** - */ - - @Override - public boolean hasTextCharacters() { - if (_currToken == JsonToken.VALUE_STRING) { return true; } // usually true - if (_currToken == JsonToken.FIELD_NAME) { return _nameCopied; } - return false; - } - - @Override // since 2.7 - public byte[] getBinaryValue(Base64Variant variant) throws IOException - { - if (_binaryValue == null) { - if (_currToken != JsonToken.VALUE_STRING) { - _reportError("Current token ("+_currToken+") not VALUE_STRING, can not access as binary"); - } - ByteArrayBuilder builder = _getByteArrayBuilder(); - _decodeBase64(getText(), builder, variant); - _binaryValue = builder.toByteArray(); - } - return _binaryValue; - } - - /* - /********************************************************** - /* Public low-level accessors - /********************************************************** - */ - - public long getTokenCharacterOffset() { return _tokenInputTotal; } - public int getTokenLineNr() { return _tokenInputRow; } - public int getTokenColumnNr() { - // note: value of -1 means "not available"; otherwise convert from 0-based to 1-based - int col = _tokenInputCol; - return (col < 0) ? col : (col + 1); - } - - /* - /********************************************************** - /* Abstract methods needed from sub-classes - /********************************************************** - */ - - protected abstract void _closeInput() throws IOException; - - /* - /********************************************************** - /* Low-level reading, other - /********************************************************** - */ - - /** - * Method called to release internal buffers owned by the base - * reader. This may be called along with {@link #_closeInput} (for - * example, when explicitly closing this reader instance), or - * separately (if need be). - */ - protected void _releaseBuffers() throws IOException { - _textBuffer.releaseBuffers(); - char[] buf = _nameCopyBuffer; - if (buf != null) { - _nameCopyBuffer = null; - _ioContext.releaseNameCopyBuffer(buf); - } - } - - /** - * Method called when an EOF is encountered between tokens. - * If so, it may be a legitimate EOF, but only iff there - * is no open non-root context. - */ - @Override - protected void _handleEOF() throws JsonParseException { - if (!_parsingContext.inRoot()) { - String marker = _parsingContext.inArray() ? "Array" : "Object"; - _reportInvalidEOF(String.format( - ": expected close marker for %s (start marker at %s)", - marker, - _parsingContext.getStartLocation(_ioContext.getSourceReference())), - null); - } - } - - /** - * @since 2.4 - */ - protected final int _eofAsNextChar() throws JsonParseException { - _handleEOF(); - return -1; - } - - /* - /********************************************************** - /* Internal/package methods: Error reporting - /********************************************************** - */ - - protected void _reportMismatchedEndMarker(int actCh, char expCh) throws JsonParseException { - String startDesc = ""+_parsingContext.getStartLocation(_ioContext.getSourceReference()); - _reportError("Unexpected close marker '"+((char) actCh)+"': expected '"+expCh+"' (for "+_parsingContext.typeDesc()+" starting at "+startDesc+")"); - } - - /* - /********************************************************** - /* Internal/package methods: shared/reusable builders - /********************************************************** - */ - - public ByteArrayBuilder _getByteArrayBuilder() - { - if (_byteArrayBuilder == null) { - _byteArrayBuilder = new ByteArrayBuilder(); - } else { - _byteArrayBuilder.reset(); - } - return _byteArrayBuilder; - } - - /* - /********************************************************** - /* Methods from former JsonNumericParserBase - /********************************************************** - */ - - // // // Life-cycle of number-parsing - - protected final JsonToken reset(boolean negative, int intLen, int fractLen, int expLen) - { - if (fractLen < 1 && expLen < 1) { // integer - return resetInt(negative, intLen); - } - return resetFloat(negative, intLen, fractLen, expLen); - } - - protected final JsonToken resetInt(boolean negative, int intLen) - { - _numberNegative = negative; - _intLength = intLen; - _fractLength = 0; - _expLength = 0; - _numTypesValid = NR_UNKNOWN; // to force parsing - return JsonToken.VALUE_NUMBER_INT; - } - - protected final JsonToken resetFloat(boolean negative, int intLen, int fractLen, int expLen) - { - _numberNegative = negative; - _intLength = intLen; - _fractLength = fractLen; - _expLength = expLen; - _numTypesValid = NR_UNKNOWN; // to force parsing - return JsonToken.VALUE_NUMBER_FLOAT; - } - - protected final JsonToken resetAsNaN(String valueStr, double value) - { - _textBuffer.resetWithString(valueStr); - _numberDouble = value; - _numTypesValid = NR_DOUBLE; - return JsonToken.VALUE_NUMBER_FLOAT; - } - - /* - /********************************************************** - /* Numeric accessors of public API - /********************************************************** - */ - - @Override - public Number getNumberValue() throws IOException - { - if (_numTypesValid == NR_UNKNOWN) { - _parseNumericValue(NR_UNKNOWN); // will also check event type - } - // Separate types for int types - if (_currToken == JsonToken.VALUE_NUMBER_INT) { - if ((_numTypesValid & NR_INT) != 0) { - return _numberInt; - } - if ((_numTypesValid & NR_LONG) != 0) { - return _numberLong; - } - if ((_numTypesValid & NR_BIGINT) != 0) { - return _numberBigInt; - } - // Shouldn't get this far but if we do - return _numberBigDecimal; - } - - /* And then floating point types. But here optimal type - * needs to be big decimal, to avoid losing any data? - */ - if ((_numTypesValid & NR_BIGDECIMAL) != 0) { - return _numberBigDecimal; - } - if ((_numTypesValid & NR_DOUBLE) == 0) { // sanity check - _throwInternal(); - } - return _numberDouble; - } - - @Override - public NumberType getNumberType() throws IOException - { - if (_numTypesValid == NR_UNKNOWN) { - _parseNumericValue(NR_UNKNOWN); // will also check event type - } - if (_currToken == JsonToken.VALUE_NUMBER_INT) { - if ((_numTypesValid & NR_INT) != 0) { - return NumberType.INT; - } - if ((_numTypesValid & NR_LONG) != 0) { - return NumberType.LONG; - } - return NumberType.BIG_INTEGER; - } - - /* And then floating point types. Here optimal type - * needs to be big decimal, to avoid losing any data? - * However... using BD is slow, so let's allow returning - * double as type if no explicit call has been made to access - * data as BD? - */ - if ((_numTypesValid & NR_BIGDECIMAL) != 0) { - return NumberType.BIG_DECIMAL; - } - return NumberType.DOUBLE; - } - - @Override - public int getIntValue() throws IOException - { - if ((_numTypesValid & NR_INT) == 0) { - if (_numTypesValid == NR_UNKNOWN) { // not parsed at all - return _parseIntValue(); - } - if ((_numTypesValid & NR_INT) == 0) { // wasn't an int natively? - convertNumberToInt(); // let's make it so, if possible - } - } - return _numberInt; - } - - @Override - public long getLongValue() throws IOException - { - if ((_numTypesValid & NR_LONG) == 0) { - if (_numTypesValid == NR_UNKNOWN) { - _parseNumericValue(NR_LONG); - } - if ((_numTypesValid & NR_LONG) == 0) { - convertNumberToLong(); - } - } - return _numberLong; - } - - @Override - public BigInteger getBigIntegerValue() throws IOException - { - if ((_numTypesValid & NR_BIGINT) == 0) { - if (_numTypesValid == NR_UNKNOWN) { - _parseNumericValue(NR_BIGINT); - } - if ((_numTypesValid & NR_BIGINT) == 0) { - convertNumberToBigInteger(); - } - } - return _numberBigInt; - } - - @Override - public float getFloatValue() throws IOException - { - double value = getDoubleValue(); - /* 22-Jan-2009, tatu: Bounds/range checks would be tricky - * here, so let's not bother even trying... - */ - /* - if (value < -Float.MAX_VALUE || value > MAX_FLOAT_D) { - _reportError("Numeric value ("+getText()+") out of range of Java float"); - } - */ - return (float) value; - } - - @Override - public double getDoubleValue() throws IOException - { - if ((_numTypesValid & NR_DOUBLE) == 0) { - if (_numTypesValid == NR_UNKNOWN) { - _parseNumericValue(NR_DOUBLE); - } - if ((_numTypesValid & NR_DOUBLE) == 0) { - convertNumberToDouble(); - } - } - return _numberDouble; - } - - @Override - public BigDecimal getDecimalValue() throws IOException - { - if ((_numTypesValid & NR_BIGDECIMAL) == 0) { - if (_numTypesValid == NR_UNKNOWN) { - _parseNumericValue(NR_BIGDECIMAL); - } - if ((_numTypesValid & NR_BIGDECIMAL) == 0) { - convertNumberToBigDecimal(); - } - } - return _numberBigDecimal; - } - - /* - /********************************************************** - /* Conversion from textual to numeric representation - /********************************************************** - */ - - /** - * Method that will parse actual numeric value out of a syntactically - * valid number value. Type it will parse into depends on whether - * it is a floating point number, as well as its magnitude: smallest - * legal type (of ones available) is used for efficiency. - * - * @param expType Numeric type that we will immediately need, if any; - * mostly necessary to optimize handling of floating point numbers - */ - protected void _parseNumericValue(int expType) throws IOException - { - // Int or float? - if (_currToken == JsonToken.VALUE_NUMBER_INT) { - char[] buf = _textBuffer.getTextBuffer(); - int offset = _textBuffer.getTextOffset(); - int len = _intLength; - if (_numberNegative) { - ++offset; - } - if (len <= 9) { // definitely fits in int - int i = NumberInput.parseInt(buf, offset, len); - _numberInt = _numberNegative ? -i : i; - _numTypesValid = NR_INT; - return; - } - if (len <= 18) { // definitely fits AND is easy to parse using 2 int parse calls - long l = NumberInput.parseLong(buf, offset, len); - if (_numberNegative) { - l = -l; - } - // [JACKSON-230] Could still fit in int, need to check - if (len == 10) { - if (_numberNegative) { - if (l >= MIN_INT_L) { - _numberInt = (int) l; - _numTypesValid = NR_INT; - return; - } - } else { - if (l <= MAX_INT_L) { - _numberInt = (int) l; - _numTypesValid = NR_INT; - return; - } - } - } - _numberLong = l; - _numTypesValid = NR_LONG; - return; - } - _parseSlowInt(expType, buf, offset, len); - return; - } - if (_currToken == JsonToken.VALUE_NUMBER_FLOAT) { - _parseSlowFloat(expType); - return; - } - _reportError("Current token ("+_currToken+") not numeric, can not use numeric value accessors"); - } - - /** - * @since 2.6 - */ - protected int _parseIntValue() throws IOException - { - // Inlined variant of: _parseNumericValue(NR_INT) - - if (_currToken == JsonToken.VALUE_NUMBER_INT) { - char[] buf = _textBuffer.getTextBuffer(); - int offset = _textBuffer.getTextOffset(); - int len = _intLength; - if (_numberNegative) { - ++offset; - } - if (len <= 9) { - int i = NumberInput.parseInt(buf, offset, len); - if (_numberNegative) { - i = -i; - } - _numberInt = i; - _numTypesValid = NR_INT; - return i; - } - } - _parseNumericValue(NR_INT); - if ((_numTypesValid & NR_INT) == 0) { - convertNumberToInt(); - } - return _numberInt; - } - - private void _parseSlowFloat(int expType) throws IOException - { - /* Nope: floating point. Here we need to be careful to get - * optimal parsing strategy: choice is between accurate but - * slow (BigDecimal) and lossy but fast (Double). For now - * let's only use BD when explicitly requested -- it can - * still be constructed correctly at any point since we do - * retain textual representation - */ - try { - if (expType == NR_BIGDECIMAL) { - _numberBigDecimal = _textBuffer.contentsAsDecimal(); - _numTypesValid = NR_BIGDECIMAL; - } else { - // Otherwise double has to do - _numberDouble = _textBuffer.contentsAsDouble(); - _numTypesValid = NR_DOUBLE; - } - } catch (NumberFormatException nex) { - // Can this ever occur? Due to overflow, maybe? - _wrapError("Malformed numeric value '"+_textBuffer.contentsAsString()+"'", nex); - } - } - - private void _parseSlowInt(int expType, char[] buf, int offset, int len) throws IOException - { - String numStr = _textBuffer.contentsAsString(); - try { - // [JACKSON-230] Some long cases still... - if (NumberInput.inLongRange(buf, offset, len, _numberNegative)) { - // Probably faster to construct a String, call parse, than to use BigInteger - _numberLong = Long.parseLong(numStr); - _numTypesValid = NR_LONG; - } else { - // nope, need the heavy guns... (rare case) - _numberBigInt = new BigInteger(numStr); - _numTypesValid = NR_BIGINT; - } - } catch (NumberFormatException nex) { - // Can this ever occur? Due to overflow, maybe? - _wrapError("Malformed numeric value '"+numStr+"'", nex); - } - } - - /* - /********************************************************** - /* Numeric conversions - /********************************************************** - */ - - protected void convertNumberToInt() throws IOException - { - // First, converting from long ought to be easy - if ((_numTypesValid & NR_LONG) != 0) { - // Let's verify it's lossless conversion by simple roundtrip - int result = (int) _numberLong; - if (((long) result) != _numberLong) { - _reportError("Numeric value ("+getText()+") out of range of int"); - } - _numberInt = result; - } else if ((_numTypesValid & NR_BIGINT) != 0) { - if (BI_MIN_INT.compareTo(_numberBigInt) > 0 - || BI_MAX_INT.compareTo(_numberBigInt) < 0) { - reportOverflowInt(); - } - _numberInt = _numberBigInt.intValue(); - } else if ((_numTypesValid & NR_DOUBLE) != 0) { - // Need to check boundaries - if (_numberDouble < MIN_INT_D || _numberDouble > MAX_INT_D) { - reportOverflowInt(); - } - _numberInt = (int) _numberDouble; - } else if ((_numTypesValid & NR_BIGDECIMAL) != 0) { - if (BD_MIN_INT.compareTo(_numberBigDecimal) > 0 - || BD_MAX_INT.compareTo(_numberBigDecimal) < 0) { - reportOverflowInt(); - } - _numberInt = _numberBigDecimal.intValue(); - } else { - _throwInternal(); - } - _numTypesValid |= NR_INT; - } - - protected void convertNumberToLong() throws IOException - { - if ((_numTypesValid & NR_INT) != 0) { - _numberLong = (long) _numberInt; - } else if ((_numTypesValid & NR_BIGINT) != 0) { - if (BI_MIN_LONG.compareTo(_numberBigInt) > 0 - || BI_MAX_LONG.compareTo(_numberBigInt) < 0) { - reportOverflowLong(); - } - _numberLong = _numberBigInt.longValue(); - } else if ((_numTypesValid & NR_DOUBLE) != 0) { - // Need to check boundaries - if (_numberDouble < MIN_LONG_D || _numberDouble > MAX_LONG_D) { - reportOverflowLong(); - } - _numberLong = (long) _numberDouble; - } else if ((_numTypesValid & NR_BIGDECIMAL) != 0) { - if (BD_MIN_LONG.compareTo(_numberBigDecimal) > 0 - || BD_MAX_LONG.compareTo(_numberBigDecimal) < 0) { - reportOverflowLong(); - } - _numberLong = _numberBigDecimal.longValue(); - } else { - _throwInternal(); - } - _numTypesValid |= NR_LONG; - } - - protected void convertNumberToBigInteger() throws IOException - { - if ((_numTypesValid & NR_BIGDECIMAL) != 0) { - // here it'll just get truncated, no exceptions thrown - _numberBigInt = _numberBigDecimal.toBigInteger(); - } else if ((_numTypesValid & NR_LONG) != 0) { - _numberBigInt = BigInteger.valueOf(_numberLong); - } else if ((_numTypesValid & NR_INT) != 0) { - _numberBigInt = BigInteger.valueOf(_numberInt); - } else if ((_numTypesValid & NR_DOUBLE) != 0) { - _numberBigInt = BigDecimal.valueOf(_numberDouble).toBigInteger(); - } else { - _throwInternal(); - } - _numTypesValid |= NR_BIGINT; - } - - protected void convertNumberToDouble() throws IOException - { - /* 05-Aug-2008, tatus: Important note: this MUST start with - * more accurate representations, since we don't know which - * value is the original one (others get generated when - * requested) - */ - - if ((_numTypesValid & NR_BIGDECIMAL) != 0) { - _numberDouble = _numberBigDecimal.doubleValue(); - } else if ((_numTypesValid & NR_BIGINT) != 0) { - _numberDouble = _numberBigInt.doubleValue(); - } else if ((_numTypesValid & NR_LONG) != 0) { - _numberDouble = (double) _numberLong; - } else if ((_numTypesValid & NR_INT) != 0) { - _numberDouble = (double) _numberInt; - } else { - _throwInternal(); - } - _numTypesValid |= NR_DOUBLE; - } - - protected void convertNumberToBigDecimal() throws IOException - { - /* 05-Aug-2008, tatus: Important note: this MUST start with - * more accurate representations, since we don't know which - * value is the original one (others get generated when - * requested) - */ - - if ((_numTypesValid & NR_DOUBLE) != 0) { - /* Let's actually parse from String representation, to avoid - * rounding errors that non-decimal floating operations could incur - */ - _numberBigDecimal = NumberInput.parseBigDecimal(getText()); - } else if ((_numTypesValid & NR_BIGINT) != 0) { - _numberBigDecimal = new BigDecimal(_numberBigInt); - } else if ((_numTypesValid & NR_LONG) != 0) { - _numberBigDecimal = BigDecimal.valueOf(_numberLong); - } else if ((_numTypesValid & NR_INT) != 0) { - _numberBigDecimal = BigDecimal.valueOf(_numberInt); - } else { - _throwInternal(); - } - _numTypesValid |= NR_BIGDECIMAL; - } - - /* - /********************************************************** - /* Number handling exceptions - /********************************************************** - */ - - protected void reportUnexpectedNumberChar(int ch, String comment) throws JsonParseException { - String msg = "Unexpected character ("+_getCharDesc(ch)+") in numeric value"; - if (comment != null) { - msg += ": "+comment; - } - _reportError(msg); - } - - protected void reportInvalidNumber(String msg) throws JsonParseException { - _reportError("Invalid numeric value: "+msg); - } - - protected void reportOverflowInt() throws IOException { - _reportError(String.format("Numeric value (%s) out of range of int (%d - %s)", - getText(), Integer.MIN_VALUE, Integer.MAX_VALUE)); - } - - protected void reportOverflowLong() throws IOException { - _reportError(String.format("Numeric value (%s) out of range of long (%d - %s)", - getText(), Long.MIN_VALUE, Long.MAX_VALUE)); - } - - /* - /********************************************************** - /* Base64 handling support - /********************************************************** - */ - - /** - * Method that sub-classes must implement to support escaped sequences - * in base64-encoded sections. - * Sub-classes that do not need base64 support can leave this as is - */ - protected char _decodeEscaped() throws IOException { - throw new UnsupportedOperationException(); - } - - protected final int _decodeBase64Escape(Base64Variant b64variant, int ch, int index) throws IOException - { - // 17-May-2011, tatu: As per [JACKSON-xxx], need to handle escaped chars - if (ch != '\\') { - throw reportInvalidBase64Char(b64variant, ch, index); - } - int unescaped = _decodeEscaped(); - // if white space, skip if first triplet; otherwise errors - if (unescaped <= INT_SPACE) { - if (index == 0) { // whitespace only allowed to be skipped between triplets - return -1; - } - } - // otherwise try to find actual triplet value - int bits = b64variant.decodeBase64Char(unescaped); - if (bits < 0) { - throw reportInvalidBase64Char(b64variant, unescaped, index); - } - return bits; - } - - protected final int _decodeBase64Escape(Base64Variant b64variant, char ch, int index) throws IOException - { - if (ch != '\\') { - throw reportInvalidBase64Char(b64variant, ch, index); - } - char unescaped = _decodeEscaped(); - // if white space, skip if first triplet; otherwise errors - if (unescaped <= INT_SPACE) { - if (index == 0) { // whitespace only allowed to be skipped between triplets - return -1; - } - } - // otherwise try to find actual triplet value - int bits = b64variant.decodeBase64Char(unescaped); - if (bits < 0) { - throw reportInvalidBase64Char(b64variant, unescaped, index); - } - return bits; - } - - protected IllegalArgumentException reportInvalidBase64Char(Base64Variant b64variant, int ch, int bindex) throws IllegalArgumentException { - return reportInvalidBase64Char(b64variant, ch, bindex, null); - } - - /** - * @param bindex Relative index within base64 character unit; between 0 - * and 3 (as unit has exactly 4 characters) - */ - protected IllegalArgumentException reportInvalidBase64Char(Base64Variant b64variant, int ch, int bindex, String msg) throws IllegalArgumentException { - String base; - if (ch <= INT_SPACE) { - base = "Illegal white space character (code 0x"+Integer.toHexString(ch)+") as character #"+(bindex+1)+" of 4-char base64 unit: can only used between units"; - } else if (b64variant.usesPaddingChar(ch)) { - base = "Unexpected padding character ('"+b64variant.getPaddingChar()+"') as character #"+(bindex+1)+" of 4-char base64 unit: padding only legal as 3rd or 4th character"; - } else if (!Character.isDefined(ch) || Character.isISOControl(ch)) { - // Not sure if we can really get here... ? (most illegal xml chars are caught at lower level) - base = "Illegal character (code 0x"+Integer.toHexString(ch)+") in base64 content"; - } else { - base = "Illegal character '"+((char)ch)+"' (code 0x"+Integer.toHexString(ch)+") in base64 content"; - } - if (msg != null) { - base = base + ": " + msg; - } - return new IllegalArgumentException(base); - } - - /* - /********************************************************** - /* Stuff that was abstract and required before 2.8, but that - /* is not mandatory in 2.8 or above. - /********************************************************** - */ - - @Deprecated // since 2.8 - protected void loadMoreGuaranteed() throws IOException { - if (!loadMore()) { _reportInvalidEOF(); } - } - - @Deprecated // since 2.8 - protected boolean loadMore() throws IOException { return false; } - - // Can't declare as deprecated, for now, but shouldn't be needed - protected void _finishString() throws IOException { } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/base/ParserMinimalBase.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/base/ParserMinimalBase.java deleted file mode 100644 index c7f699a8..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/base/ParserMinimalBase.java +++ /dev/null @@ -1,599 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.base; - -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_EMBEDDED_OBJECT; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_FALSE; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_NULL; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_NUMBER_FLOAT; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_NUMBER_INT; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_STRING; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_TRUE; - -import java.io.IOException; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.Base64Variant; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonProcessingException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonStreamContext; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.JsonEOFException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.NumberInput; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.ByteArrayBuilder; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.VersionUtil; - -/** - * Intermediate base class used by all Jackson {@link JsonParser} - * implementations, but does not add any additional fields that depend - * on particular method of obtaining input. - *

- * Note that 'minimal' here mostly refers to minimal number of fields - * (size) and functionality that is specific to certain types - * of parser implementations; but not necessarily to number of methods. - */ -public abstract class ParserMinimalBase extends JsonParser -{ - // Control chars: - protected final static int INT_TAB = '\t'; - protected final static int INT_LF = '\n'; - protected final static int INT_CR = '\r'; - protected final static int INT_SPACE = 0x0020; - - // Markup - protected final static int INT_LBRACKET = '['; - protected final static int INT_RBRACKET = ']'; - protected final static int INT_LCURLY = '{'; - protected final static int INT_RCURLY = '}'; - protected final static int INT_QUOTE = '"'; - protected final static int INT_BACKSLASH = '\\'; - protected final static int INT_SLASH = '/'; - protected final static int INT_COLON = ':'; - protected final static int INT_COMMA = ','; - protected final static int INT_HASH = '#'; - - // fp numbers - protected final static int INT_PERIOD = '.'; - protected final static int INT_e = 'e'; - protected final static int INT_E = 'E'; - - /* - /********************************************************** - /* Minimal generally useful state - /********************************************************** - */ - - /** - * Last token retrieved via {@link #nextToken}, if any. - * Null before the first call to nextToken(), - * as well as if token has been explicitly cleared - */ - protected JsonToken _currToken; - - /** - * Last cleared token, if any: that is, value that was in - * effect when {@link #clearCurrentToken} was called. - */ - protected JsonToken _lastClearedToken; - - /* - /********************************************************** - /* Life-cycle - /********************************************************** - */ - - protected ParserMinimalBase() { } - protected ParserMinimalBase(int features) { super(features); } - - // NOTE: had base impl in 2.3 and before; but shouldn't - // public abstract Version version(); - - /* - /********************************************************** - /* Configuration overrides if any - /********************************************************** - */ - - // from base class: - - //public void enableFeature(Feature f) - //public void disableFeature(Feature f) - //public void setFeature(Feature f, boolean state) - //public boolean isFeatureEnabled(Feature f) - - /* - /********************************************************** - /* JsonParser impl - /********************************************************** - */ - - @Override public abstract JsonToken nextToken() throws IOException; - - @Override public JsonToken currentToken() { return _currToken; } - @Override public int currentTokenId() { - final JsonToken t = _currToken; - return (t == null) ? JsonTokenId.ID_NO_TOKEN : t.id(); - } - - @Override public JsonToken getCurrentToken() { return _currToken; } - @Override public int getCurrentTokenId() { - final JsonToken t = _currToken; - return (t == null) ? JsonTokenId.ID_NO_TOKEN : t.id(); - } - - @Override public boolean hasCurrentToken() { return _currToken != null; } - @Override public boolean hasTokenId(int id) { - final JsonToken t = _currToken; - if (t == null) { - return (JsonTokenId.ID_NO_TOKEN == id); - } - return t.id() == id; - } - - @Override public boolean hasToken(JsonToken t) { - return (_currToken == t); - } - - @Override public boolean isExpectedStartArrayToken() { return _currToken == JsonToken.START_ARRAY; } - @Override public boolean isExpectedStartObjectToken() { return _currToken == JsonToken.START_OBJECT; } - - @Override - public JsonToken nextValue() throws IOException { - /* Implementation should be as trivial as follows; only - * needs to change if we are to skip other tokens (for - * example, if comments were exposed as tokens) - */ - JsonToken t = nextToken(); - if (t == JsonToken.FIELD_NAME) { - t = nextToken(); - } - return t; - } - - @Override - public JsonParser skipChildren() throws IOException - { - if (_currToken != JsonToken.START_OBJECT - && _currToken != JsonToken.START_ARRAY) { - return this; - } - int open = 1; - - /* Since proper matching of start/end markers is handled - * by nextToken(), we'll just count nesting levels here - */ - while (true) { - JsonToken t = nextToken(); - if (t == null) { - _handleEOF(); - /* given constraints, above should never return; - * however, FindBugs doesn't know about it and - * complains... so let's add dummy break here - */ - return this; - } - if (t.isStructStart()) { - ++open; - } else if (t.isStructEnd()) { - if (--open == 0) { - return this; - } - } - } - } - - /** - * Method sub-classes need to implement - */ - protected abstract void _handleEOF() throws JsonParseException; - - //public JsonToken getCurrentToken() - //public boolean hasCurrentToken() - - @Override public abstract String getCurrentName() throws IOException; - @Override public abstract void close() throws IOException; - @Override public abstract boolean isClosed(); - - @Override public abstract JsonStreamContext getParsingContext(); - -// public abstract JsonLocation getTokenLocation(); - -// public abstract JsonLocation getCurrentLocation(); - - /* - /********************************************************** - /* Public API, token state overrides - /********************************************************** - */ - - @Override public void clearCurrentToken() { - if (_currToken != null) { - _lastClearedToken = _currToken; - _currToken = null; - } - } - - @Override public JsonToken getLastClearedToken() { return _lastClearedToken; } - - @Override public abstract void overrideCurrentName(String name); - - /* - /********************************************************** - /* Public API, access to token information, text - /********************************************************** - */ - - @Override public abstract String getText() throws IOException; - @Override public abstract char[] getTextCharacters() throws IOException; - @Override public abstract boolean hasTextCharacters(); - @Override public abstract int getTextLength() throws IOException; - @Override public abstract int getTextOffset() throws IOException; - - /* - /********************************************************** - /* Public API, access to token information, binary - /********************************************************** - */ - - @Override public abstract byte[] getBinaryValue(Base64Variant b64variant) throws IOException; - - /* - /********************************************************** - /* Public API, access with conversion/coercion - /********************************************************** - */ - - @Override - public boolean getValueAsBoolean(boolean defaultValue) throws IOException - { - JsonToken t = _currToken; - if (t != null) { - switch (t.id()) { - case ID_STRING: - String str = getText().trim(); - if ("true".equals(str)) { - return true; - } - if ("false".equals(str)) { - return false; - } - if (_hasTextualNull(str)) { - return false; - } - break; - case ID_NUMBER_INT: - return getIntValue() != 0; - case ID_TRUE: - return true; - case ID_FALSE: - case ID_NULL: - return false; - case ID_EMBEDDED_OBJECT: - Object value = getEmbeddedObject(); - if (value instanceof Boolean) { - return (Boolean) value; - } - break; - default: - } - } - return defaultValue; - } - - @Override - public int getValueAsInt() throws IOException - { - JsonToken t = _currToken; - if ((t == JsonToken.VALUE_NUMBER_INT) || (t == JsonToken.VALUE_NUMBER_FLOAT)) { - return getIntValue(); - } - return getValueAsInt(0); - } - - @Override - public int getValueAsInt(int defaultValue) throws IOException - { - JsonToken t = _currToken; - if ((t == JsonToken.VALUE_NUMBER_INT) || (t == JsonToken.VALUE_NUMBER_FLOAT)) { - return getIntValue(); - } - if (t != null) { - switch (t.id()) { - case ID_STRING: - String str = getText(); - if (_hasTextualNull(str)) { - return 0; - } - return NumberInput.parseAsInt(str, defaultValue); - case ID_TRUE: - return 1; - case ID_FALSE: - return 0; - case ID_NULL: - return 0; - case ID_EMBEDDED_OBJECT: - Object value = getEmbeddedObject(); - if (value instanceof Number) { - return ((Number) value).intValue(); - } - } - } - return defaultValue; - } - - @Override - public long getValueAsLong() throws IOException - { - JsonToken t = _currToken; - if ((t == JsonToken.VALUE_NUMBER_INT) || (t == JsonToken.VALUE_NUMBER_FLOAT)) { - return getLongValue(); - } - return getValueAsLong(0L); - } - - @Override - public long getValueAsLong(long defaultValue) throws IOException - { - JsonToken t = _currToken; - if ((t == JsonToken.VALUE_NUMBER_INT) || (t == JsonToken.VALUE_NUMBER_FLOAT)) { - return getLongValue(); - } - if (t != null) { - switch (t.id()) { - case ID_STRING: - String str = getText(); - if (_hasTextualNull(str)) { - return 0L; - } - return NumberInput.parseAsLong(str, defaultValue); - case ID_TRUE: - return 1L; - case ID_FALSE: - case ID_NULL: - return 0L; - case ID_EMBEDDED_OBJECT: - Object value = getEmbeddedObject(); - if (value instanceof Number) { - return ((Number) value).longValue(); - } - } - } - return defaultValue; - } - - @Override - public double getValueAsDouble(double defaultValue) throws IOException - { - JsonToken t = _currToken; - if (t != null) { - switch (t.id()) { - case ID_STRING: - String str = getText(); - if (_hasTextualNull(str)) { - return 0L; - } - return NumberInput.parseAsDouble(str, defaultValue); - case ID_NUMBER_INT: - case ID_NUMBER_FLOAT: - return getDoubleValue(); - case ID_TRUE: - return 1.0; - case ID_FALSE: - case ID_NULL: - return 0.0; - case ID_EMBEDDED_OBJECT: - Object value = this.getEmbeddedObject(); - if (value instanceof Number) { - return ((Number) value).doubleValue(); - } - } - } - return defaultValue; - } - - @Override - public String getValueAsString() throws IOException { - if (_currToken == JsonToken.VALUE_STRING) { - return getText(); - } - if (_currToken == JsonToken.FIELD_NAME) { - return getCurrentName(); - } - return getValueAsString(null); - } - - @Override - public String getValueAsString(String defaultValue) throws IOException { - if (_currToken == JsonToken.VALUE_STRING) { - return getText(); - } - if (_currToken == JsonToken.FIELD_NAME) { - return getCurrentName(); - } - if (_currToken == null || _currToken == JsonToken.VALUE_NULL || !_currToken.isScalarValue()) { - return defaultValue; - } - return getText(); - } - - /* - /********************************************************** - /* Base64 decoding - /********************************************************** - */ - - /** - * Helper method that can be used for base64 decoding in cases where - * encoded content has already been read as a String. - */ - protected void _decodeBase64(String str, ByteArrayBuilder builder, Base64Variant b64variant) throws IOException - { - try { - b64variant.decode(str, builder); - } catch (IllegalArgumentException e) { - _reportError(e.getMessage()); - } - } - - /* - /********************************************************** - /* Coercion helper methods (overridable) - /********************************************************** - */ - - /** - * Helper method used to determine whether we are currently pointing to - * a String value of "null" (NOT a null token); and, if so, that parser - * is to recognize and return it similar to if it was real null token. - * - * @since 2.3 - */ - protected boolean _hasTextualNull(String value) { return "null".equals(value); } - - /* - /********************************************************** - /* Error reporting - /********************************************************** - */ - - protected void _reportUnexpectedChar(int ch, String comment) throws JsonParseException - { - if (ch < 0) { // sanity check - _reportInvalidEOF(); - } - String msg = "Unexpected character ("+_getCharDesc(ch)+")"; - if (comment != null) { - msg += ": "+comment; - } - _reportError(msg); - } - - protected void _reportInvalidEOF() throws JsonParseException { - _reportInvalidEOF(" in "+_currToken, _currToken); - } - - /** - * @since 2.8 - */ - protected void _reportInvalidEOFInValue(JsonToken type) throws JsonParseException { - String msg; - if (type == JsonToken.VALUE_STRING) { - msg = " in a String value"; - } else if ((type == JsonToken.VALUE_NUMBER_INT) - || (type == JsonToken.VALUE_NUMBER_FLOAT)) { - msg = " in a Number value"; - } else { - msg = " in a value"; - } - _reportInvalidEOF(msg, type); - } - - /** - * @since 2.8 - */ - protected void _reportInvalidEOF(String msg, JsonToken currToken) throws JsonParseException { - throw new JsonEOFException(this, currToken, "Unexpected end-of-input"+msg); - } - - /** - * @deprecated Since 2.8 use {@link #_reportInvalidEOF(String, JsonToken)} instead - */ - @Deprecated // since 2.8 - protected void _reportInvalidEOFInValue() throws JsonParseException { - _reportInvalidEOF(" in a value"); - } - - /** - * @deprecated Since 2.8 use {@link #_reportInvalidEOF(String, JsonToken)} instead - */ - @Deprecated // since 2.8 - protected void _reportInvalidEOF(String msg) throws JsonParseException { - throw new JsonEOFException(this, null, "Unexpected end-of-input"+msg); - } - - protected void _reportMissingRootWS(int ch) throws JsonParseException { - _reportUnexpectedChar(ch, "Expected space separating root-level values"); - } - - protected void _throwInvalidSpace(int i) throws JsonParseException { - char c = (char) i; - String msg = "Illegal character ("+_getCharDesc(c)+"): only regular white space (\\r, \\n, \\t) is allowed between tokens"; - _reportError(msg); - } - - /** - * Method called to report a problem with unquoted control character. - * Note: starting with version 1.4, it is possible to suppress - * exception by enabling {@link Feature#ALLOW_UNQUOTED_CONTROL_CHARS}. - */ - protected void _throwUnquotedSpace(int i, String ctxtDesc) throws JsonParseException { - // JACKSON-208; possible to allow unquoted control chars: - if (!isEnabled(Feature.ALLOW_UNQUOTED_CONTROL_CHARS) || i > INT_SPACE) { - char c = (char) i; - String msg = "Illegal unquoted character ("+_getCharDesc(c)+"): has to be escaped using backslash to be included in "+ctxtDesc; - _reportError(msg); - } - } - - protected char _handleUnrecognizedCharacterEscape(char ch) throws JsonProcessingException { - // as per [JACKSON-300] - if (isEnabled(Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER)) { - return ch; - } - // and [JACKSON-548] - if (ch == '\'' && isEnabled(Feature.ALLOW_SINGLE_QUOTES)) { - return ch; - } - _reportError("Unrecognized character escape "+_getCharDesc(ch)); - return ch; - } - - /* - /********************************************************** - /* Error reporting, generic - /********************************************************** - */ - - protected final static String _getCharDesc(int ch) - { - char c = (char) ch; - if (Character.isISOControl(c)) { - return "(CTRL-CHAR, code "+ch+")"; - } - if (ch > 255) { - return "'"+c+"' (code "+ch+" / 0x"+Integer.toHexString(ch)+")"; - } - return "'"+c+"' (code "+ch+")"; - } - - protected final void _reportError(String msg) throws JsonParseException { - throw _constructError(msg); - } - - protected final void _wrapError(String msg, Throwable t) throws JsonParseException { - throw _constructError(msg, t); - } - - protected final void _throwInternal() { - VersionUtil.throwInternal(); - } - - protected final JsonParseException _constructError(String msg, Throwable t) { - return new JsonParseException(this, msg, t); - } - - protected static byte[] _asciiBytes(String str) { - byte[] b = new byte[str.length()]; - for (int i = 0, len = str.length(); i < len; ++i) { - b[i] = (byte) str.charAt(i); - } - return b; - } - - protected static String _ascii(byte[] b) { - try { - return new String(b, "US-ASCII"); - } catch (IOException e) { // never occurs - throw new RuntimeException(e); - } - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/filter/FilteringGeneratorDelegate.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/filter/FilteringGeneratorDelegate.java deleted file mode 100644 index 89fc6fb5..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/filter/FilteringGeneratorDelegate.java +++ /dev/null @@ -1,871 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.filter; - -import java.io.IOException; -import java.io.InputStream; -import java.math.BigDecimal; -import java.math.BigInteger; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.Base64Variant; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonStreamContext; -import autosaveworld.zlibs.com.fasterxml.jackson.core.SerializableString; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.JsonGeneratorDelegate; - -/** - * Specialized {@link JsonGeneratorDelegate} that allows use of - * {@link TokenFilter} for outputting a subset of content that - * caller tries to generate. - * - * @since 2.6 - */ -public class FilteringGeneratorDelegate extends JsonGeneratorDelegate -{ - /* - /********************************************************** - /* Configuration - /********************************************************** - */ - - /** - * Object consulted to determine whether to write parts of content generator - * is asked to write or not. - */ - protected TokenFilter rootFilter; - - /** - * Flag that determines whether filtering will continue after the first - * match is indicated or not: if `false`, output is based on just the first - * full match (returning {@link TokenFilter#INCLUDE_ALL}) and no more - * checks are made; if `true` then filtering will be applied as necessary - * until end of content. - */ - protected boolean _allowMultipleMatches; - - /** - * Flag that determines whether path leading up to included content should - * also be automatically included or not. If `false`, no path inclusion is - * done and only explicitly included entries are output; if `true` then - * path from main level down to match is also included as necessary. - */ - protected boolean _includePath; - - /* NOTE: this feature is included in the first version (2.6), but - * there is no public API to enable it, yet, since there isn't an - * actual use case. But it seemed possible need could arise, which - * is feature has not yet been removed. If no use is found within - * first version or two, just remove. - * - * Marked as deprecated since its status is uncertain. - */ - @Deprecated - protected boolean _includeImmediateParent; - - /* - /********************************************************** - /* Additional state - /********************************************************** - */ - - /** - * Although delegate has its own output context it is not sufficient since we actually - * have to keep track of excluded (filtered out) structures as well as ones delegate - * actually outputs. - */ - protected TokenFilterContext _filterContext; - - /** - * State that applies to the item within container, used where applicable. - * Specifically used to pass inclusion state between property name and - * property, and also used for array elements. - */ - protected TokenFilter _itemFilter; - - /** - * Number of tokens for which {@link TokenFilter#INCLUDE_ALL} - * has been returned - */ - protected int _matchCount; - - /* - /********************************************************** - /* Construction, initialization - /********************************************************** - */ - - public FilteringGeneratorDelegate(JsonGenerator d, TokenFilter f, - boolean includePath, boolean allowMultipleMatches) - { - // By default, do NOT delegate copy methods - super(d, false); - rootFilter = f; - // and this is the currently active filter for root values - _itemFilter = f; - _filterContext = TokenFilterContext.createRootContext(f); - _includePath = includePath; - _allowMultipleMatches = allowMultipleMatches; - } - - /* - /********************************************************** - /* Extended API - /********************************************************** - */ - - public TokenFilter getFilter() { return rootFilter; } - - public JsonStreamContext getFilterContext() { - return _filterContext; - } - - /** - * Accessor for finding number of matches, where specific token and sub-tree - * starting (if structured type) are passed. - */ - public int getMatchCount() { - return _matchCount; - } - - /* - /********************************************************** - /* Public API, accessors - /********************************************************** - */ - - @Override - public JsonStreamContext getOutputContext() { - /* 11-Apr-2015, tatu: Choice is between pre- and post-filter context; - * let's expose post-filter context that correlates with the view - * of caller. - */ - return _filterContext; - } - - /* - /********************************************************** - /* Public API, write methods, structural - /********************************************************** - */ - - @Override - public void writeStartArray() throws IOException - { - // First things first: whole-sale skipping easy - if (_itemFilter == null) { - _filterContext = _filterContext.createChildArrayContext(null, false); - return; - } - if (_itemFilter == TokenFilter.INCLUDE_ALL) { // include the whole sub-tree? - _filterContext = _filterContext.createChildArrayContext(_itemFilter, true); - delegate.writeStartArray(); - return; - } - // Ok; regular checking state then - _itemFilter = _filterContext.checkValue(_itemFilter); - if (_itemFilter == null) { - _filterContext = _filterContext.createChildArrayContext(null, false); - return; - } - if (_itemFilter != TokenFilter.INCLUDE_ALL) { - _itemFilter = _itemFilter.filterStartArray(); - } - if (_itemFilter == TokenFilter.INCLUDE_ALL) { - _checkParentPath(); - _filterContext = _filterContext.createChildArrayContext(_itemFilter, true); - delegate.writeStartArray(); - } else { - _filterContext = _filterContext.createChildArrayContext(_itemFilter, false); - } - } - - @Override - public void writeStartArray(int size) throws IOException - { - if (_itemFilter == null) { - _filterContext = _filterContext.createChildArrayContext(null, false); - return; - } - if (_itemFilter == TokenFilter.INCLUDE_ALL) { - _filterContext = _filterContext.createChildArrayContext(_itemFilter, true); - delegate.writeStartArray(size); - return; - } - _itemFilter = _filterContext.checkValue(_itemFilter); - if (_itemFilter == null) { - _filterContext = _filterContext.createChildArrayContext(null, false); - return; - } - if (_itemFilter != TokenFilter.INCLUDE_ALL) { - _itemFilter = _itemFilter.filterStartArray(); - } - if (_itemFilter == TokenFilter.INCLUDE_ALL) { - _checkParentPath(); - _filterContext = _filterContext.createChildArrayContext(_itemFilter, true); - delegate.writeStartArray(size); - } else { - _filterContext = _filterContext.createChildArrayContext(_itemFilter, false); - } - } - - @Override - public void writeEndArray() throws IOException - { - _filterContext = _filterContext.closeArray(delegate); - - if (_filterContext != null) { - _itemFilter = _filterContext.getFilter(); - } - } - - @Override - public void writeStartObject() throws IOException - { - if (_itemFilter == null) { - _filterContext = _filterContext.createChildObjectContext(_itemFilter, false); - return; - } - if (_itemFilter == TokenFilter.INCLUDE_ALL) { - _filterContext = _filterContext.createChildObjectContext(_itemFilter, true); - delegate.writeStartObject(); - return; - } - - TokenFilter f = _filterContext.checkValue(_itemFilter); - if (f == null) { - return; - } - - if (f != TokenFilter.INCLUDE_ALL) { - f = f.filterStartObject(); - } - if (f == TokenFilter.INCLUDE_ALL) { - _checkParentPath(); - _filterContext = _filterContext.createChildObjectContext(f, true); - delegate.writeStartObject(); - } else { // filter out - _filterContext = _filterContext.createChildObjectContext(f, false); - } - } - - @Override - public void writeEndObject() throws IOException - { - _filterContext = _filterContext.closeObject(delegate); - if (_filterContext != null) { - _itemFilter = _filterContext.getFilter(); - } - } - - @Override - public void writeFieldName(String name) throws IOException - { - TokenFilter state = _filterContext.setFieldName(name); - if (state == null) { - _itemFilter = null; - return; - } - if (state == TokenFilter.INCLUDE_ALL) { - _itemFilter = state; - delegate.writeFieldName(name); - return; - } - state = state.includeProperty(name); - _itemFilter = state; - if (state == TokenFilter.INCLUDE_ALL) { - _checkPropertyParentPath(); - } - } - - @Override - public void writeFieldName(SerializableString name) throws IOException - { - TokenFilter state = _filterContext.setFieldName(name.getValue()); - if (state == null) { - _itemFilter = null; - return; - } - if (state == TokenFilter.INCLUDE_ALL) { - _itemFilter = state; - delegate.writeFieldName(name); - return; - } - state = state.includeProperty(name.getValue()); - _itemFilter = state; - if (state == TokenFilter.INCLUDE_ALL) { - _checkPropertyParentPath(); - } - } - - /* - /********************************************************** - /* Public API, write methods, text/String values - /********************************************************** - */ - - @Override - public void writeString(String value) throws IOException - { - if (_itemFilter == null) { - return; - } - if (_itemFilter != TokenFilter.INCLUDE_ALL) { - TokenFilter state = _filterContext.checkValue(_itemFilter); - if (state == null) { - return; - } - if (state != TokenFilter.INCLUDE_ALL) { - if (!state.includeString(value)) { - return; - } - } - _checkParentPath(); - } - delegate.writeString(value); - } - - @Override - public void writeString(char[] text, int offset, int len) throws IOException - { - if (_itemFilter == null) { - return; - } - if (_itemFilter != TokenFilter.INCLUDE_ALL) { - String value = new String(text, offset, len); - TokenFilter state = _filterContext.checkValue(_itemFilter); - if (state == null) { - return; - } - if (state != TokenFilter.INCLUDE_ALL) { - if (!state.includeString(value)) { - return; - } - } - _checkParentPath(); - } - delegate.writeString(text, offset, len); - } - - @Override - public void writeString(SerializableString value) throws IOException - { - if (_itemFilter == null) { - return; - } - if (_itemFilter != TokenFilter.INCLUDE_ALL) { - TokenFilter state = _filterContext.checkValue(_itemFilter); - if (state == null) { - return; - } - if (state != TokenFilter.INCLUDE_ALL) { - if (!state.includeString(value.getValue())) { - return; - } - } - _checkParentPath(); - } - delegate.writeString(value); - } - - @Override - public void writeRawUTF8String(byte[] text, int offset, int length) throws IOException - { - if (_checkRawValueWrite()) { - delegate.writeRawUTF8String(text, offset, length); - } - } - - @Override - public void writeUTF8String(byte[] text, int offset, int length) throws IOException - { - // not exact match, but best we can do - if (_checkRawValueWrite()) { - delegate.writeUTF8String(text, offset, length); - } - } - - /* - /********************************************************** - /* Public API, write methods, binary/raw content - /********************************************************** - */ - - @Override - public void writeRaw(String text) throws IOException - { - if (_checkRawValueWrite()) { - delegate.writeRaw(text); - } - } - - @Override - public void writeRaw(String text, int offset, int len) throws IOException - { - if (_checkRawValueWrite()) { - delegate.writeRaw(text); - } - } - - @Override - public void writeRaw(SerializableString text) throws IOException - { - if (_checkRawValueWrite()) { - delegate.writeRaw(text); - } - } - - @Override - public void writeRaw(char[] text, int offset, int len) throws IOException - { - if (_checkRawValueWrite()) { - delegate.writeRaw(text, offset, len); - } - } - - @Override - public void writeRaw(char c) throws IOException - { - if (_checkRawValueWrite()) { - delegate.writeRaw(c); - } - } - - @Override - public void writeRawValue(String text) throws IOException - { - if (_checkRawValueWrite()) { - delegate.writeRaw(text); - } - } - - @Override - public void writeRawValue(String text, int offset, int len) throws IOException - { - if (_checkRawValueWrite()) { - delegate.writeRaw(text, offset, len); - } - } - - @Override - public void writeRawValue(char[] text, int offset, int len) throws IOException - { - if (_checkRawValueWrite()) { - delegate.writeRaw(text, offset, len); - } - } - - @Override - public void writeBinary(Base64Variant b64variant, byte[] data, int offset, int len) throws IOException - { - if (_checkBinaryWrite()) { - delegate.writeBinary(b64variant, data, offset, len); - } - } - - @Override - public int writeBinary(Base64Variant b64variant, InputStream data, int dataLength) throws IOException - { - if (_checkBinaryWrite()) { - return delegate.writeBinary(b64variant, data, dataLength); - } - return -1; - } - - /* - /********************************************************** - /* Public API, write methods, other value types - /********************************************************** - */ - - @Override - public void writeNumber(short v) throws IOException - { - if (_itemFilter == null) { - return; - } - if (_itemFilter != TokenFilter.INCLUDE_ALL) { - TokenFilter state = _filterContext.checkValue(_itemFilter); - if (state == null) { - return; - } - if (state != TokenFilter.INCLUDE_ALL) { - if (!state.includeNumber(v)) { - return; - } - } - _checkParentPath(); - } - delegate.writeNumber(v); - } - - @Override - public void writeNumber(int v) throws IOException - { - if (_itemFilter == null) { - return; - } - if (_itemFilter != TokenFilter.INCLUDE_ALL) { - TokenFilter state = _filterContext.checkValue(_itemFilter); - if (state == null) { - return; - } - if (state != TokenFilter.INCLUDE_ALL) { - if (!state.includeNumber(v)) { - return; - } - } - _checkParentPath(); - } - delegate.writeNumber(v); - } - - @Override - public void writeNumber(long v) throws IOException - { - if (_itemFilter == null) { - return; - } - if (_itemFilter != TokenFilter.INCLUDE_ALL) { - TokenFilter state = _filterContext.checkValue(_itemFilter); - if (state == null) { - return; - } - if (state != TokenFilter.INCLUDE_ALL) { - if (!state.includeNumber(v)) { - return; - } - } - _checkParentPath(); - } - delegate.writeNumber(v); - } - - @Override - public void writeNumber(BigInteger v) throws IOException - { - if (_itemFilter == null) { - return; - } - if (_itemFilter != TokenFilter.INCLUDE_ALL) { - TokenFilter state = _filterContext.checkValue(_itemFilter); - if (state == null) { - return; - } - if (state != TokenFilter.INCLUDE_ALL) { - if (!state.includeNumber(v)) { - return; - } - } - _checkParentPath(); - } - delegate.writeNumber(v); - } - - @Override - public void writeNumber(double v) throws IOException - { - if (_itemFilter == null) { - return; - } - if (_itemFilter != TokenFilter.INCLUDE_ALL) { - TokenFilter state = _filterContext.checkValue(_itemFilter); - if (state == null) { - return; - } - if (state != TokenFilter.INCLUDE_ALL) { - if (!state.includeNumber(v)) { - return; - } - } - _checkParentPath(); - } - delegate.writeNumber(v); - } - - @Override - public void writeNumber(float v) throws IOException - { - if (_itemFilter == null) { - return; - } - if (_itemFilter != TokenFilter.INCLUDE_ALL) { - TokenFilter state = _filterContext.checkValue(_itemFilter); - if (state == null) { - return; - } - if (state != TokenFilter.INCLUDE_ALL) { - if (!state.includeNumber(v)) { - return; - } - } - _checkParentPath(); - } - delegate.writeNumber(v); - } - - @Override - public void writeNumber(BigDecimal v) throws IOException - { - if (_itemFilter == null) { - return; - } - if (_itemFilter != TokenFilter.INCLUDE_ALL) { - TokenFilter state = _filterContext.checkValue(_itemFilter); - if (state == null) { - return; - } - if (state != TokenFilter.INCLUDE_ALL) { - if (!state.includeNumber(v)) { - return; - } - } - _checkParentPath(); - } - delegate.writeNumber(v); - } - - @Override - public void writeNumber(String encodedValue) throws IOException, UnsupportedOperationException - { - if (_itemFilter == null) { - return; - } - if (_itemFilter != TokenFilter.INCLUDE_ALL) { - TokenFilter state = _filterContext.checkValue(_itemFilter); - if (state == null) { - return; - } - if (state != TokenFilter.INCLUDE_ALL) { - if (!state.includeRawValue()) { // close enough? - return; - } - } - _checkParentPath(); - } - delegate.writeNumber(encodedValue); - } - - @Override - public void writeBoolean(boolean v) throws IOException - { - if (_itemFilter == null) { - return; - } - if (_itemFilter != TokenFilter.INCLUDE_ALL) { - TokenFilter state = _filterContext.checkValue(_itemFilter); - if (state == null) { - return; - } - if (state != TokenFilter.INCLUDE_ALL) { - if (!state.includeBoolean(v)) { - return; - } - } - _checkParentPath(); - } - delegate.writeBoolean(v); - } - - @Override - public void writeNull() throws IOException - { - if (_itemFilter == null) { - return; - } - if (_itemFilter != TokenFilter.INCLUDE_ALL) { - TokenFilter state = _filterContext.checkValue(_itemFilter); - if (state == null) { - return; - } - if (state != TokenFilter.INCLUDE_ALL) { - if (!state.includeNull()) { - return; - } - } - _checkParentPath(); - } - delegate.writeNull(); - } - - /* - /********************************************************** - /* Overridden field methods - /********************************************************** - */ - - @Override - public void writeOmittedField(String fieldName) throws IOException { - // Hmmh. Not sure how this would work but... - if (_itemFilter != null) { - delegate.writeOmittedField(fieldName); - } - } - - /* - /********************************************************** - /* Public API, write methods, Native Ids - /********************************************************** - */ - - // 25-Mar-2015, tatu: These are tricky as they sort of predate actual filtering calls. - // Let's try to use current state as a clue at least... - - @Override - public void writeObjectId(Object id) throws IOException { - if (_itemFilter != null) { - delegate.writeObjectId(id); - } - } - - @Override - public void writeObjectRef(Object id) throws IOException { - if (_itemFilter != null) { - delegate.writeObjectRef(id); - } - } - - @Override - public void writeTypeId(Object id) throws IOException { - if (_itemFilter != null) { - delegate.writeTypeId(id); - } - } - - /* - /********************************************************** - /* Public API, write methods, serializing Java objects - /********************************************************** - */ - - // Base class definitions for these seems correct to me, iff not directly delegating: - - /* - @Override - public void writeObject(Object pojo) throws IOException,JsonProcessingException { - if (delegateCopyMethods) { - delegate.writeObject(pojo); - return; - } - // NOTE: copied from - if (pojo == null) { - writeNull(); - } else { - if (getCodec() != null) { - getCodec().writeValue(this, pojo); - return; - } - _writeSimpleObject(pojo); - } - } - - @Override - public void writeTree(TreeNode rootNode) throws IOException { - if (delegateCopyMethods) { - delegate.writeTree(rootNode); - return; - } - // As with 'writeObject()', we are not check if write would work - if (rootNode == null) { - writeNull(); - } else { - if (getCodec() == null) { - throw new IllegalStateException("No ObjectCodec defined"); - } - getCodec().writeValue(this, rootNode); - } - } - */ - - /* - /********************************************************** - /* Public API, copy-through methods - /********************************************************** - */ - - // Base class definitions for these seems correct to me, iff not directly delegating: - - /* - @Override - public void copyCurrentEvent(JsonParser jp) throws IOException { - if (delegateCopyMethods) delegate.copyCurrentEvent(jp); - else super.copyCurrentEvent(jp); - } - - @Override - public void copyCurrentStructure(JsonParser jp) throws IOException { - if (delegateCopyMethods) delegate.copyCurrentStructure(jp); - else super.copyCurrentStructure(jp); - } - */ - - /* - /********************************************************** - /* Helper methods - /********************************************************** - */ - - protected void _checkParentPath() throws IOException - { - ++_matchCount; - // only need to construct path if parent wasn't written - if (_includePath) { - _filterContext.writePath(delegate); - } - // also: if no multiple matches desired, short-cut checks - if (!_allowMultipleMatches) { - // Mark parents as "skip" so that further check calls are not made - _filterContext.skipParentChecks(); - } - } - - /** - * Specialized variant of {@link #_checkParentPath} used when checking - * parent for a property name to be included with value: rules are slightly - * different. - */ - protected void _checkPropertyParentPath() throws IOException - { - ++_matchCount; - if (_includePath) { - _filterContext.writePath(delegate); - } else if (_includeImmediateParent) { - // 21-Apr-2015, tatu: Note that there is no API to enable this currently... - // retained for speculative future use - _filterContext.writeImmediatePath(delegate); - } - - // also: if no multiple matches desired, short-cut checks - if (!_allowMultipleMatches) { - // Mark parents as "skip" so that further check calls are not made - _filterContext.skipParentChecks(); - } - } - - protected boolean _checkBinaryWrite() throws IOException - { - if (_itemFilter == null) { - return false; - } - if (_itemFilter == TokenFilter.INCLUDE_ALL) { - return true; - } - if (_itemFilter.includeBinary()) { // close enough? - _checkParentPath(); - return true; - } - return false; - } - - protected boolean _checkRawValueWrite() throws IOException - { - if (_itemFilter == null) { - return false; - } - if (_itemFilter == TokenFilter.INCLUDE_ALL) { - return true; - } - if (_itemFilter.includeRawValue()) { // close enough? - _checkParentPath(); - return true; - } - return false; - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/filter/FilteringParserDelegate.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/filter/FilteringParserDelegate.java deleted file mode 100644 index 71e691be..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/filter/FilteringParserDelegate.java +++ /dev/null @@ -1,912 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.filter; - -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_END_ARRAY; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_END_OBJECT; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_FIELD_NAME; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_START_ARRAY; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_START_OBJECT; - -import java.io.IOException; -import java.io.OutputStream; -import java.math.BigDecimal; -import java.math.BigInteger; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.Base64Variant; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonLocation; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonStreamContext; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.JsonParserDelegate; - -/** - * Specialized {@link JsonParserDelegate} that allows use of - * {@link TokenFilter} for outputting a subset of content that - * is visible to caller - * - * @since 2.6 - */ -public class FilteringParserDelegate extends JsonParserDelegate -{ - /* - /********************************************************** - /* Configuration - /********************************************************** - */ - - /** - * Object consulted to determine whether to write parts of content generator - * is asked to write or not. - */ - protected TokenFilter rootFilter; - - /** - * Flag that determines whether filtering will continue after the first - * match is indicated or not: if `false`, output is based on just the first - * full match (returning {@link TokenFilter#INCLUDE_ALL}) and no more - * checks are made; if `true` then filtering will be applied as necessary - * until end of content. - */ - protected boolean _allowMultipleMatches; - - /** - * Flag that determines whether path leading up to included content should - * also be automatically included or not. If `false`, no path inclusion is - * done and only explicitly included entries are output; if `true` then - * path from main level down to match is also included as necessary. - */ - protected boolean _includePath; - - /* NOTE: this feature is included in the first version (2.6), but - * there is no public API to enable it, yet, since there isn't an - * actual use case. But it seemed possible need could arise, which - * is feature has not yet been removed. If no use is found within - * first version or two, just remove. - * - * Marked as deprecated since its status is uncertain. - */ - @Deprecated - protected boolean _includeImmediateParent; - - /* - /********************************************************** - /* State - /********************************************************** - */ - - /** - * Last token retrieved via {@link #nextToken}, if any. - * Null before the first call to nextToken(), - * as well as if token has been explicitly cleared - */ - protected JsonToken _currToken; - - /** - * Last cleared token, if any: that is, value that was in - * effect when {@link #clearCurrentToken} was called. - */ - protected JsonToken _lastClearedToken; - - /** - * During traversal this is the actual "open" parse tree, which sometimes - * is the same as {@link #_exposedContext}, and at other times is ahead - * of it. Note that this context is never null. - */ - protected TokenFilterContext _headContext; - - /** - * In cases where {@link #_headContext} is "ahead" of context exposed to - * caller, this context points to what is currently exposed to caller. - * When the two are in sync, this context reference will be null. - */ - protected TokenFilterContext _exposedContext; - - /** - * State that applies to the item within container, used where applicable. - * Specifically used to pass inclusion state between property name and - * property, and also used for array elements. - */ - protected TokenFilter _itemFilter; - - /** - * Number of tokens for which {@link TokenFilter#INCLUDE_ALL} - * has been returned. - */ - protected int _matchCount; - - /* - /********************************************************** - /* Construction, initialization - /********************************************************** - */ - - public FilteringParserDelegate(JsonParser p, TokenFilter f, - boolean includePath, boolean allowMultipleMatches) - { - super(p); - rootFilter = f; - // and this is the currently active filter for root values - _itemFilter = f; - _headContext = TokenFilterContext.createRootContext(f); - _includePath = includePath; - _allowMultipleMatches = allowMultipleMatches; - } - - /* - /********************************************************** - /* Extended API - /********************************************************** - */ - - public TokenFilter getFilter() { return rootFilter; } - - /** - * Accessor for finding number of matches, where specific token and sub-tree - * starting (if structured type) are passed. - */ - public int getMatchCount() { - return _matchCount; - } - - /* - /********************************************************** - /* Public API, token accessors - /********************************************************** - */ - - @Override public JsonToken getCurrentToken() { return _currToken; } - @Override public JsonToken currentToken() { return _currToken; } - - @Override public final int getCurrentTokenId() { - final JsonToken t = _currToken; - return (t == null) ? JsonTokenId.ID_NO_TOKEN : t.id(); - } - @Override public final int currentTokenId() { - final JsonToken t = _currToken; - return (t == null) ? JsonTokenId.ID_NO_TOKEN : t.id(); - } - - @Override public boolean hasCurrentToken() { return _currToken != null; } - @Override public boolean hasTokenId(int id) { - final JsonToken t = _currToken; - if (t == null) { - return (JsonTokenId.ID_NO_TOKEN == id); - } - return t.id() == id; - } - - @Override public final boolean hasToken(JsonToken t) { - return (_currToken == t); - } - - @Override public boolean isExpectedStartArrayToken() { return _currToken == JsonToken.START_ARRAY; } - @Override public boolean isExpectedStartObjectToken() { return _currToken == JsonToken.START_OBJECT; } - - @Override public JsonLocation getCurrentLocation() { return delegate.getCurrentLocation(); } - - @Override - public JsonStreamContext getParsingContext() { - return _filterContext(); - } - - // !!! TODO: Verify it works as expected: copied from standard JSON parser impl - @Override - public String getCurrentName() throws IOException { - JsonStreamContext ctxt = _filterContext(); - if (_currToken == JsonToken.START_OBJECT || _currToken == JsonToken.START_ARRAY) { - JsonStreamContext parent = ctxt.getParent(); - return (parent == null) ? null : parent.getCurrentName(); - } - return ctxt.getCurrentName(); - } - - /* - /********************************************************** - /* Public API, token state overrides - /********************************************************** - */ - - @Override - public void clearCurrentToken() { - if (_currToken != null) { - _lastClearedToken = _currToken; - _currToken = null; - } - } - - @Override - public JsonToken getLastClearedToken() { return _lastClearedToken; } - - @Override - public void overrideCurrentName(String name) { - /* 14-Apr-2015, tatu: Not sure whether this can be supported, and if so, - * what to do with it... Delegation won't work for sure, so let's for - * now throw an exception - */ - throw new UnsupportedOperationException("Can not currently override name during filtering read"); - } - - /* - /********************************************************** - /* Public API, traversal - /********************************************************** - */ - - @Override - public JsonToken nextToken() throws IOException - { - //Check for _allowMultipleMatches - false and atleast there is one token - which is _currToken - // check for no buffered context _exposedContext - null - //If all the conditions matches then check for scalar / non-scalar property - if(!_allowMultipleMatches && _currToken != null && _exposedContext == null){ - //if not scalar and ended successfully, then return null - if((_currToken.isStructEnd() && _headContext.isStartHandled()) ){ - return (_currToken = null); - } - //else if scalar, and scalar not present in obj/array and !includePath and INCLUDE_ALL matched once - // then return null - else if(_currToken.isScalarValue() && !_headContext.isStartHandled() && !_includePath - && _itemFilter == TokenFilter.INCLUDE_ALL) { - return (_currToken = null); - } - } - // Anything buffered? - TokenFilterContext ctxt = _exposedContext; - - if (ctxt != null) { - while (true) { - JsonToken t = ctxt.nextTokenToRead(); - if (t != null) { - _currToken = t; - return t; - } - // all done with buffered stuff? - if (ctxt == _headContext) { - _exposedContext = null; - if (ctxt.inArray()) { - t = delegate.getCurrentToken(); -// Is this guaranteed to work without further checks? -// if (t != JsonToken.START_ARRAY) { - _currToken = t; - return t; - } - - // Almost! Most likely still have the current token; - // with the sole exception of - /* - t = delegate.getCurrentToken(); - if (t != JsonToken.FIELD_NAME) { - _currToken = t; - return t; - } - */ - break; - } - // If not, traverse down the context chain - ctxt = _headContext.findChildOf(ctxt); - _exposedContext = ctxt; - if (ctxt == null) { // should never occur - throw _constructError("Unexpected problem: chain of filtered context broken"); - } - } - } - - // If not, need to read more. If we got any: - JsonToken t = delegate.nextToken(); - if (t == null) { - // no strict need to close, since we have no state here - _currToken = t; - return t; - } - - // otherwise... to include or not? - TokenFilter f; - - switch (t.id()) { - case ID_START_ARRAY: - f = _itemFilter; - if (f == TokenFilter.INCLUDE_ALL) { - _headContext = _headContext.createChildArrayContext(f, true); - return (_currToken = t); - } - if (f == null) { // does this occur? - delegate.skipChildren(); - break; - } - // Otherwise still iffy, need to check - f = _headContext.checkValue(f); - if (f == null) { - delegate.skipChildren(); - break; - } - if (f != TokenFilter.INCLUDE_ALL) { - f = f.filterStartArray(); - } - _itemFilter = f; - if (f == TokenFilter.INCLUDE_ALL) { - _headContext = _headContext.createChildArrayContext(f, true); - return (_currToken = t); - } - _headContext = _headContext.createChildArrayContext(f, false); - - // Also: only need buffering if parent path to be included - if (_includePath) { - t = _nextTokenWithBuffering(_headContext); - if (t != null) { - _currToken = t; - return t; - } - } - break; - - case ID_START_OBJECT: - f = _itemFilter; - if (f == TokenFilter.INCLUDE_ALL) { - _headContext = _headContext.createChildObjectContext(f, true); - return (_currToken = t); - } - if (f == null) { // does this occur? - delegate.skipChildren(); - break; - } - // Otherwise still iffy, need to check - f = _headContext.checkValue(f); - if (f == null) { - delegate.skipChildren(); - break; - } - if (f != TokenFilter.INCLUDE_ALL) { - f = f.filterStartObject(); - } - _itemFilter = f; - if (f == TokenFilter.INCLUDE_ALL) { - _headContext = _headContext.createChildObjectContext(f, true); - return (_currToken = t); - } - _headContext = _headContext.createChildObjectContext(f, false); - // Also: only need buffering if parent path to be included - if (_includePath) { - t = _nextTokenWithBuffering(_headContext); - if (t != null) { - _currToken = t; - return t; - } - } - // note: inclusion of surrounding Object handled separately via - // FIELD_NAME - break; - - case ID_END_ARRAY: - case ID_END_OBJECT: - { - boolean returnEnd = _headContext.isStartHandled(); - f = _headContext.getFilter(); - if ((f != null) && (f != TokenFilter.INCLUDE_ALL)) { - f.filterFinishArray(); - } - _headContext = _headContext.getParent(); - _itemFilter = _headContext.getFilter(); - if (returnEnd) { - return (_currToken = t); - } - } - break; - - case ID_FIELD_NAME: - { - final String name = delegate.getCurrentName(); - // note: this will also set 'needToHandleName' - f = _headContext.setFieldName(name); - if (f == TokenFilter.INCLUDE_ALL) { - _itemFilter = f; - if (!_includePath) { - // Minor twist here: if parent NOT included, may need to induce output of - // surrounding START_OBJECT/END_OBJECT - if (_includeImmediateParent && !_headContext.isStartHandled()) { - t = _headContext.nextTokenToRead(); // returns START_OBJECT but also marks it handled - _exposedContext = _headContext; - } - } - return (_currToken = t); - } - if (f == null) { - delegate.nextToken(); - delegate.skipChildren(); - break; - } - f = f.includeProperty(name); - if (f == null) { - delegate.nextToken(); - delegate.skipChildren(); - break; - } - _itemFilter = f; - if (f == TokenFilter.INCLUDE_ALL) { - if (_includePath) { - return (_currToken = t); - } - } - if (_includePath) { - t = _nextTokenWithBuffering(_headContext); - if (t != null) { - _currToken = t; - return t; - } - } - break; - } - - default: // scalar value - f = _itemFilter; - if (f == TokenFilter.INCLUDE_ALL) { - return (_currToken = t); - } - if (f != null) { - f = _headContext.checkValue(f); - if ((f == TokenFilter.INCLUDE_ALL) - || ((f != null) && f.includeValue(delegate))) { - return (_currToken = t); - } - } - // Otherwise not included (leaves must be explicitly included) - break; - } - - // We get here if token was not yet found; offlined handling - return _nextToken2(); - } - - /** - * Offlined handling for cases where there was no buffered token to - * return, and the token read next could not be returned as-is, - * at least not yet, but where we have not yet established that - * buffering is needed. - */ - protected final JsonToken _nextToken2() throws IOException - { - main_loop: - while (true) { - JsonToken t = delegate.nextToken(); - if (t == null) { // is this even legal? - _currToken = t; - return t; - } - TokenFilter f; - - switch (t.id()) { - case ID_START_ARRAY: - f = _itemFilter; - if (f == TokenFilter.INCLUDE_ALL) { - _headContext = _headContext.createChildArrayContext(f, true); - return (_currToken = t); - } - if (f == null) { // does this occur? - delegate.skipChildren(); - continue main_loop; - } - // Otherwise still iffy, need to check - f = _headContext.checkValue(f); - if (f == null) { - delegate.skipChildren(); - continue main_loop; - } - if (f != TokenFilter.INCLUDE_ALL) { - f = f.filterStartArray(); - } - _itemFilter = f; - if (f == TokenFilter.INCLUDE_ALL) { - _headContext = _headContext.createChildArrayContext(f, true); - return (_currToken = t); - } - _headContext = _headContext.createChildArrayContext(f, false); - // but if we didn't figure it out yet, need to buffer possible events - if (_includePath) { - t = _nextTokenWithBuffering(_headContext); - if (t != null) { - _currToken = t; - return t; - } - } - continue main_loop; - - case ID_START_OBJECT: - f = _itemFilter; - if (f == TokenFilter.INCLUDE_ALL) { - _headContext = _headContext.createChildObjectContext(f, true); - return (_currToken = t); - } - if (f == null) { // does this occur? - delegate.skipChildren(); - continue main_loop; - } - // Otherwise still iffy, need to check - f = _headContext.checkValue(f); - if (f == null) { - delegate.skipChildren(); - continue main_loop; - } - if (f != TokenFilter.INCLUDE_ALL) { - f = f.filterStartObject(); - } - _itemFilter = f; - if (f == TokenFilter.INCLUDE_ALL) { - _headContext = _headContext.createChildObjectContext(f, true); - return (_currToken = t); - } - _headContext = _headContext.createChildObjectContext(f, false); - if (_includePath) { - t = _nextTokenWithBuffering(_headContext); - if (t != null) { - _currToken = t; - return t; - } - } - continue main_loop; - - case ID_END_ARRAY: - case ID_END_OBJECT: - { - boolean returnEnd = _headContext.isStartHandled(); - f = _headContext.getFilter(); - if ((f != null) && (f != TokenFilter.INCLUDE_ALL)) { - f.filterFinishArray(); - } - _headContext = _headContext.getParent(); - _itemFilter = _headContext.getFilter(); - if (returnEnd) { - return (_currToken = t); - } - } - continue main_loop; - - case ID_FIELD_NAME: - { - final String name = delegate.getCurrentName(); - f = _headContext.setFieldName(name); - if (f == TokenFilter.INCLUDE_ALL) { - _itemFilter = f; - return (_currToken = t); - } - if (f == null) { // filter out the value - delegate.nextToken(); - delegate.skipChildren(); - continue main_loop; - } - f = f.includeProperty(name); - if (f == null) { // filter out the value - delegate.nextToken(); - delegate.skipChildren(); - continue main_loop; - } - _itemFilter = f; - if (f == TokenFilter.INCLUDE_ALL) { - if (_includePath) { - return (_currToken = t); - } -// if (_includeImmediateParent) { ... - continue main_loop; - } - if (_includePath) { - t = _nextTokenWithBuffering(_headContext); - if (t != null) { - _currToken = t; - return t; - } - } - } - continue main_loop; - - default: // scalar value - f = _itemFilter; - if (f == TokenFilter.INCLUDE_ALL) { - return (_currToken = t); - } - if (f != null) { - f = _headContext.checkValue(f); - if ((f == TokenFilter.INCLUDE_ALL) - || ((f != null) && f.includeValue(delegate))) { - return (_currToken = t); - } - } - // Otherwise not included (leaves must be explicitly included) - break; - } - } - } - - /** - * Method called when a new potentially included context is found. - */ - protected final JsonToken _nextTokenWithBuffering(final TokenFilterContext buffRoot) - throws IOException - { - main_loop: - while (true) { - JsonToken t = delegate.nextToken(); - if (t == null) { // is this even legal? - return t; - } - TokenFilter f; - - // One simplification here: we know for a fact that the item filter is - // neither null nor 'include all', for most cases; the only exception - // being FIELD_NAME handling - - switch (t.id()) { - case ID_START_ARRAY: - f = _headContext.checkValue(_itemFilter); - if (f == null) { - delegate.skipChildren(); - continue main_loop; - } - if (f != TokenFilter.INCLUDE_ALL) { - f = f.filterStartArray(); - } - _itemFilter = f; - if (f == TokenFilter.INCLUDE_ALL) { - _headContext = _headContext.createChildArrayContext(f, true); - return _nextBuffered(buffRoot); - } - _headContext = _headContext.createChildArrayContext(f, false); - continue main_loop; - - case ID_START_OBJECT: - f = _itemFilter; - if (f == TokenFilter.INCLUDE_ALL) { - _headContext = _headContext.createChildObjectContext(f, true); - return t; - } - if (f == null) { // does this occur? - delegate.skipChildren(); - continue main_loop; - } - // Otherwise still iffy, need to check - f = _headContext.checkValue(f); - if (f == null) { - delegate.skipChildren(); - continue main_loop; - } - if (f != TokenFilter.INCLUDE_ALL) { - f = f.filterStartObject(); - } - _itemFilter = f; - if (f == TokenFilter.INCLUDE_ALL) { - _headContext = _headContext.createChildObjectContext(f, true); - return _nextBuffered(buffRoot); - } - _headContext = _headContext.createChildObjectContext(f, false); - continue main_loop; - - case ID_END_ARRAY: - case ID_END_OBJECT: - { - // Unlike with other loops, here we know that content was NOT - // included (won't get this far otherwise) - f = _headContext.getFilter(); - if ((f != null) && (f != TokenFilter.INCLUDE_ALL)) { - f.filterFinishArray(); - } - boolean gotEnd = (_headContext == buffRoot); - boolean returnEnd = gotEnd && _headContext.isStartHandled(); - - _headContext = _headContext.getParent(); - _itemFilter = _headContext.getFilter(); - - if (returnEnd) { - return t; - } - // Hmmh. Do we need both checks, or should above suffice? - if (gotEnd || (_headContext == buffRoot)) { - return null; - } - } - continue main_loop; - - case ID_FIELD_NAME: - { - final String name = delegate.getCurrentName(); - f = _headContext.setFieldName(name); - if (f == TokenFilter.INCLUDE_ALL) { - _itemFilter = f; - return _nextBuffered(buffRoot); - } - if (f == null) { // filter out the value - delegate.nextToken(); - delegate.skipChildren(); - continue main_loop; - } - f = f.includeProperty(name); - if (f == null) { // filter out the value - delegate.nextToken(); - delegate.skipChildren(); - continue main_loop; - } - _itemFilter = f; - if (f == TokenFilter.INCLUDE_ALL) { - return _nextBuffered(buffRoot); - } - } - continue main_loop; - - default: // scalar value - f = _itemFilter; - if (f == TokenFilter.INCLUDE_ALL) { - return _nextBuffered(buffRoot); - } - if (f != null) { - f = _headContext.checkValue(f); - if ((f == TokenFilter.INCLUDE_ALL) - || ((f != null) && f.includeValue(delegate))) { - return _nextBuffered(buffRoot); - } - } - // Otherwise not included (leaves must be explicitly included) - continue main_loop; - } - } - } - - private JsonToken _nextBuffered(TokenFilterContext buffRoot) throws IOException - { - _exposedContext = buffRoot; - TokenFilterContext ctxt = buffRoot; - JsonToken t = ctxt.nextTokenToRead(); - if (t != null) { - return t; - } - while (true) { - // all done with buffered stuff? - if (ctxt == _headContext) { - throw _constructError("Internal error: failed to locate expected buffered tokens"); - /* - _exposedContext = null; - break; - */ - } - // If not, traverse down the context chain - ctxt = _exposedContext.findChildOf(ctxt); - _exposedContext = ctxt; - if (ctxt == null) { // should never occur - throw _constructError("Unexpected problem: chain of filtered context broken"); - } - t = _exposedContext.nextTokenToRead(); - if (t != null) { - return t; - } - } - } - - @Override - public JsonToken nextValue() throws IOException { - // Re-implemented same as ParserMinimalBase: - JsonToken t = nextToken(); - if (t == JsonToken.FIELD_NAME) { - t = nextToken(); - } - return t; - } - - /** - * Need to override, re-implement similar to how method defined in - * {@link autosaveworld.zlibs.com.fasterxml.jackson.core.base.ParserMinimalBase}, to keep - * state correct here. - */ - @Override - public JsonParser skipChildren() throws IOException - { - if ((_currToken != JsonToken.START_OBJECT) - && (_currToken != JsonToken.START_ARRAY)) { - return this; - } - int open = 1; - - // Since proper matching of start/end markers is handled - // by nextToken(), we'll just count nesting levels here - while (true) { - JsonToken t = nextToken(); - if (t == null) { // not ideal but for now, just return - return this; - } - if (t.isStructStart()) { - ++open; - } else if (t.isStructEnd()) { - if (--open == 0) { - return this; - } - } - } - } - - /* - /********************************************************** - /* Public API, access to token information, text - /********************************************************** - */ - - @Override public String getText() throws IOException { return delegate.getText(); } - @Override public boolean hasTextCharacters() { return delegate.hasTextCharacters(); } - @Override public char[] getTextCharacters() throws IOException { return delegate.getTextCharacters(); } - @Override public int getTextLength() throws IOException { return delegate.getTextLength(); } - @Override public int getTextOffset() throws IOException { return delegate.getTextOffset(); } - - /* - /********************************************************** - /* Public API, access to token information, numeric - /********************************************************** - */ - - @Override - public BigInteger getBigIntegerValue() throws IOException { return delegate.getBigIntegerValue(); } - - @Override - public boolean getBooleanValue() throws IOException { return delegate.getBooleanValue(); } - - @Override - public byte getByteValue() throws IOException { return delegate.getByteValue(); } - - @Override - public short getShortValue() throws IOException { return delegate.getShortValue(); } - - @Override - public BigDecimal getDecimalValue() throws IOException { return delegate.getDecimalValue(); } - - @Override - public double getDoubleValue() throws IOException { return delegate.getDoubleValue(); } - - @Override - public float getFloatValue() throws IOException { return delegate.getFloatValue(); } - - @Override - public int getIntValue() throws IOException { return delegate.getIntValue(); } - - @Override - public long getLongValue() throws IOException { return delegate.getLongValue(); } - - @Override - public NumberType getNumberType() throws IOException { return delegate.getNumberType(); } - - @Override - public Number getNumberValue() throws IOException { return delegate.getNumberValue(); } - - /* - /********************************************************** - /* Public API, access to token information, coercion/conversion - /********************************************************** - */ - - @Override public int getValueAsInt() throws IOException { return delegate.getValueAsInt(); } - @Override public int getValueAsInt(int defaultValue) throws IOException { return delegate.getValueAsInt(defaultValue); } - @Override public long getValueAsLong() throws IOException { return delegate.getValueAsLong(); } - @Override public long getValueAsLong(long defaultValue) throws IOException { return delegate.getValueAsLong(defaultValue); } - @Override public double getValueAsDouble() throws IOException { return delegate.getValueAsDouble(); } - @Override public double getValueAsDouble(double defaultValue) throws IOException { return delegate.getValueAsDouble(defaultValue); } - @Override public boolean getValueAsBoolean() throws IOException { return delegate.getValueAsBoolean(); } - @Override public boolean getValueAsBoolean(boolean defaultValue) throws IOException { return delegate.getValueAsBoolean(defaultValue); } - @Override public String getValueAsString() throws IOException { return delegate.getValueAsString(); } - @Override public String getValueAsString(String defaultValue) throws IOException { return delegate.getValueAsString(defaultValue); } - - /* - /********************************************************** - /* Public API, access to token values, other - /********************************************************** - */ - - @Override public Object getEmbeddedObject() throws IOException { return delegate.getEmbeddedObject(); } - @Override public byte[] getBinaryValue(Base64Variant b64variant) throws IOException { return delegate.getBinaryValue(b64variant); } - @Override public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws IOException { return delegate.readBinaryValue(b64variant, out); } - @Override public JsonLocation getTokenLocation() { return delegate.getTokenLocation(); } - - /* - /********************************************************** - /* Internal helper methods - /********************************************************** - */ - - protected JsonStreamContext _filterContext() { - if (_exposedContext != null) { - return _exposedContext; - } - return _headContext; - } - -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/filter/JsonPointerBasedFilter.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/filter/JsonPointerBasedFilter.java deleted file mode 100644 index 75c7f458..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/filter/JsonPointerBasedFilter.java +++ /dev/null @@ -1,69 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.filter; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonPointer; - -/** - * Simple {@link TokenFilter} implementation that takes a single - * {@link JsonPointer} and matches a single value accordingly. - * Instances are immutable and fully thread-safe, shareable, - * and efficient to use. - * - * @since 2.6 - */ -public class JsonPointerBasedFilter extends TokenFilter -{ - protected final JsonPointer _pathToMatch; - - public JsonPointerBasedFilter(String ptrExpr) { - this(JsonPointer.compile(ptrExpr)); - } - - public JsonPointerBasedFilter(JsonPointer match) { - _pathToMatch = match; - } - - @Override - public TokenFilter includeElement(int index) { - JsonPointer next = _pathToMatch.matchElement(index); - if (next == null) { - return null; - } - if (next.matches()) { - return TokenFilter.INCLUDE_ALL; - } - return new JsonPointerBasedFilter(next); - } - - @Override - public TokenFilter includeProperty(String name) { - JsonPointer next = _pathToMatch.matchProperty(name); - if (next == null) { - return null; - } - if (next.matches()) { - return TokenFilter.INCLUDE_ALL; - } - return new JsonPointerBasedFilter(next); - } - - @Override - public TokenFilter filterStartArray() { - return this; - } - - @Override - public TokenFilter filterStartObject() { - return this; - } - - @Override - protected boolean _includeScalar() { - // should only occur for root-level scalars, path "/" - return _pathToMatch.matches(); - } - - @Override - public String toString() { - return "[JsonPointerFilter at: "+_pathToMatch+"]"; - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/filter/TokenFilter.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/filter/TokenFilter.java deleted file mode 100644 index fd5c66f9..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/filter/TokenFilter.java +++ /dev/null @@ -1,363 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.filter; - -import java.io.IOException; -import java.math.BigDecimal; -import java.math.BigInteger; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; - -/** - * Strategy class that can be implemented to specify actual inclusion/exclusion - * criteria for filtering, used by {@link FilteringGeneratorDelegate}. - * - * @since 2.6 - */ -public class TokenFilter -{ - - // // Marker values - - /** - * Marker value that should be used to indicate inclusion of a structured - * value (sub-tree representing Object or Array), or value of a named - * property (regardless of type). - * Note that if this instance is returned, it will used as a marker, and - * no actual callbacks need to be made. For this reason, it is more efficient - * to return this instance if the whole sub-tree is to be included, instead - * of implementing similar filter functionality explicitly. - */ - public final static TokenFilter INCLUDE_ALL = new TokenFilter(); - - // Life-cycle - - protected TokenFilter() { } - - /* - /********************************************************** - /* API, structured values - /********************************************************** - */ - - /** - * Method called to check whether Object value at current output - * location should be included in output. - * Three kinds of return values may be used as follows: - *

    - *
  • null to indicate that the Object should be skipped - *
  • - *
  • {@link #INCLUDE_ALL} to indicate that the Object should be included - * completely in output - *
  • - *
  • Any other {@link TokenFilter} implementation (possibly this one) to mean - * that further inclusion calls on return filter object need to be made - * on contained properties, as necessary. {@link #filterFinishObject()} will - * also be called on returned filter object - *
  • - *
- *

- * Default implementation returns this, which means that checks - * are made recursively for properties of the Object to determine possible inclusion. - * - * @return TokenFilter to use for further calls within Array, unless return value - * is null or {@link #INCLUDE_ALL} (which have simpler semantics) - */ - public TokenFilter filterStartObject() { - return this; - } - - /** - * Method called to check whether Array value at current output - * location should be included in output. - * Three kinds of return values may be used as follows: - *

    - *
  • null to indicate that the Array should be skipped - *
  • - *
  • {@link #INCLUDE_ALL} to indicate that the Array should be included - * completely in output - *
  • - *
  • Any other {@link TokenFilter} implementation (possibly this one) to mean - * that further inclusion calls on return filter object need to be made - * on contained element values, as necessary. {@link #filterFinishArray()} will - * also be called on returned filter object - *
  • - *
- *

- * Default implementation returns this, which means that checks - * are made recursively for elements of the array to determine possible inclusion. - * - * @return TokenFilter to use for further calls within Array, unless return value - * is null or {@link #INCLUDE_ALL} (which have simpler semantics) - */ - public TokenFilter filterStartArray() { - return this; - } - - /** - * Method called to indicate that output of non-filtered Object (one that may - * have been included either completely, or in part) is completed, - * in cases where filter other that {@link #INCLUDE_ALL} was returned. - * This occurs when {@link JsonGenerator#writeEndObject()} is called. - */ - public void filterFinishObject() { } - - /** - * Method called to indicate that output of non-filtered Array (one that may - * have been included either completely, or in part) is completed, - * in cases where filter other that {@link #INCLUDE_ALL} was returned. - * This occurs when {@link JsonGenerator#writeEndArray()} is called. - */ - public void filterFinishArray() { } - - /* - /********************************************************** - /* API, properties/elements - /********************************************************** - */ - - /** - * Method called to check whether property value with specified name, - * at current output location, should be included in output. - * Three kinds of return values may be used as follows: - *

    - *
  • null to indicate that the property and its value should be skipped - *
  • - *
  • {@link #INCLUDE_ALL} to indicate that the property and its value should be included - * completely in output - *
  • - *
  • Any other {@link TokenFilter} implementation (possibly this one) to mean - * that further inclusion calls on returned filter object need to be made - * as necessary, to determine inclusion. - *
  • - *
- *

- * The default implementation simply returns this to continue calling - * methods on this filter object, without full inclusion or exclusion. - * - * @return TokenFilter to use for further calls within property value, unless return value - * is null or {@link #INCLUDE_ALL} (which have simpler semantics) - */ - public TokenFilter includeProperty(String name) { - return this; - } - - /** - * Method called to check whether array element with specified index (zero-based), - * at current output location, should be included in output. - * Three kinds of return values may be used as follows: - *

    - *
  • null to indicate that the Array element should be skipped - *
  • - *
  • {@link #INCLUDE_ALL} to indicate that the Array element should be included - * completely in output - *
  • - *
  • Any other {@link TokenFilter} implementation (possibly this one) to mean - * that further inclusion calls on returned filter object need to be made - * as necessary, to determine inclusion. - *
  • - *
- *

- * The default implementation simply returns this to continue calling - * methods on this filter object, without full inclusion or exclusion. - * - * @return TokenFilter to use for further calls within element value, unless return value - * is null or {@link #INCLUDE_ALL} (which have simpler semantics) - */ - public TokenFilter includeElement(int index) { - return this; - } - - /** - * Method called to check whether root-level value, - * at current output location, should be included in output. - * Three kinds of return values may be used as follows: - *

    - *
  • null to indicate that the root value should be skipped - *
  • - *
  • {@link #INCLUDE_ALL} to indicate that the root value should be included - * completely in output - *
  • - *
  • Any other {@link TokenFilter} implementation (possibly this one) to mean - * that further inclusion calls on returned filter object need to be made - * as necessary, to determine inclusion. - *
  • - *
- *

- * The default implementation simply returns this to continue calling - * methods on this filter object, without full inclusion or exclusion. - * - * @return TokenFilter to use for further calls within root value, unless return value - * is null or {@link #INCLUDE_ALL} (which have simpler semantics) - */ - public TokenFilter includeRootValue(int index) { - return this; - } - - /* - /********************************************************** - /* API, scalar values (being read) - /********************************************************** - */ - - /** - * Call made when verifying whether a scaler value is being - * read from a parser. - *

- * Default action is to call _includeScalar() and return - * whatever it indicates. - */ - public boolean includeValue(JsonParser p) throws IOException { - return _includeScalar(); - } - - /* - /********************************************************** - /* API, scalar values (being written) - /********************************************************** - */ - - /** - * Call made to verify whether leaf-level - * boolean value - * should be included in output or not. - */ - public boolean includeBoolean(boolean value) { - return _includeScalar(); - } - - /** - * Call made to verify whether leaf-level - * null value - * should be included in output or not. - */ - public boolean includeNull() { - return _includeScalar(); - } - - /** - * Call made to verify whether leaf-level - * String value - * should be included in output or not. - */ - public boolean includeString(String value) { - return _includeScalar(); - } - - /** - * Call made to verify whether leaf-level - * int value - * should be included in output or not. - * - * NOTE: also called for `short`, `byte` - */ - public boolean includeNumber(int v) { - return _includeScalar(); - } - - /** - * Call made to verify whether leaf-level - * long value - * should be included in output or not. - */ - public boolean includeNumber(long v) { - return _includeScalar(); - } - - /** - * Call made to verify whether leaf-level - * float value - * should be included in output or not. - */ - public boolean includeNumber(float v) { - return _includeScalar(); - } - - /** - * Call made to verify whether leaf-level - * double value - * should be included in output or not. - */ - public boolean includeNumber(double v) { - return _includeScalar(); - } - - /** - * Call made to verify whether leaf-level - * {@link BigDecimal} value - * should be included in output or not. - */ - public boolean includeNumber(BigDecimal v) { - return _includeScalar(); - } - - /** - * Call made to verify whether leaf-level - * {@link BigInteger} value - * should be included in output or not. - */ - public boolean includeNumber(BigInteger v) { - return _includeScalar(); - } - - /** - * Call made to verify whether leaf-level - * Binary value - * should be included in output or not. - *

- * NOTE: no binary payload passed; assumption is this won't be of much use. - */ - public boolean includeBinary() { - return _includeScalar(); - } - - /** - * Call made to verify whether leaf-level - * raw (pre-encoded, not quoted by generator) value - * should be included in output or not. - *

- * NOTE: value itself not passed since it may come on multiple forms - * and is unlikely to be of much use in determining inclusion - * criteria. - */ - public boolean includeRawValue() { - return _includeScalar(); - } - - /** - * Call made to verify whether leaf-level - * embedded (Opaque) value - * should be included in output or not. - */ - public boolean includeEmbeddedValue(Object ob) { - return _includeScalar(); - } - - /* - /********************************************************** - /* Overrides - /********************************************************** - */ - - @Override - public String toString() { - if (this == INCLUDE_ALL) { - return "TokenFilter.INCLUDE_ALL"; - } - return super.toString(); - } - - /* - /********************************************************** - /* Other methods - /********************************************************** - */ - - /** - * Overridable default implementation delegated to all scalar value - * inclusion check methods. - * The default implementation simply includes all leaf values. - */ - protected boolean _includeScalar() { - return true; - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/filter/TokenFilterContext.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/filter/TokenFilterContext.java deleted file mode 100644 index 37e191a8..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/filter/TokenFilterContext.java +++ /dev/null @@ -1,356 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.filter; - -import java.io.IOException; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonProcessingException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonStreamContext; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * Alternative variant of {@link JsonStreamContext}, used when filtering - * content being read or written (based on {@link TokenFilter}). - * - * @since 2.6 - */ -public class TokenFilterContext extends JsonStreamContext -{ - /** - * Parent context for this context; null for root context. - */ - protected final TokenFilterContext _parent; - - /* - /********************************************************** - /* Simple instance reuse slots; speed up things - /* a bit (10-15%) for docs with lots of small - /* arrays/objects - /********************************************************** - */ - - protected TokenFilterContext _child; - - /* - /********************************************************** - /* Location/state information - /********************************************************** - */ - - /** - * Name of the field of which value is to be parsed; only - * used for OBJECT contexts - */ - protected String _currentName; - - /** - * Filter to use for items in this state (for properties of Objects, - * elements of Arrays, and root-level values of root context) - */ - protected TokenFilter _filter; - - /** - * Flag that indicates that start token has been read/written, - * so that matching close token needs to be read/written as well - * when context is getting closed. - */ - protected boolean _startHandled; - - /** - * Flag that indicates that the current name of this context - * still needs to be read/written, if path from root down to - * included leaf is to be exposed. - */ - protected boolean _needToHandleName; - - /* - /********************************************************** - /* Life-cycle - /********************************************************** - */ - - protected TokenFilterContext(int type, TokenFilterContext parent, - TokenFilter filter, boolean startHandled) - { - super(); - _type = type; - _parent = parent; - _filter = filter; - _index = -1; - _startHandled = startHandled; - _needToHandleName = false; - } - - protected TokenFilterContext reset(int type, - TokenFilter filter, boolean startWritten) - { - _type = type; - _filter = filter; - _index = -1; - _currentName = null; - _startHandled = startWritten; - _needToHandleName = false; - return this; - } - - /* - /********************************************************** - /* Factory methods - /********************************************************** - */ - - public static TokenFilterContext createRootContext(TokenFilter filter) { - // true -> since we have no start/end marker, consider start handled - return new TokenFilterContext(TYPE_ROOT, null, filter, true); - } - - public TokenFilterContext createChildArrayContext(TokenFilter filter, boolean writeStart) { - TokenFilterContext ctxt = _child; - if (ctxt == null) { - _child = ctxt = new TokenFilterContext(TYPE_ARRAY, this, filter, writeStart); - return ctxt; - } - return ctxt.reset(TYPE_ARRAY, filter, writeStart); - } - - public TokenFilterContext createChildObjectContext(TokenFilter filter, boolean writeStart) { - TokenFilterContext ctxt = _child; - if (ctxt == null) { - _child = ctxt = new TokenFilterContext(TYPE_OBJECT, this, filter, writeStart); - return ctxt; - } - return ctxt.reset(TYPE_OBJECT, filter, writeStart); - } - - /* - /********************************************************** - /* State changes - /********************************************************** - */ - - public TokenFilter setFieldName(String name) throws JsonProcessingException { - _currentName = name; - _needToHandleName = true; - return _filter; - } - - /** - * Method called to check whether value is to be included at current output - * position, either as Object property, Array element, or root value. - */ - public TokenFilter checkValue(TokenFilter filter) { - // First, checks for Object properties have been made earlier: - if (_type == TYPE_OBJECT) { - return filter; - } - // We increase it first because at the beginning of array, value is -1 - int ix = ++_index; - if (_type == TYPE_ARRAY) { - return filter.includeElement(ix); - } - return filter.includeRootValue(ix); - } - - /** - * Method called to ensure that parent path from root is written up to - * and including this node. - */ - public void writePath(JsonGenerator gen) throws IOException - { - if ((_filter == null) || (_filter == TokenFilter.INCLUDE_ALL)) { - return; - } - if (_parent != null) { - _parent._writePath(gen); - } - if (_startHandled) { - // even if Object started, need to start leaf-level name - if (_needToHandleName) { - gen.writeFieldName(_currentName); - } - } else { - _startHandled = true; - if (_type == TYPE_OBJECT) { - gen.writeStartObject(); - gen.writeFieldName(_currentName); // we know name must be written - } else if (_type == TYPE_ARRAY) { - gen.writeStartArray(); - } - } - } - - /** - * Variant of {@link #writePath(JsonGenerator)} called when all we - * need is immediately surrounding Object. Method typically called - * when including a single property but not including full path - * to root. - */ - public void writeImmediatePath(JsonGenerator gen) throws IOException - { - if ((_filter == null) || (_filter == TokenFilter.INCLUDE_ALL)) { - return; - } - if (_startHandled) { - // even if Object started, need to start leaf-level name - if (_needToHandleName) { - gen.writeFieldName(_currentName); - } - } else { - _startHandled = true; - if (_type == TYPE_OBJECT) { - gen.writeStartObject(); - if (_needToHandleName) { - gen.writeFieldName(_currentName); - } - } else if (_type == TYPE_ARRAY) { - gen.writeStartArray(); - } - } - } - - private void _writePath(JsonGenerator gen) throws IOException - { - if ((_filter == null) || (_filter == TokenFilter.INCLUDE_ALL)) { - return; - } - if (_parent != null) { - _parent._writePath(gen); - } - if (_startHandled) { - // even if Object started, need to start leaf-level name - if (_needToHandleName) { - _needToHandleName = false; // at parent must explicitly clear - gen.writeFieldName(_currentName); - } - } else { - _startHandled = true; - if (_type == TYPE_OBJECT) { - gen.writeStartObject(); - if (_needToHandleName) { - _needToHandleName = false; // at parent must explicitly clear - gen.writeFieldName(_currentName); - } - } else if (_type == TYPE_ARRAY) { - gen.writeStartArray(); - } - } - } - - public TokenFilterContext closeArray(JsonGenerator gen) throws IOException - { - if (_startHandled) { - gen.writeEndArray(); - } - if ((_filter != null) && (_filter != TokenFilter.INCLUDE_ALL)) { - _filter.filterFinishArray(); - } - return _parent; - } - - public TokenFilterContext closeObject(JsonGenerator gen) throws IOException - { - if (_startHandled) { - gen.writeEndObject(); - } - if ((_filter != null) && (_filter != TokenFilter.INCLUDE_ALL)) { - _filter.filterFinishObject(); - } - return _parent; - } - - public void skipParentChecks() { - _filter = null; - for (TokenFilterContext ctxt = _parent; ctxt != null; ctxt = ctxt._parent) { - _parent._filter = null; - } - } - - /* - /********************************************************** - /* Accessors, mutators - /********************************************************** - */ - - @Override - public Object getCurrentValue() { return null; } - - @Override - public void setCurrentValue(Object v) { } - - @Override public final TokenFilterContext getParent() { return _parent; } - @Override public final String getCurrentName() { return _currentName; } - - public TokenFilter getFilter() { return _filter; } - public boolean isStartHandled() { return _startHandled; } - - public JsonToken nextTokenToRead() { - if (!_startHandled) { - _startHandled = true; - if (_type == TYPE_OBJECT) { - return JsonToken.START_OBJECT; - } - // Note: root should never be unhandled - return JsonToken.START_ARRAY; - } - // But otherwise at most might have FIELD_NAME - if (_needToHandleName && (_type == TYPE_OBJECT)) { - _needToHandleName = false; - return JsonToken.FIELD_NAME; - } - return null; - } - - public TokenFilterContext findChildOf(TokenFilterContext parent) { - if (_parent == parent) { - return this; - } - TokenFilterContext curr = _parent; - while (curr != null) { - TokenFilterContext p = curr._parent; - if (p == parent) { - return curr; - } - curr = p; - } - // should never occur but... - return null; - } - - // // // Internally used abstract methods - - protected void appendDesc(StringBuilder sb) { - if (_parent != null) { - _parent.appendDesc(sb); - } - if (_type == TYPE_OBJECT) { - sb.append('{'); - if (_currentName != null) { - sb.append('"'); - // !!! TODO: Name chars should be escaped? - sb.append(_currentName); - sb.append('"'); - } else { - sb.append('?'); - } - sb.append('}'); - } else if (_type == TYPE_ARRAY) { - sb.append('['); - sb.append(getCurrentIndex()); - sb.append(']'); - } else { - // nah, ROOT: - sb.append("/"); - } - } - - // // // Overridden standard methods - - /** - * Overridden to provide developer writeable "JsonPath" representation - * of the context. - */ - @Override public String toString() { - StringBuilder sb = new StringBuilder(64); - appendDesc(sb); - return sb.toString(); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/format/DataFormatDetector.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/format/DataFormatDetector.java deleted file mode 100644 index 1158a9bc..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/format/DataFormatDetector.java +++ /dev/null @@ -1,203 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.format; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Collection; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonFactory; - -/** - * Simple helper class that allows data format (content type) auto-detection, - * given an ordered set of {@link JsonFactory} instances to use for actual low-level - * detection. - */ -public class DataFormatDetector -{ - /** - * By default we will look ahead at most 64 bytes; in most cases, - * much less (4 bytes or so) is needed, but we will allow bit more - * leniency to support data formats that need more complex heuristics. - */ - public final static int DEFAULT_MAX_INPUT_LOOKAHEAD = 64; - - /** - * Ordered list of factories which both represent data formats to - * detect (in precedence order, starting with highest) and are used - * for actual detection. - */ - protected final JsonFactory[] _detectors; - - /** - * Strength of match we consider to be good enough to be used - * without checking any other formats. - * Default value is {@link MatchStrength#SOLID_MATCH}, - */ - protected final MatchStrength _optimalMatch; - - /** - * Strength of minimal match we accept as the answer, unless - * better matches are found. - * Default value is {@link MatchStrength#WEAK_MATCH}, - */ - protected final MatchStrength _minimalMatch; - - /** - * Maximum number of leading bytes of the input that we can read - * to determine data format. - *

- * Default value is {@link #DEFAULT_MAX_INPUT_LOOKAHEAD}. - */ - protected final int _maxInputLookahead; - - /* - /********************************************************** - /* Construction - /********************************************************** - */ - - public DataFormatDetector(JsonFactory... detectors) { - this(detectors, MatchStrength.SOLID_MATCH, MatchStrength.WEAK_MATCH, - DEFAULT_MAX_INPUT_LOOKAHEAD); - } - - public DataFormatDetector(Collection detectors) { - this(detectors.toArray(new JsonFactory[detectors.size()])); - } - - /** - * Method that will return a detector instance that uses given - * optimal match level (match that is considered sufficient to return, without - * trying to find stronger matches with other formats). - */ - public DataFormatDetector withOptimalMatch(MatchStrength optMatch) { - if (optMatch == _optimalMatch) { - return this; - } - return new DataFormatDetector(_detectors, optMatch, _minimalMatch, _maxInputLookahead); - } - /** - * Method that will return a detector instance that uses given - * minimal match level; match that may be returned unless a stronger match - * is found with other format detectors. - */ - public DataFormatDetector withMinimalMatch(MatchStrength minMatch) { - if (minMatch == _minimalMatch) { - return this; - } - return new DataFormatDetector(_detectors, _optimalMatch, minMatch, _maxInputLookahead); - } - - /** - * Method that will return a detector instance that allows detectors to - * read up to specified number of bytes when determining format match strength. - */ - public DataFormatDetector withMaxInputLookahead(int lookaheadBytes) { - if (lookaheadBytes == _maxInputLookahead) { - return this; - } - return new DataFormatDetector(_detectors, _optimalMatch, _minimalMatch, lookaheadBytes); - } - - private DataFormatDetector(JsonFactory[] detectors, - MatchStrength optMatch, MatchStrength minMatch, int maxInputLookahead) { - _detectors = detectors; - _optimalMatch = optMatch; - _minimalMatch = minMatch; - _maxInputLookahead = maxInputLookahead; - } - - /* - /********************************************************** - /* Public API - /********************************************************** - */ - - /** - * Method to call to find format that content (accessible via given - * {@link InputStream}) given has, as per configuration of this detector - * instance. - * - * @return Matcher object which contains result; never null, even in cases - * where no match (with specified minimal match strength) is found. - */ - public DataFormatMatcher findFormat(InputStream in) throws IOException { - return _findFormat(new InputAccessor.Std(in, new byte[_maxInputLookahead])); - } - - /** - * Method to call to find format that given content (full document) - * has, as per configuration of this detector instance. - * - * @return Matcher object which contains result; never null, even in cases - * where no match (with specified minimal match strength) is found. - */ - public DataFormatMatcher findFormat(byte[] fullInputData) throws IOException { - return _findFormat(new InputAccessor.Std(fullInputData)); - } - - /** - * Method to call to find format that given content (full document) - * has, as per configuration of this detector instance. - * - * @return Matcher object which contains result; never null, even in cases - * where no match (with specified minimal match strength) is found. - * - * @since 2.1 - */ - public DataFormatMatcher findFormat(byte[] fullInputData, int offset, int len) throws IOException { - return _findFormat(new InputAccessor.Std(fullInputData, offset, len)); - } - - /* - /********************************************************** - /* Overrides - /********************************************************** - */ - - @Override public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append('['); - final int len = _detectors.length; - if (len > 0) { - sb.append(_detectors[0].getFormatName()); - for (int i = 1; i < len; ++i) { - sb.append(", "); - sb.append(_detectors[i].getFormatName()); - } - } - sb.append(']'); - return sb.toString(); - } - - /* - /********************************************************** - /* Internal methods - /********************************************************** - */ - - private DataFormatMatcher _findFormat(InputAccessor.Std acc) throws IOException { - JsonFactory bestMatch = null; - MatchStrength bestMatchStrength = null; - for (JsonFactory f : _detectors) { - acc.reset(); - MatchStrength strength = f.hasFormat(acc); - // if not better than what we have so far (including minimal level limit), skip - if (strength == null || strength.ordinal() < _minimalMatch.ordinal()) { - continue; - } - // also, needs to better match than before - if (bestMatch != null) { - if (bestMatchStrength.ordinal() >= strength.ordinal()) { - continue; - } - } - // finally: if it's good enough match, we are done - bestMatch = f; - bestMatchStrength = strength; - if (strength.ordinal() >= _optimalMatch.ordinal()) { - break; - } - } - return acc.createMatcher(bestMatch, bestMatchStrength); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/format/DataFormatMatcher.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/format/DataFormatMatcher.java deleted file mode 100644 index cab092aa..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/format/DataFormatMatcher.java +++ /dev/null @@ -1,126 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.format; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonFactory; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.MergedStream; - -/** - * Result object constructed by {@link DataFormatDetector} when requested - * to detect format of given input data. - */ -public class DataFormatMatcher -{ - protected final InputStream _originalStream; - - /** - * Content read during format matching process - */ - protected final byte[] _bufferedData; - - /** - * Pointer to the first byte in buffer available for reading - */ - protected final int _bufferedStart; - - /** - * Number of bytes available in buffer. - */ - protected final int _bufferedLength; - - /** - * Factory that produced sufficient match (if any) - */ - protected final JsonFactory _match; - - /** - * Strength of match with {@link #_match} - */ - protected final MatchStrength _matchStrength; - - protected DataFormatMatcher(InputStream in, byte[] buffered, - int bufferedStart, int bufferedLength, - JsonFactory match, MatchStrength strength) - { - _originalStream = in; - _bufferedData = buffered; - _bufferedStart = bufferedStart; - _bufferedLength = bufferedLength; - _match = match; - _matchStrength = strength; - } - - /* - /********************************************************** - /* Public API, simple accessors - /********************************************************** - */ - - /** - * Accessor to use to see if any formats matched well enough with - * the input data. - */ - public boolean hasMatch() { return _match != null; } - - /** - * Method for accessing strength of the match, if any; if no match, - * will return {@link MatchStrength#INCONCLUSIVE}. - */ - public MatchStrength getMatchStrength() { - return (_matchStrength == null) ? MatchStrength.INCONCLUSIVE : _matchStrength; - } - - /** - * Accessor for {@link JsonFactory} that represents format that data matched. - */ - public JsonFactory getMatch() { return _match; } - - /** - * Accessor for getting brief textual name of matched format if any (null - * if none). Equivalent to: - *

-     *   return hasMatch() ? getMatch().getFormatName() : null;
-     *
- */ - public String getMatchedFormatName() { - return _match.getFormatName(); - } - - /* - /********************************************************** - /* Public API, factory methods - /********************************************************** - */ - - /** - * Convenience method for trying to construct a {@link JsonParser} for - * parsing content which is assumed to be in detected data format. - * If no match was found, returns null. - */ - public JsonParser createParserWithMatch() throws IOException { - if (_match == null) { - return null; - } - if (_originalStream == null) { - return _match.createParser(_bufferedData, _bufferedStart, _bufferedLength); - } - return _match.createParser(getDataStream()); - } - - /** - * Method to use for accessing input for which format detection has been done. - * This must be used instead of using stream passed to detector - * unless given stream itself can do buffering. - * Stream will return all content that was read during matching process, as well - * as remaining contents of the underlying stream. - */ - public InputStream getDataStream() { - if (_originalStream == null) { - return new ByteArrayInputStream(_bufferedData, _bufferedStart, _bufferedLength); - } - return new MergedStream(null, _originalStream, _bufferedData, _bufferedStart, _bufferedLength); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/format/InputAccessor.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/format/InputAccessor.java deleted file mode 100644 index 70a0b753..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/format/InputAccessor.java +++ /dev/null @@ -1,153 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.format; - -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonFactory; - -/** - * Interface used to expose beginning of a data file to data format - * detection code. - */ -public interface InputAccessor -{ - /** - * Method to call to check if more input is available. - * Since this may result in more content to be read (at least - * one more byte), a {@link IOException} may get thrown. - */ - boolean hasMoreBytes() throws IOException; - - /** - * Returns next byte available, if any; if no more bytes are - * available, will throw {@link java.io.EOFException}. - */ - byte nextByte() throws IOException; - - /** - * Method that can be called to reset accessor to read from beginning - * of input. - */ - void reset(); - - /* - /********************************************************** - /* Standard implementation - /********************************************************** - */ - - /** - * Basic implementation that reads data from given - * {@link InputStream} and buffers it as necessary. - */ - class Std implements InputAccessor - { - protected final InputStream _in; - - protected final byte[] _buffer; - - protected final int _bufferedStart; - - /** - * End of valid bytes in the buffer (points to one past last valid) - */ - protected int _bufferedEnd; - - /** - * Pointer to next available buffered byte in {@link #_buffer}. - */ - protected int _ptr; - - /** - * Constructor used when content to check is available via - * input stream and must be read. - */ - public Std(InputStream in, byte[] buffer) - { - _in = in; - _buffer = buffer; - _bufferedStart = 0; - _ptr = 0; - _bufferedEnd = 0; - } - - /** - * Constructor used when the full input (or at least enough leading bytes - * of full input) is available. - */ - public Std(byte[] inputDocument) - { - _in = null; - _buffer = inputDocument; - // we have it all: - _bufferedStart = 0; - _bufferedEnd = inputDocument.length; - } - - /** - * Constructor used when the full input (or at least enough leading bytes - * of full input) is available. - * - * @since 2.1 - */ - public Std(byte[] inputDocument, int start, int len) - { - _in = null; - _buffer = inputDocument; - _ptr = start; - _bufferedStart = start; - _bufferedEnd = start+len; - } - - @Override - public boolean hasMoreBytes() throws IOException - { - if (_ptr < _bufferedEnd) { // already got more - return true; - } - if (_in == null) { // nowhere to read from - return false; - } - int amount = _buffer.length - _ptr; - if (amount < 1) { // can not load any more - return false; - } - int count = _in.read(_buffer, _ptr, amount); - if (count <= 0) { // EOF - return false; - } - _bufferedEnd += count; - return true; - } - - @Override - public byte nextByte() throws IOException - { - // should we just try loading more automatically? - if (_ptr >= _bufferedEnd) { - if (!hasMoreBytes()) { - throw new EOFException("Failed auto-detect: could not read more than "+_ptr+" bytes (max buffer size: "+_buffer.length+")"); - } - } - return _buffer[_ptr++]; - } - - @Override - public void reset() { - _ptr = _bufferedStart; - } - - /* - /********************************************************** - /* Extended API for DataFormatDetector/Matcher - /********************************************************** - */ - - public DataFormatMatcher createMatcher(JsonFactory match, MatchStrength matchStrength) - { - return new DataFormatMatcher(_in, _buffer, _bufferedStart, (_bufferedEnd - _bufferedStart), - match, matchStrength); - } - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/format/MatchStrength.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/format/MatchStrength.java deleted file mode 100644 index de2c0d20..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/format/MatchStrength.java +++ /dev/null @@ -1,62 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.format; - -/** - * Enumeration used to indicate strength of match between data format - * and piece of data (typically beginning of a data file). - * Values are in increasing match strength; and detectors should return - * "strongest" value: that is, it should start with strongest match - * criteria, and downgrading if criteria is not fulfilled. - */ -public enum MatchStrength -{ - /** - * Value that indicates that given data can not be in given format. - */ - NO_MATCH, - - /** - * Value that indicates that detector can not find out whether could - * be a match or not. - * This can occur for example for textual data formats t - * when there are so many leading spaces that detector can not - * find the first data byte (because detectors typically limit lookahead - * to some smallish value). - */ - INCONCLUSIVE, - - /** - * Value that indicates that given data could be of specified format (i.e. - * it can not be ruled out). This can occur for example when seen data - * is both not in canonical formats (for example: JSON data should be a JSON Array or Object - * not a scalar value, as per JSON specification) and there are known use case - * where a format detected is actually used (plain JSON Strings are actually used, even - * though specification does not indicate that as valid usage: as such, seeing a leading - * double-quote could indicate a JSON String, which plausibly could indicate - * non-standard JSON usage). - */ - WEAK_MATCH, - - /** - * Value that indicates that given data conforms to (one of) canonical form(s) of - * the data format. - *

- * For example, when testing for XML data format, - * seeing a less-than character ("<") alone (with possible leading spaces) - * would be a strong indication that data could - * be in xml format (but see below for {@link #FULL_MATCH} description for more) - */ - SOLID_MATCH, - - /** - * Value that indicates that given data contains a signature that is deemed - * specific enough to uniquely indicate data format used. - *

- * For example, when testing for XML data format, - * seing "<xml" as the first data bytes ("XML declaration", as per XML specification) - * could give full confidence that data is indeed in XML format. - * Not all data formats have unique leading identifiers to allow full matches; for example, - * JSON only has heuristic matches and can have at most {@link #SOLID_MATCH}) match. - */ - FULL_MATCH - ; -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/CharTypes.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/CharTypes.java deleted file mode 100644 index 91a6752c..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/CharTypes.java +++ /dev/null @@ -1,259 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.io; - -import java.util.Arrays; - -public final class CharTypes -{ - private final static char[] HC = "0123456789ABCDEF".toCharArray(); - private final static byte[] HB; - static { - int len = HC.length; - HB = new byte[len]; - for (int i = 0; i < len; ++i) { - HB[i] = (byte) HC[i]; - } - } - - - /** - * Lookup table used for determining which input characters - * need special handling when contained in text segment. - */ - private final static int[] sInputCodes; - static { - /* 96 would do for most cases (backslash is ASCII 94) - * but if we want to do lookups by raw bytes it's better - * to have full table - */ - final int[] table = new int[256]; - // Control chars and non-space white space are not allowed unquoted - for (int i = 0; i < 32; ++i) { - table[i] = -1; - } - // And then string end and quote markers are special too - table['"'] = 1; - table['\\'] = 1; - sInputCodes = table; - } - - /** - * Additionally we can combine UTF-8 decoding info into similar - * data table. - */ - private final static int[] sInputCodesUTF8; - static { - final int[] table = new int[sInputCodes.length]; - System.arraycopy(sInputCodes, 0, table, 0, table.length); - for (int c = 128; c < 256; ++c) { - int code; - - // We'll add number of bytes needed for decoding - if ((c & 0xE0) == 0xC0) { // 2 bytes (0x0080 - 0x07FF) - code = 2; - } else if ((c & 0xF0) == 0xE0) { // 3 bytes (0x0800 - 0xFFFF) - code = 3; - } else if ((c & 0xF8) == 0xF0) { - // 4 bytes; double-char with surrogates and all... - code = 4; - } else { - // And -1 seems like a good "universal" error marker... - code = -1; - } - table[c] = code; - } - sInputCodesUTF8 = table; - } - - /** - * To support non-default (and -standard) unquoted field names mode, - * need to have alternate checking. - * Basically this is list of 8-bit ASCII characters that are legal - * as part of Javascript identifier - */ - private final static int[] sInputCodesJsNames; - static { - final int[] table = new int[256]; - // Default is "not a name char", mark ones that are - Arrays.fill(table, -1); - // Assume rules with JS same as Java (change if/as needed) - for (int i = 33; i < 256; ++i) { - if (Character.isJavaIdentifierPart((char) i)) { - table[i] = 0; - } - } - /* As per [JACKSON-267], '@', '#' and '*' are also to be accepted as well. - * And '-' (for hyphenated names); and '+' for sake of symmetricity... - */ - table['@'] = 0; - table['#'] = 0; - table['*'] = 0; - table['-'] = 0; - table['+'] = 0; - sInputCodesJsNames = table; - } - - /** - * This table is similar to Latin-1, except that it marks all "high-bit" - * code as ok. They will be validated at a later point, when decoding - * name - */ - private final static int[] sInputCodesUtf8JsNames; - static { - final int[] table = new int[256]; - // start with 8-bit JS names - System.arraycopy(sInputCodesJsNames, 0, table, 0, table.length); - Arrays.fill(table, 128, 128, 0); - sInputCodesUtf8JsNames = table; - } - - /** - * Decoding table used to quickly determine characters that are - * relevant within comment content. - */ - private final static int[] sInputCodesComment; - static { - final int[] buf = new int[256]; - // but first: let's start with UTF-8 multi-byte markers: - System.arraycopy(sInputCodesUTF8, 128, buf, 128, 128); - - // default (0) means "ok" (skip); -1 invalid, others marked by char itself - Arrays.fill(buf, 0, 32, -1); // invalid white space - buf['\t'] = 0; // tab is still fine - buf['\n'] = '\n'; // lf/cr need to be observed, ends cpp comment - buf['\r'] = '\r'; - buf['*'] = '*'; // end marker for c-style comments - sInputCodesComment = buf; - } - - /** - * Decoding table used for skipping white space and comments. - * - * @since 2.3 - */ - private final static int[] sInputCodesWS; - static { - // but first: let's start with UTF-8 multi-byte markers: - final int[] buf = new int[256]; - System.arraycopy(sInputCodesUTF8, 128, buf, 128, 128); - - // default (0) means "not whitespace" (end); 1 "whitespace", -1 invalid, - // 2-4 UTF-8 multi-bytes, others marked by char itself - // - Arrays.fill(buf, 0, 32, -1); // invalid white space - buf[' '] = 1; - buf['\t'] = 1; - buf['\n'] = '\n'; // lf/cr need to be observed, ends cpp comment - buf['\r'] = '\r'; - buf['/'] = '/'; // start marker for c/cpp comments - buf['#'] = '#'; // start marker for YAML comments - sInputCodesWS = buf; - } - - /** - * Lookup table used for determining which output characters in - * 7-bit ASCII range need to be quoted. - */ - private final static int[] sOutputEscapes128; - static { - int[] table = new int[128]; - // Control chars need generic escape sequence - for (int i = 0; i < 32; ++i) { - // 04-Mar-2011, tatu: Used to use "-(i + 1)", replaced with constant - table[i] = CharacterEscapes.ESCAPE_STANDARD; - } - /* Others (and some within that range too) have explicit shorter - * sequences - */ - table['"'] = '"'; - table['\\'] = '\\'; - // Escaping of slash is optional, so let's not add it - table[0x08] = 'b'; - table[0x09] = 't'; - table[0x0C] = 'f'; - table[0x0A] = 'n'; - table[0x0D] = 'r'; - sOutputEscapes128 = table; - } - - /** - * Lookup table for the first 128 Unicode characters (7-bit ASCII) - * range. For actual hex digits, contains corresponding value; - * for others -1. - */ - private final static int[] sHexValues = new int[128]; - static { - Arrays.fill(sHexValues, -1); - for (int i = 0; i < 10; ++i) { - sHexValues['0' + i] = i; - } - for (int i = 0; i < 6; ++i) { - sHexValues['a' + i] = 10 + i; - sHexValues['A' + i] = 10 + i; - } - } - - public static int[] getInputCodeLatin1() { return sInputCodes; } - public static int[] getInputCodeUtf8() { return sInputCodesUTF8; } - - public static int[] getInputCodeLatin1JsNames() { return sInputCodesJsNames; } - public static int[] getInputCodeUtf8JsNames() { return sInputCodesUtf8JsNames; } - - public static int[] getInputCodeComment() { return sInputCodesComment; } - public static int[] getInputCodeWS() { return sInputCodesWS; } - - /** - * Accessor for getting a read-only encoding table for first 128 Unicode - * code points (single-byte UTF-8 characters). - * Value of 0 means "no escaping"; other positive values that value is character - * to use after backslash; and negative values that generic (backslash - u) - * escaping is to be used. - */ - public static int[] get7BitOutputEscapes() { return sOutputEscapes128; } - - public static int charToHex(int ch) - { - return (ch > 127) ? -1 : sHexValues[ch]; - } - - public static void appendQuoted(StringBuilder sb, String content) - { - final int[] escCodes = sOutputEscapes128; - int escLen = escCodes.length; - for (int i = 0, len = content.length(); i < len; ++i) { - char c = content.charAt(i); - if (c >= escLen || escCodes[c] == 0) { - sb.append(c); - continue; - } - sb.append('\\'); - int escCode = escCodes[c]; - if (escCode < 0) { // generic quoting (hex value) - // The only negative value sOutputEscapes128 returns - // is CharacterEscapes.ESCAPE_STANDARD, which mean - // appendQuotes should encode using the Unicode encoding; - // not sure if this is the right way to encode for - // CharacterEscapes.ESCAPE_CUSTOM or other (future) - // CharacterEscapes.ESCAPE_XXX values. - - // We know that it has to fit in just 2 hex chars - sb.append('u'); - sb.append('0'); - sb.append('0'); - int value = c; // widening - sb.append(HC[value >> 4]); - sb.append(HC[value & 0xF]); - } else { // "named", i.e. prepend with slash - sb.append((char) escCode); - } - } - } - - public static char[] copyHexChars() { - return (char[]) HC.clone(); - } - - public static byte[] copyHexBytes() { - return (byte[]) HB.clone(); - } -} - diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/CharacterEscapes.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/CharacterEscapes.java deleted file mode 100644 index c4db7c1a..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/CharacterEscapes.java +++ /dev/null @@ -1,71 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.io; - -import java.util.Arrays; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.SerializableString; - -/** - * Abstract base class that defines interface for customizing character - * escaping aspects for String values, for formats that use escaping. - * For JSON this applies to both property names and String values. - */ -@SuppressWarnings("serial") -public abstract class CharacterEscapes - implements java.io.Serializable // since 2.1 -{ - /** - * Value used for lookup tables to indicate that matching characters - * do not need to be escaped. - */ - public final static int ESCAPE_NONE = 0; - - /** - * Value used for lookup tables to indicate that matching characters - * are to be escaped using standard escaping; for JSON this means - * (for example) using "backslash - u" escape method. - */ - public final static int ESCAPE_STANDARD = -1; - - /** - * Value used for lookup tables to indicate that matching characters - * will need custom escapes; and that another call - * to {@link #getEscapeSequence} is needed to figure out exact escape - * sequence to output. - */ - public final static int ESCAPE_CUSTOM = -2; - - /** - * Method generators can call to get lookup table for determining - * escape handling for first 128 characters of Unicode (ASCII - * characters. Caller is not to modify contents of this array, since - * this is expected to be a shared copy. - * - * @return Array with size of at least 128, where first 128 entries - * have either one of ESCAPE_xxx constants, or non-zero positive - * integer (meaning of which is data format specific; for JSON it means - * that combination of backslash and character with that value is to be used) - * to indicate that specific escape sequence is to be used. - */ - public abstract int[] getEscapeCodesForAscii(); - - /** - * Method generators can call to get lookup table for determining - * exact escape sequence to use for given character. - * It can be called for any character, but typically is called for - * either for ASCII characters for which custom escape - * sequence is needed; or for any non-ASCII character. - */ - public abstract SerializableString getEscapeSequence(int ch); - - /** - * Helper method that can be used to get a copy of standard JSON - * escape definitions; this is useful when just wanting to slightly - * customize definitions. Caller can modify this array as it sees - * fit and usually returns modified instance via {@link #getEscapeCodesForAscii} - */ - public static int[] standardAsciiEscapesForJSON() - { - int[] esc = CharTypes.get7BitOutputEscapes(); - return Arrays.copyOf(esc, esc.length); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/DataOutputAsStream.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/DataOutputAsStream.java deleted file mode 100644 index 49b4f9f4..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/DataOutputAsStream.java +++ /dev/null @@ -1,46 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.io; - -import java.io.DataOutput; -import java.io.IOException; -import java.io.OutputStream; - -/** - * Helper class to support use of {@link DataOutput} for output, directly, - * without caller having to provide for implementation. - * - * @since 2.8 - */ -public class DataOutputAsStream extends OutputStream -{ - protected final DataOutput _output; - - public DataOutputAsStream(DataOutput out) { - super(); - _output = out; - } - - @Override - public void write(int b) throws IOException { - _output.write(b); - } - - @Override - public void write(byte b[]) throws IOException { - _output.write(b, 0, b.length); - } - - @Override - public void write(byte b[], int offset, int length) throws IOException { - _output.write(b, offset, length); - } - - // These are no-ops, base class impl works fine - - /* - @Override - public void flush() throws IOException { } - - @Override - public void close() throws IOException { } - */ -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/IOContext.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/IOContext.java deleted file mode 100644 index f6d13ced..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/IOContext.java +++ /dev/null @@ -1,286 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.io; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonEncoding; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.BufferRecycler; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.TextBuffer; - -/** - * To limit number of configuration and state objects to pass, all - * contextual objects that need to be passed by the factory to - * readers and writers are combined under this object. One instance - * is created for each reader and writer. - *

- * NOTE: non-final since 2.4, to allow sub-classing. - */ -public class IOContext -{ - /* - /********************************************************** - /* Configuration - /********************************************************** - */ - - /** - * Reference to the source object, which can be used for displaying - * location information - */ - protected final Object _sourceRef; - - /** - * Encoding used by the underlying stream, if known. - */ - protected JsonEncoding _encoding; - - /** - * Flag that indicates whether underlying input/output source/target - * object is fully managed by the owner of this context (parser or - * generator). If true, it is, and is to be closed by parser/generator; - * if false, calling application has to do closing (unless auto-closing - * feature is enabled for the parser/generator in question; in which - * case it acts like the owner). - */ - protected final boolean _managedResource; - - /* - /********************************************************** - /* Buffer handling, recycling - /********************************************************** - */ - - /** - * Recycler used for actual allocation/deallocation/reuse - */ - protected final BufferRecycler _bufferRecycler; - - /** - * Reference to the allocated I/O buffer for low-level input reading, - * if any allocated. - */ - protected byte[] _readIOBuffer; - - /** - * Reference to the allocated I/O buffer used for low-level - * encoding-related buffering. - */ - protected byte[] _writeEncodingBuffer; - - /** - * Reference to the buffer allocated for temporary use with - * base64 encoding or decoding. - */ - protected byte[] _base64Buffer; - - /** - * Reference to the buffer allocated for tokenization purposes, - * in which character input is read, and from which it can be - * further returned. - */ - protected char[] _tokenCBuffer; - - /** - * Reference to the buffer allocated for buffering it for - * output, before being encoded: generally this means concatenating - * output, then encoding when buffer fills up. - */ - protected char[] _concatCBuffer; - - /** - * Reference temporary buffer Parser instances need if calling - * app decides it wants to access name via 'getTextCharacters' method. - * Regular text buffer can not be used as it may contain textual - * representation of the value token. - */ - protected char[] _nameCopyBuffer; - - /* - /********************************************************** - /* Life-cycle - /********************************************************** - */ - - public IOContext(BufferRecycler br, Object sourceRef, boolean managedResource) - { - _bufferRecycler = br; - _sourceRef = sourceRef; - _managedResource = managedResource; - } - - public void setEncoding(JsonEncoding enc) { - _encoding = enc; - } - - /** - * @since 1.6 - */ - public IOContext withEncoding(JsonEncoding enc) { - _encoding = enc; - return this; - } - - /* - /********************************************************** - /* Public API, accessors - /********************************************************** - */ - - public Object getSourceReference() { return _sourceRef; } - public JsonEncoding getEncoding() { return _encoding; } - public boolean isResourceManaged() { return _managedResource; } - - /* - /********************************************************** - /* Public API, buffer management - /********************************************************** - */ - - public TextBuffer constructTextBuffer() { - return new TextBuffer(_bufferRecycler); - } - - /** - *

- * Note: the method can only be called once during its life cycle. - * This is to protect against accidental sharing. - */ - public byte[] allocReadIOBuffer() { - _verifyAlloc(_readIOBuffer); - return (_readIOBuffer = _bufferRecycler.allocByteBuffer(BufferRecycler.BYTE_READ_IO_BUFFER)); - } - - /** - * @since 2.4 - */ - public byte[] allocReadIOBuffer(int minSize) { - _verifyAlloc(_readIOBuffer); - return (_readIOBuffer = _bufferRecycler.allocByteBuffer(BufferRecycler.BYTE_READ_IO_BUFFER, minSize)); - } - - public byte[] allocWriteEncodingBuffer() { - _verifyAlloc(_writeEncodingBuffer); - return (_writeEncodingBuffer = _bufferRecycler.allocByteBuffer(BufferRecycler.BYTE_WRITE_ENCODING_BUFFER)); - } - - /** - * @since 2.4 - */ - public byte[] allocWriteEncodingBuffer(int minSize) { - _verifyAlloc(_writeEncodingBuffer); - return (_writeEncodingBuffer = _bufferRecycler.allocByteBuffer(BufferRecycler.BYTE_WRITE_ENCODING_BUFFER, minSize)); - } - - /** - * @since 2.1 - */ - public byte[] allocBase64Buffer() { - _verifyAlloc(_base64Buffer); - return (_base64Buffer = _bufferRecycler.allocByteBuffer(BufferRecycler.BYTE_BASE64_CODEC_BUFFER)); - } - - public char[] allocTokenBuffer() { - _verifyAlloc(_tokenCBuffer); - return (_tokenCBuffer = _bufferRecycler.allocCharBuffer(BufferRecycler.CHAR_TOKEN_BUFFER)); - } - - /** - * @since 2.4 - */ - public char[] allocTokenBuffer(int minSize) { - _verifyAlloc(_tokenCBuffer); - return (_tokenCBuffer = _bufferRecycler.allocCharBuffer(BufferRecycler.CHAR_TOKEN_BUFFER, minSize)); - } - - public char[] allocConcatBuffer() { - _verifyAlloc(_concatCBuffer); - return (_concatCBuffer = _bufferRecycler.allocCharBuffer(BufferRecycler.CHAR_CONCAT_BUFFER)); - } - - public char[] allocNameCopyBuffer(int minSize) { - _verifyAlloc(_nameCopyBuffer); - return (_nameCopyBuffer = _bufferRecycler.allocCharBuffer(BufferRecycler.CHAR_NAME_COPY_BUFFER, minSize)); - } - - /** - * Method to call when all the processing buffers can be safely - * recycled. - */ - public void releaseReadIOBuffer(byte[] buf) { - if (buf != null) { - /* Let's do sanity checks to ensure once-and-only-once release, - * as well as avoiding trying to release buffers not owned - */ - _verifyRelease(buf, _readIOBuffer); - _readIOBuffer = null; - _bufferRecycler.releaseByteBuffer(BufferRecycler.BYTE_READ_IO_BUFFER, buf); - } - } - - public void releaseWriteEncodingBuffer(byte[] buf) { - if (buf != null) { - /* Let's do sanity checks to ensure once-and-only-once release, - * as well as avoiding trying to release buffers not owned - */ - _verifyRelease(buf, _writeEncodingBuffer); - _writeEncodingBuffer = null; - _bufferRecycler.releaseByteBuffer(BufferRecycler.BYTE_WRITE_ENCODING_BUFFER, buf); - } - } - - public void releaseBase64Buffer(byte[] buf) { - if (buf != null) { // sanity checks, release once-and-only-once, must be one owned - _verifyRelease(buf, _base64Buffer); - _base64Buffer = null; - _bufferRecycler.releaseByteBuffer(BufferRecycler.BYTE_BASE64_CODEC_BUFFER, buf); - } - } - - public void releaseTokenBuffer(char[] buf) { - if (buf != null) { - _verifyRelease(buf, _tokenCBuffer); - _tokenCBuffer = null; - _bufferRecycler.releaseCharBuffer(BufferRecycler.CHAR_TOKEN_BUFFER, buf); - } - } - - public void releaseConcatBuffer(char[] buf) { - if (buf != null) { - // 14-Jan-2014, tatu: Let's actually allow upgrade of the original buffer. - _verifyRelease(buf, _concatCBuffer); - _concatCBuffer = null; - _bufferRecycler.releaseCharBuffer(BufferRecycler.CHAR_CONCAT_BUFFER, buf); - } - } - - public void releaseNameCopyBuffer(char[] buf) { - if (buf != null) { - // 14-Jan-2014, tatu: Let's actually allow upgrade of the original buffer. - _verifyRelease(buf, _nameCopyBuffer); - _nameCopyBuffer = null; - _bufferRecycler.releaseCharBuffer(BufferRecycler.CHAR_NAME_COPY_BUFFER, buf); - } - } - - /* - /********************************************************** - /* Internal helpers - /********************************************************** - */ - - protected final void _verifyAlloc(Object buffer) { - if (buffer != null) { throw new IllegalStateException("Trying to call same allocXxx() method second time"); } - } - - protected final void _verifyRelease(byte[] toRelease, byte[] src) { - // 07-Mar-2016, tatu: As per [core#255], only prevent shrinking of buffer - if ((toRelease != src) && (toRelease.length < src.length)) { throw wrongBuf(); } - } - - protected final void _verifyRelease(char[] toRelease, char[] src) { - // 07-Mar-2016, tatu: As per [core#255], only prevent shrinking of buffer - if ((toRelease != src) && (toRelease.length < src.length)) { throw wrongBuf(); } - } - - private IllegalArgumentException wrongBuf() { - // sanity check failed; trying to return different, smaller buffer. - return new IllegalArgumentException("Trying to release buffer smaller than original"); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/InputDecorator.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/InputDecorator.java deleted file mode 100644 index 98c0c00b..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/InputDecorator.java +++ /dev/null @@ -1,95 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.io; - -import java.io.DataInput; -import java.io.FilterReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; - -/** - * Handler class that can be used to decorate input sources. - * Typical use is to use a filter abstraction (filtered stream, - * reader) around original input source, and apply additional - * processing during read operations. - */ -public abstract class InputDecorator - implements java.io.Serializable // since 2.1 -{ - private static final long serialVersionUID = 1L; - - /** - * Method called by {@link autosaveworld.zlibs.com.fasterxml.jackson.core.JsonFactory} instance when - * creating parser given an {@link InputStream}, when this decorator - * has been registered. - * - * @param ctxt IO context in use (provides access to declared encoding). - * NOTE: at this point context may not have all information initialized; - * specifically auto-detected encoding is only available once parsing starts, - * which may occur only after this method is called. - * @param in Original input source - * - * @return InputStream to use; either 'in' as is, or decorator - * version that typically delogates to 'in' - */ - public abstract InputStream decorate(IOContext ctxt, InputStream in) - throws IOException; - - /** - * Method called by {@link autosaveworld.zlibs.com.fasterxml.jackson.core.JsonFactory} instance when - * creating parser on given "raw" byte source. - * Method can either construct a {@link InputStream} for reading; or return - * null to indicate that no wrapping should occur. - * - * @param ctxt IO context in use (provides access to declared encoding) - * NOTE: at this point context may not have all information initialized; - * specifically auto-detected encoding is only available once parsing starts, - * which may occur only after this method is called. - * @param src Input buffer that contains contents to parse - * @param offset Offset of the first available byte in the input buffer - * @param length Number of bytes available in the input buffer - * - * @return Either {@link InputStream} to use as input source; or null to indicate - * that contents are to be processed as-is by caller - */ - public abstract InputStream decorate(IOContext ctxt, byte[] src, int offset, int length) - throws IOException; - - /** - * Method called by {@link autosaveworld.zlibs.com.fasterxml.jackson.core.JsonFactory} instance when - * creating parser given an {@link DataInput}, when this decorator - * has been registered. - *

- * Default implementation simply throws {@link UnsupportedOperationException} - * - * @param ctxt IO context in use (provides access to declared encoding). - * NOTE: at this point context may not have all information initialized; - * specifically auto-detected encoding is only available once parsing starts, - * which may occur only after this method is called. - * @param input Original input source - * - * @return InputStream to use; either 'input' as is, or decorator - * version that typically delogates to 'input' - * - * @since 2.8 - */ - public DataInput decorate(IOContext ctxt, DataInput input) - throws IOException { - throw new UnsupportedOperationException(); - } - - /** - * Method called by {@link autosaveworld.zlibs.com.fasterxml.jackson.core.JsonFactory} instance when - * creating parser given an {@link Reader}, when this decorator - * has been registered. - * - * @param ctxt IO context in use (provides access to declared encoding) - * NOTE: at this point context may not have all information initialized; - * specifically auto-detected encoding is only available once parsing starts, - * which may occur only after this method is called. - * @param r Original reader - * - * @return Reader to use; either passed in argument, or something that - * calls it (for example, a {@link FilterReader}) - */ - public abstract Reader decorate(IOContext ctxt, Reader r) throws IOException; -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/JsonEOFException.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/JsonEOFException.java deleted file mode 100644 index aea9b6b5..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/JsonEOFException.java +++ /dev/null @@ -1,37 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.io; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * Specialized {@link JsonParseException} that is thrown when end-of-input - * is reached unexpectedly, either within token being decoded, or during - * skipping of intervening white-space that is not between root-level - * tokens (that is, is within JSON Object or JSON Array construct). - * - * @since 2.8 - */ -public class JsonEOFException extends JsonParseException -{ - private static final long serialVersionUID = 1L; - - /** - * Type of token that was being decoded, if parser had enough information - * to recognize type (such as starting double-quote for Strings) - */ - protected final JsonToken _token; - - public JsonEOFException(JsonParser p, JsonToken token, String msg) { - super(p, msg); - _token = token; - } - - /** - * Accessor for possibly available information about token that was being - * decoded while encountering end of input. - */ - public JsonToken getTokenBeingDecoded() { - return _token; - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/JsonStringEncoder.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/JsonStringEncoder.java deleted file mode 100644 index 8be5036a..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/JsonStringEncoder.java +++ /dev/null @@ -1,428 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.io; - -import java.lang.ref.SoftReference; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.BufferRecycler; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.ByteArrayBuilder; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.TextBuffer; - -/** - * Helper class used for efficient encoding of JSON String values (including - * JSON field names) into Strings or UTF-8 byte arrays. - *

- * Note that methods in here are somewhat optimized, but not ridiculously so. - * Reason is that conversion method results are expected to be cached so that - * these methods will not be hot spots during normal operation. - */ -public final class JsonStringEncoder -{ - private final static char[] HC = CharTypes.copyHexChars(); - - private final static byte[] HB = CharTypes.copyHexBytes(); - - private final static int SURR1_FIRST = 0xD800; - private final static int SURR1_LAST = 0xDBFF; - private final static int SURR2_FIRST = 0xDC00; - private final static int SURR2_LAST = 0xDFFF; - -// private final static int INT_BACKSLASH = '\\'; -// private final static int INT_U = 'u'; -// private final static int INT_0 = '0'; - - /** - * This ThreadLocal contains a {@link java.lang.ref.SoftReference} - * to a {@link BufferRecycler} used to provide a low-cost - * buffer recycling between reader and writer instances. - */ - final protected static ThreadLocal> _threadEncoder - = new ThreadLocal>(); - - /** - * Lazily constructed text buffer used to produce JSON encoded Strings - * as characters (without UTF-8 encoding) - */ - protected TextBuffer _text; - - /** - * Lazily-constructed builder used for UTF-8 encoding of text values - * (quoted and unquoted) - */ - protected ByteArrayBuilder _bytes; - - /** - * Temporary buffer used for composing quote/escape sequences - */ - protected final char[] _qbuf; - - /* - /********************************************************** - /* Construction, instance access - /********************************************************** - */ - - public JsonStringEncoder() { - _qbuf = new char[6]; - _qbuf[0] = '\\'; - _qbuf[2] = '0'; - _qbuf[3] = '0'; - } - - /** - * Factory method for getting an instance; this is either recycled per-thread instance, - * or a newly constructed one. - */ - public static JsonStringEncoder getInstance() { - SoftReference ref = _threadEncoder.get(); - JsonStringEncoder enc = (ref == null) ? null : ref.get(); - - if (enc == null) { - enc = new JsonStringEncoder(); - _threadEncoder.set(new SoftReference(enc)); - } - return enc; - } - - /* - /********************************************************** - /* Public API - /********************************************************** - */ - - /** - * Method that will quote text contents using JSON standard quoting, - * and return results as a character array - */ - public char[] quoteAsString(String input) - { - TextBuffer textBuffer = _text; - if (textBuffer == null) { - // no allocator; can add if we must, shouldn't need to - _text = textBuffer = new TextBuffer(null); - } - char[] outputBuffer = textBuffer.emptyAndGetCurrentSegment(); - final int[] escCodes = CharTypes.get7BitOutputEscapes(); - final int escCodeCount = escCodes.length; - int inPtr = 0; - final int inputLen = input.length(); - int outPtr = 0; - - outer: - while (inPtr < inputLen) { - tight_loop: - while (true) { - char c = input.charAt(inPtr); - if (c < escCodeCount && escCodes[c] != 0) { - break tight_loop; - } - if (outPtr >= outputBuffer.length) { - outputBuffer = textBuffer.finishCurrentSegment(); - outPtr = 0; - } - outputBuffer[outPtr++] = c; - if (++inPtr >= inputLen) { - break outer; - } - } - // something to escape; 2 or 6-char variant? - char d = input.charAt(inPtr++); - int escCode = escCodes[d]; - int length = (escCode < 0) - ? _appendNumeric(d, _qbuf) - : _appendNamed(escCode, _qbuf); - ; - if ((outPtr + length) > outputBuffer.length) { - int first = outputBuffer.length - outPtr; - if (first > 0) { - System.arraycopy(_qbuf, 0, outputBuffer, outPtr, first); - } - outputBuffer = textBuffer.finishCurrentSegment(); - int second = length - first; - System.arraycopy(_qbuf, first, outputBuffer, 0, second); - outPtr = second; - } else { - System.arraycopy(_qbuf, 0, outputBuffer, outPtr, length); - outPtr += length; - } - } - textBuffer.setCurrentLength(outPtr); - return textBuffer.contentsAsArray(); - } - - /** - * Method that will quote text contents using JSON standard quoting, - * and append results to a supplied {@link StringBuilder}. - * Use this variant if you have e.g. a {@link StringBuilder} and want to avoid superfluous copying of it. - * - * @since 2.8 - */ - public void quoteAsString(CharSequence input, StringBuilder output) - { - final int[] escCodes = CharTypes.get7BitOutputEscapes(); - final int escCodeCount = escCodes.length; - int inPtr = 0; - final int inputLen = input.length(); - - outer: - while (inPtr < inputLen) { - tight_loop: - while (true) { - char c = input.charAt(inPtr); - if (c < escCodeCount && escCodes[c] != 0) { - break tight_loop; - } - output.append(c); - if (++inPtr >= inputLen) { - break outer; - } - } - // something to escape; 2 or 6-char variant? - char d = input.charAt(inPtr++); - int escCode = escCodes[d]; - int length = (escCode < 0) - ? _appendNumeric(d, _qbuf) - : _appendNamed(escCode, _qbuf); - ; - output.append(_qbuf, 0, length); - } - } - - /** - * Will quote given JSON String value using standard quoting, encode - * results as UTF-8, and return result as a byte array. - */ - public byte[] quoteAsUTF8(String text) - { - ByteArrayBuilder bb = _bytes; - if (bb == null) { - // no allocator; can add if we must, shouldn't need to - _bytes = bb = new ByteArrayBuilder(null); - } - int inputPtr = 0; - int inputEnd = text.length(); - int outputPtr = 0; - byte[] outputBuffer = bb.resetAndGetFirstSegment(); - - main: - while (inputPtr < inputEnd) { - final int[] escCodes = CharTypes.get7BitOutputEscapes(); - - inner_loop: // ASCII and escapes - while (true) { - int ch = text.charAt(inputPtr); - if (ch > 0x7F || escCodes[ch] != 0) { - break inner_loop; - } - if (outputPtr >= outputBuffer.length) { - outputBuffer = bb.finishCurrentSegment(); - outputPtr = 0; - } - outputBuffer[outputPtr++] = (byte) ch; - if (++inputPtr >= inputEnd) { - break main; - } - } - if (outputPtr >= outputBuffer.length) { - outputBuffer = bb.finishCurrentSegment(); - outputPtr = 0; - } - // Ok, so what did we hit? - int ch = (int) text.charAt(inputPtr++); - if (ch <= 0x7F) { // needs quoting - int escape = escCodes[ch]; - // ctrl-char, 6-byte escape... - outputPtr = _appendByte(ch, escape, bb, outputPtr); - outputBuffer = bb.getCurrentSegment(); - continue main; - } - if (ch <= 0x7FF) { // fine, just needs 2 byte output - outputBuffer[outputPtr++] = (byte) (0xc0 | (ch >> 6)); - ch = (0x80 | (ch & 0x3f)); - } else { // 3 or 4 bytes - // Surrogates? - if (ch < SURR1_FIRST || ch > SURR2_LAST) { // nope - outputBuffer[outputPtr++] = (byte) (0xe0 | (ch >> 12)); - if (outputPtr >= outputBuffer.length) { - outputBuffer = bb.finishCurrentSegment(); - outputPtr = 0; - } - outputBuffer[outputPtr++] = (byte) (0x80 | ((ch >> 6) & 0x3f)); - ch = (0x80 | (ch & 0x3f)); - } else { // yes, surrogate pair - if (ch > SURR1_LAST) { // must be from first range - _illegal(ch); - } - // and if so, followed by another from next range - if (inputPtr >= inputEnd) { - _illegal(ch); - } - ch = _convert(ch, text.charAt(inputPtr++)); - if (ch > 0x10FFFF) { // illegal, as per RFC 4627 - _illegal(ch); - } - outputBuffer[outputPtr++] = (byte) (0xf0 | (ch >> 18)); - if (outputPtr >= outputBuffer.length) { - outputBuffer = bb.finishCurrentSegment(); - outputPtr = 0; - } - outputBuffer[outputPtr++] = (byte) (0x80 | ((ch >> 12) & 0x3f)); - if (outputPtr >= outputBuffer.length) { - outputBuffer = bb.finishCurrentSegment(); - outputPtr = 0; - } - outputBuffer[outputPtr++] = (byte) (0x80 | ((ch >> 6) & 0x3f)); - ch = (0x80 | (ch & 0x3f)); - } - } - if (outputPtr >= outputBuffer.length) { - outputBuffer = bb.finishCurrentSegment(); - outputPtr = 0; - } - outputBuffer[outputPtr++] = (byte) ch; - } - return _bytes.completeAndCoalesce(outputPtr); - } - - /** - * Will encode given String as UTF-8 (without any quoting), return - * resulting byte array. - */ - public byte[] encodeAsUTF8(String text) - { - ByteArrayBuilder byteBuilder = _bytes; - if (byteBuilder == null) { - // no allocator; can add if we must, shouldn't need to - _bytes = byteBuilder = new ByteArrayBuilder(null); - } - int inputPtr = 0; - int inputEnd = text.length(); - int outputPtr = 0; - byte[] outputBuffer = byteBuilder.resetAndGetFirstSegment(); - int outputEnd = outputBuffer.length; - - main_loop: - while (inputPtr < inputEnd) { - int c = text.charAt(inputPtr++); - - // first tight loop for ascii - while (c <= 0x7F) { - if (outputPtr >= outputEnd) { - outputBuffer = byteBuilder.finishCurrentSegment(); - outputEnd = outputBuffer.length; - outputPtr = 0; - } - outputBuffer[outputPtr++] = (byte) c; - if (inputPtr >= inputEnd) { - break main_loop; - } - c = text.charAt(inputPtr++); - } - - // then multi-byte... - if (outputPtr >= outputEnd) { - outputBuffer = byteBuilder.finishCurrentSegment(); - outputEnd = outputBuffer.length; - outputPtr = 0; - } - if (c < 0x800) { // 2-byte - outputBuffer[outputPtr++] = (byte) (0xc0 | (c >> 6)); - } else { // 3 or 4 bytes - // Surrogates? - if (c < SURR1_FIRST || c > SURR2_LAST) { // nope - outputBuffer[outputPtr++] = (byte) (0xe0 | (c >> 12)); - if (outputPtr >= outputEnd) { - outputBuffer = byteBuilder.finishCurrentSegment(); - outputEnd = outputBuffer.length; - outputPtr = 0; - } - outputBuffer[outputPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f)); - } else { // yes, surrogate pair - if (c > SURR1_LAST) { // must be from first range - _illegal(c); - } - // and if so, followed by another from next range - if (inputPtr >= inputEnd) { - _illegal(c); - } - c = _convert(c, text.charAt(inputPtr++)); - if (c > 0x10FFFF) { // illegal, as per RFC 4627 - _illegal(c); - } - outputBuffer[outputPtr++] = (byte) (0xf0 | (c >> 18)); - if (outputPtr >= outputEnd) { - outputBuffer = byteBuilder.finishCurrentSegment(); - outputEnd = outputBuffer.length; - outputPtr = 0; - } - outputBuffer[outputPtr++] = (byte) (0x80 | ((c >> 12) & 0x3f)); - if (outputPtr >= outputEnd) { - outputBuffer = byteBuilder.finishCurrentSegment(); - outputEnd = outputBuffer.length; - outputPtr = 0; - } - outputBuffer[outputPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f)); - } - } - if (outputPtr >= outputEnd) { - outputBuffer = byteBuilder.finishCurrentSegment(); - outputEnd = outputBuffer.length; - outputPtr = 0; - } - outputBuffer[outputPtr++] = (byte) (0x80 | (c & 0x3f)); - } - return _bytes.completeAndCoalesce(outputPtr); - } - - /* - /********************************************************** - /* Internal methods - /********************************************************** - */ - - private int _appendNumeric(int value, char[] qbuf) { - qbuf[1] = 'u'; - // We know it's a control char, so only the last 2 chars are non-0 - qbuf[4] = HC[value >> 4]; - qbuf[5] = HC[value & 0xF]; - return 6; - } - - private int _appendNamed(int esc, char[] qbuf) { - qbuf[1] = (char) esc; - return 2; - } - - private int _appendByte(int ch, int esc, ByteArrayBuilder bb, int ptr) - { - bb.setCurrentSegmentLength(ptr); - bb.append('\\'); - if (esc < 0) { // standard escape - bb.append('u'); - if (ch > 0xFF) { - int hi = (ch >> 8); - bb.append(HB[hi >> 4]); - bb.append(HB[hi & 0xF]); - ch &= 0xFF; - } else { - bb.append('0'); - bb.append('0'); - } - bb.append(HB[ch >> 4]); - bb.append(HB[ch & 0xF]); - } else { // 2-char simple escape - bb.append((byte) esc); - } - return bb.getCurrentSegmentLength(); - } - - private static int _convert(int p1, int p2) { - // Ok, then, is the second part valid? - if (p2 < SURR2_FIRST || p2 > SURR2_LAST) { - throw new IllegalArgumentException("Broken surrogate pair: first char 0x"+Integer.toHexString(p1)+", second 0x"+Integer.toHexString(p2)+"; illegal combination"); - } - return 0x10000 + ((p1 - SURR1_FIRST) << 10) + (p2 - SURR2_FIRST); - } - - private static void _illegal(int c) { - throw new IllegalArgumentException(UTF8Writer.illegalSurrogateDesc(c)); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/MergedStream.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/MergedStream.java deleted file mode 100644 index 2023ab83..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/MergedStream.java +++ /dev/null @@ -1,122 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.io; - -import java.io.IOException; -import java.io.InputStream; - -/** - * Simple {@link InputStream} implementation that is used to "unwind" some - * data previously read from an input stream; so that as long as some of - * that data remains, it's returned; but as long as it's read, we'll - * just use data from the underlying original stream. - * This is similar to {@link java.io.PushbackInputStream}, but here there's - * only one implicit pushback, when instance is constructed. - */ -public final class MergedStream extends InputStream -{ - final private IOContext _ctxt; - - final private InputStream _in; - - private byte[] _b; - - private int _ptr; - - final private int _end; - - public MergedStream(IOContext ctxt, InputStream in, byte[] buf, int start, int end) { - _ctxt = ctxt; - _in = in; - _b = buf; - _ptr = start; - _end = end; - } - - @Override - public int available() throws IOException { - if (_b != null) { - return _end - _ptr; - } - return _in.available(); - } - - @Override public void close() throws IOException { - _free(); - _in.close(); - } - - @Override public void mark(int readlimit) { - if (_b == null) { _in.mark(readlimit); } - } - - @Override public boolean markSupported() { - // Only supports marks past the initial rewindable section... - return (_b == null) && _in.markSupported(); - } - - @Override public int read() throws IOException { - if (_b != null) { - int c = _b[_ptr++] & 0xFF; - if (_ptr >= _end) { - _free(); - } - return c; - } - return _in.read(); - } - - @Override public int read(byte[] b) throws IOException { - return read(b, 0, b.length); - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - if (_b != null) { - int avail = _end - _ptr; - if (len > avail) { - len = avail; - } - System.arraycopy(_b, _ptr, b, off, len); - _ptr += len; - if (_ptr >= _end) { - _free(); - } - return len; - } - return _in.read(b, off, len); - } - - @Override - public void reset() throws IOException { - if (_b == null) { _in.reset(); } - } - - @Override - public long skip(long n) throws IOException { - long count = 0L; - - if (_b != null) { - int amount = _end - _ptr; - - if (amount > n) { // all in pushed back segment? - _ptr += (int) n; - return n; - } - _free(); - count += amount; - n -= amount; - } - - if (n > 0) { count += _in.skip(n); } - return count; - } - - private void _free() { - byte[] buf = _b; - if (buf != null) { - _b = null; - if (_ctxt != null) { - _ctxt.releaseReadIOBuffer(buf); - } - } - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/NumberInput.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/NumberInput.java deleted file mode 100644 index 58208367..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/NumberInput.java +++ /dev/null @@ -1,307 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.io; - -import java.math.BigDecimal; - -public final class NumberInput -{ - /** - * Textual representation of a double constant that can cause nasty problems - * with JDK (see http://www.exploringbinary.com/java-hangs-when-converting-2-2250738585072012e-308). - */ - public final static String NASTY_SMALL_DOUBLE = "2.2250738585072012e-308"; - - /** - * Constants needed for parsing longs from basic int parsing methods - */ - final static long L_BILLION = 1000000000; - - final static String MIN_LONG_STR_NO_SIGN = String.valueOf(Long.MIN_VALUE).substring(1); - final static String MAX_LONG_STR = String.valueOf(Long.MAX_VALUE); - - /** - * Fast method for parsing integers that are known to fit into - * regular 32-bit signed int type. This means that length is - * between 1 and 9 digits (inclusive) - *

- * Note: public to let unit tests call it - */ - public static int parseInt(char[] ch, int off, int len) - { - int num = ch[off] - '0'; - - if (len > 4) { - num = (num * 10) + (ch[++off] - '0'); - num = (num * 10) + (ch[++off] - '0'); - num = (num * 10) + (ch[++off] - '0'); - num = (num * 10) + (ch[++off] - '0'); - len -= 4; - if (len > 4) { - num = (num * 10) + (ch[++off] - '0'); - num = (num * 10) + (ch[++off] - '0'); - num = (num * 10) + (ch[++off] - '0'); - num = (num * 10) + (ch[++off] - '0'); - return num; - } - } - if (len > 1) { - num = (num * 10) + (ch[++off] - '0'); - if (len > 2) { - num = (num * 10) + (ch[++off] - '0'); - if (len > 3) { - num = (num * 10) + (ch[++off] - '0'); - } - } - } - return num; - } - - /** - * Helper method to (more) efficiently parse integer numbers from - * String values. - */ - public static int parseInt(String s) - { - /* Ok: let's keep strategy simple: ignoring optional minus sign, - * we'll accept 1 - 9 digits and parse things efficiently; - * otherwise just defer to JDK parse functionality. - */ - char c = s.charAt(0); - int len = s.length(); - boolean neg = (c == '-'); - int offset = 1; - // must have 1 - 9 digits after optional sign: - // negative? - if (neg) { - if (len == 1 || len > 10) { - return Integer.parseInt(s); - } - c = s.charAt(offset++); - } else { - if (len > 9) { - return Integer.parseInt(s); - } - } - if (c > '9' || c < '0') { - return Integer.parseInt(s); - } - int num = c - '0'; - if (offset < len) { - c = s.charAt(offset++); - if (c > '9' || c < '0') { - return Integer.parseInt(s); - } - num = (num * 10) + (c - '0'); - if (offset < len) { - c = s.charAt(offset++); - if (c > '9' || c < '0') { - return Integer.parseInt(s); - } - num = (num * 10) + (c - '0'); - // Let's just loop if we have more than 3 digits: - if (offset < len) { - do { - c = s.charAt(offset++); - if (c > '9' || c < '0') { - return Integer.parseInt(s); - } - num = (num * 10) + (c - '0'); - } while (offset < len); - } - } - } - return neg ? -num : num; - } - - public static long parseLong(char[] ch, int off, int len) - { - // Note: caller must ensure length is [10, 18] - int len1 = len-9; - long val = parseInt(ch, off, len1) * L_BILLION; - return val + (long) parseInt(ch, off+len1, 9); - } - - public static long parseLong(String s) - { - /* Ok, now; as the very first thing, let's just optimize case of "fake longs"; - * that is, if we know they must be ints, call int parsing - */ - int length = s.length(); - if (length <= 9) { - return (long) parseInt(s); - } - // !!! TODO: implement efficient 2-int parsing... - return Long.parseLong(s); - } - - /** - * Helper method for determining if given String representation of - * an integral number would fit in 64-bit Java long or not. - * Note that input String must NOT contain leading minus sign (even - * if 'negative' is set to true). - * - * @param negative Whether original number had a minus sign (which is - * NOT passed to this method) or not - */ - public static boolean inLongRange(char[] ch, int off, int len, - boolean negative) - { - String cmpStr = negative ? MIN_LONG_STR_NO_SIGN : MAX_LONG_STR; - int cmpLen = cmpStr.length(); - if (len < cmpLen) return true; - if (len > cmpLen) return false; - - for (int i = 0; i < cmpLen; ++i) { - int diff = ch[off+i] - cmpStr.charAt(i); - if (diff != 0) { - return (diff < 0); - } - } - return true; - } - - /** - * Similar to {@link #inLongRange(char[],int,int,boolean)}, but - * with String argument - * - * @param negative Whether original number had a minus sign (which is - * NOT passed to this method) or not - */ - public static boolean inLongRange(String s, boolean negative) - { - String cmp = negative ? MIN_LONG_STR_NO_SIGN : MAX_LONG_STR; - int cmpLen = cmp.length(); - int alen = s.length(); - if (alen < cmpLen) return true; - if (alen > cmpLen) return false; - - // could perhaps just use String.compareTo()? - for (int i = 0; i < cmpLen; ++i) { - int diff = s.charAt(i) - cmp.charAt(i); - if (diff != 0) { - return (diff < 0); - } - } - return true; - } - - public static int parseAsInt(String s, int def) - { - if (s == null) { - return def; - } - s = s.trim(); - int len = s.length(); - if (len == 0) { - return def; - } - // One more thing: use integer parsing for 'simple' - int i = 0; - if (i < len) { // skip leading sign: - char c = s.charAt(0); - if (c == '+') { // for plus, actually physically remove - s = s.substring(1); - len = s.length(); - } else if (c == '-') { // minus, just skip for checks, must retain - ++i; - } - } - for (; i < len; ++i) { - char c = s.charAt(i); - // if other symbols, parse as Double, coerce - if (c > '9' || c < '0') { - try { - return (int) parseDouble(s); - } catch (NumberFormatException e) { - return def; - } - } - } - try { - return Integer.parseInt(s); - } catch (NumberFormatException e) { } - return def; - } - - public static long parseAsLong(String s, long def) - { - if (s == null) { - return def; - } - s = s.trim(); - int len = s.length(); - if (len == 0) { - return def; - } - // One more thing: use long parsing for 'simple' - int i = 0; - if (i < len) { // skip leading sign: - char c = s.charAt(0); - if (c == '+') { // for plus, actually physically remove - s = s.substring(1); - len = s.length(); - } else if (c == '-') { // minus, just skip for checks, must retain - ++i; - } - } - for (; i < len; ++i) { - char c = s.charAt(i); - // if other symbols, parse as Double, coerce - if (c > '9' || c < '0') { - try { - return (long) parseDouble(s); - } catch (NumberFormatException e) { - return def; - } - } - } - try { - return Long.parseLong(s); - } catch (NumberFormatException e) { } - return def; - } - - public static double parseAsDouble(String s, double def) - { - if (s == null) { return def; } - s = s.trim(); - int len = s.length(); - if (len == 0) { - return def; - } - try { - return parseDouble(s); - } catch (NumberFormatException e) { } - return def; - } - - public static double parseDouble(String s) throws NumberFormatException { - // [JACKSON-486]: avoid some nasty float representations... but should it be MIN_NORMAL or MIN_VALUE? - /* as per [JACKSON-827], let's use MIN_VALUE as it is available on all JDKs; normalized - * only in JDK 1.6. In practice, should not really matter. - */ - if (NASTY_SMALL_DOUBLE.equals(s)) { - return Double.MIN_VALUE; - } - return Double.parseDouble(s); - } - - public static BigDecimal parseBigDecimal(String s) throws NumberFormatException { - try { return new BigDecimal(s); } catch (NumberFormatException e) { - throw _badBD(s); - } - } - - public static BigDecimal parseBigDecimal(char[] b) throws NumberFormatException { - return parseBigDecimal(b, 0, b.length); - } - - public static BigDecimal parseBigDecimal(char[] b, int off, int len) throws NumberFormatException { - try { return new BigDecimal(b, off, len); } catch (NumberFormatException e) { - throw _badBD(new String(b, off, len)); - } - } - - private static NumberFormatException _badBD(String s) { - return new NumberFormatException("Value \""+s+"\" can not be represented as BigDecimal"); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/NumberOutput.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/NumberOutput.java deleted file mode 100644 index 549fb8ee..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/NumberOutput.java +++ /dev/null @@ -1,497 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.io; - -public final class NumberOutput -{ - private static int MILLION = 1000000; - private static int BILLION = 1000000000; - private static long BILLION_L = 1000000000L; - - private static long MIN_INT_AS_LONG = (long) Integer.MIN_VALUE; - private static long MAX_INT_AS_LONG = (long) Integer.MAX_VALUE; - - final static String SMALLEST_INT = String.valueOf(Integer.MIN_VALUE); - final static String SMALLEST_LONG = String.valueOf(Long.MIN_VALUE); - - /** - * Encoded representations of 3-decimal-digit indexed values, where - * 3 LSB are ascii characters - * - * @since 2.8.2 - */ - private final static int[] TRIPLET_TO_CHARS = new int[1000]; - - static { - /* Let's fill it with NULLs for ignorable leading digits, - * and digit chars for others - */ - int fullIx = 0; - for (int i1 = 0; i1 < 10; ++i1) { - for (int i2 = 0; i2 < 10; ++i2) { - for (int i3 = 0; i3 < 10; ++i3) { - int enc = ((i1 + '0') << 16) - | ((i2 + '0') << 8) - | (i3 + '0'); - TRIPLET_TO_CHARS[fullIx++] = enc; - } - } - } - } - - private final static String[] sSmallIntStrs = new String[] { - "0","1","2","3","4","5","6","7","8","9","10" - }; - private final static String[] sSmallIntStrs2 = new String[] { - "-1","-2","-3","-4","-5","-6","-7","-8","-9","-10" - }; - - /* - /********************************************************** - /* Efficient serialization methods using raw buffers - /********************************************************** - */ - - /** - * @return Offset within buffer after outputting int - */ - public static int outputInt(int v, char[] b, int off) - { - if (v < 0) { - if (v == Integer.MIN_VALUE) { - // Special case: no matching positive value within range; - // let's then "upgrade" to long and output as such. - return _outputSmallestI(b, off); - } - b[off++] = '-'; - v = -v; - } - - if (v < MILLION) { // at most 2 triplets... - if (v < 1000) { - if (v < 10) { - b[off] = (char) ('0' + v); - return off+1; - } - return _leading3(v, b, off); - } - int thousands = v / 1000; - v -= (thousands * 1000); // == value % 1000 - off = _leading3(thousands, b, off); - off = _full3(v, b, off); - return off; - } - - // ok, all 3 triplets included - /* Let's first hand possible billions separately before - * handling 3 triplets. This is possible since we know we - * can have at most '2' as billion count. - */ - if (v >= BILLION) { - v -= BILLION; - if (v >= BILLION) { - v -= BILLION; - b[off++] = '2'; - } else { - b[off++] = '1'; - } - return _outputFullBillion(v, b, off); - } - int newValue = v / 1000; - int ones = (v - (newValue * 1000)); // == value % 1000 - v = newValue; - newValue /= 1000; - int thousands = (v - (newValue * 1000)); - - off = _leading3(newValue, b, off); - off = _full3(thousands, b, off); - return _full3(ones, b, off); - } - - public static int outputInt(int v, byte[] b, int off) - { - if (v < 0) { - if (v == Integer.MIN_VALUE) { - return _outputSmallestI(b, off); - } - b[off++] = '-'; - v = -v; - } - - if (v < MILLION) { // at most 2 triplets... - if (v < 1000) { - if (v < 10) { - b[off++] = (byte) ('0' + v); - } else { - off = _leading3(v, b, off); - } - } else { - int thousands = v / 1000; - v -= (thousands * 1000); // == value % 1000 - off = _leading3(thousands, b, off); - off = _full3(v, b, off); - } - return off; - } - if (v >= BILLION) { - v -= BILLION; - if (v >= BILLION) { - v -= BILLION; - b[off++] = '2'; - } else { - b[off++] = '1'; - } - return _outputFullBillion(v, b, off); - } - int newValue = v / 1000; - int ones = (v - (newValue * 1000)); // == value % 1000 - v = newValue; - newValue /= 1000; - int thousands = (v - (newValue * 1000)); - off = _leading3(newValue, b, off); - off = _full3(thousands, b, off); - return _full3(ones, b, off); - } - - /** - * @return Offset within buffer after outputting int - */ - public static int outputLong(long v, char[] b, int off) - { - // First: does it actually fit in an int? - if (v < 0L) { - if (v > MIN_INT_AS_LONG) { - return outputInt((int) v, b, off); - } - if (v == Long.MIN_VALUE) { - return _outputSmallestL(b, off); - } - b[off++] = '-'; - v = -v; - } else { - if (v <= MAX_INT_AS_LONG) { - return outputInt((int) v, b, off); - } - } - - // Ok, let's separate last 9 digits (3 x full sets of 3) - long upper = v / BILLION_L; - v -= (upper * BILLION_L); - - // two integers? - if (upper < BILLION_L) { - off = _outputUptoBillion((int) upper, b, off); - } else { - // no, two ints and bits; hi may be about 16 or so - long hi = upper / BILLION_L; - upper -= (hi * BILLION_L); - off = _leading3((int) hi, b, off); - off = _outputFullBillion((int) upper, b, off); - } - return _outputFullBillion((int) v, b, off); - } - - public static int outputLong(long v, byte[] b, int off) - { - if (v < 0L) { - if (v > MIN_INT_AS_LONG) { - return outputInt((int) v, b, off); - } - if (v == Long.MIN_VALUE) { - return _outputSmallestL(b, off); - } - b[off++] = '-'; - v = -v; - } else { - if (v <= MAX_INT_AS_LONG) { - return outputInt((int) v, b, off); - } - } - - // Ok, let's separate last 9 digits (3 x full sets of 3) - long upper = v / BILLION_L; - v -= (upper * BILLION_L); - - // two integers? - if (upper < BILLION_L) { - off = _outputUptoBillion((int) upper, b, off); - } else { - // no, two ints and bits; hi may be about 16 or so - long hi = upper / BILLION_L; - upper -= (hi * BILLION_L); - off = _leading3((int) hi, b, off); - off = _outputFullBillion((int) upper, b, off); - } - return _outputFullBillion((int) v, b, off); - } - - /* - /********************************************************** - /* Convenience serialization methods - /********************************************************** - */ - - /* !!! 05-Aug-2008, tatus: Any ways to further optimize - * these? (or need: only called by diagnostics methods?) - */ - public static String toString(int v) - { - // Lookup table for small values - if (v < sSmallIntStrs.length) { - if (v >= 0) { - return sSmallIntStrs[v]; - } - int v2 = -v - 1; - if (v2 < sSmallIntStrs2.length) { - return sSmallIntStrs2[v2]; - } - } - return Integer.toString(v); - } - - public static String toString(long v) { - if (v <= Integer.MAX_VALUE && v >= Integer.MIN_VALUE) { - return toString((int) v); - } - return Long.toString(v); - } - - public static String toString(double v) { - return Double.toString(v); - } - - /** - * @since 2.6.0 - */ - public static String toString(float v) { - return Float.toString(v); - } - - /* - /********************************************************** - /* Internal helper methods - /********************************************************** - */ - - private static int _outputUptoBillion(int v, char[] b, int off) - { - if (v < MILLION) { // at most 2 triplets... - if (v < 1000) { - return _leading3(v, b, off); - } - int thousands = v / 1000; - int ones = v - (thousands * 1000); // == value % 1000 - return _outputUptoMillion(b, off, thousands, ones); - } - int thousands = v / 1000; - int ones = (v - (thousands * 1000)); // == value % 1000 - int millions = thousands / 1000; - thousands -= (millions * 1000); - - off = _leading3(millions, b, off); - - int enc = TRIPLET_TO_CHARS[thousands]; - b[off++] = (char) (enc >> 16); - b[off++] = (char) ((enc >> 8) & 0x7F); - b[off++] = (char) (enc & 0x7F); - - enc = TRIPLET_TO_CHARS[ones]; - b[off++] = (char) (enc >> 16); - b[off++] = (char) ((enc >> 8) & 0x7F); - b[off++] = (char) (enc & 0x7F); - - return off; - } - - private static int _outputFullBillion(int v, char[] b, int off) - { - int thousands = v / 1000; - int ones = (v - (thousands * 1000)); // == value % 1000 - int millions = thousands / 1000; - - int enc = TRIPLET_TO_CHARS[millions]; - b[off++] = (char) (enc >> 16); - b[off++] = (char) ((enc >> 8) & 0x7F); - b[off++] = (char) (enc & 0x7F); - - thousands -= (millions * 1000); - enc = TRIPLET_TO_CHARS[thousands]; - b[off++] = (char) (enc >> 16); - b[off++] = (char) ((enc >> 8) & 0x7F); - b[off++] = (char) (enc & 0x7F); - - enc = TRIPLET_TO_CHARS[ones]; - b[off++] = (char) (enc >> 16); - b[off++] = (char) ((enc >> 8) & 0x7F); - b[off++] = (char) (enc & 0x7F); - - return off; - } - - private static int _outputUptoBillion(int v, byte[] b, int off) - { - if (v < MILLION) { // at most 2 triplets... - if (v < 1000) { - return _leading3(v, b, off); - } - int thousands = v / 1000; - int ones = v - (thousands * 1000); // == value % 1000 - return _outputUptoMillion(b, off, thousands, ones); - } - int thousands = v / 1000; - int ones = (v - (thousands * 1000)); // == value % 1000 - int millions = thousands / 1000; - thousands -= (millions * 1000); - - off = _leading3(millions, b, off); - - int enc = TRIPLET_TO_CHARS[thousands]; - b[off++] = (byte) (enc >> 16); - b[off++] = (byte) (enc >> 8); - b[off++] = (byte) enc; - - enc = TRIPLET_TO_CHARS[ones]; - b[off++] = (byte) (enc >> 16); - b[off++] = (byte) (enc >> 8); - b[off++] = (byte) enc; - - return off; - } - - private static int _outputFullBillion(int v, byte[] b, int off) - { - int thousands = v / 1000; - int ones = (v - (thousands * 1000)); // == value % 1000 - int millions = thousands / 1000; - thousands -= (millions * 1000); - - int enc = TRIPLET_TO_CHARS[millions]; - b[off++] = (byte) (enc >> 16); - b[off++] = (byte) (enc >> 8); - b[off++] = (byte) enc; - - enc = TRIPLET_TO_CHARS[thousands]; - b[off++] = (byte) (enc >> 16); - b[off++] = (byte) (enc >> 8); - b[off++] = (byte) enc; - - enc = TRIPLET_TO_CHARS[ones]; - b[off++] = (byte) (enc >> 16); - b[off++] = (byte) (enc >> 8); - b[off++] = (byte) enc; - - return off; - } - - private static int _outputUptoMillion(char[] b, int off, int thousands, int ones) - { - int enc = TRIPLET_TO_CHARS[thousands]; - if (thousands > 9) { - if (thousands > 99) { - b[off++] = (char) (enc >> 16); - } - b[off++] = (char) ((enc >> 8) & 0x7F); - } - b[off++] = (char) (enc & 0x7F); - // and then full - enc = TRIPLET_TO_CHARS[ones]; - b[off++] = (char) (enc >> 16); - b[off++] = (char) ((enc >> 8) & 0x7F); - b[off++] = (char) (enc & 0x7F); - return off; - } - - private static int _outputUptoMillion(byte[] b, int off, int thousands, int ones) - { - int enc = TRIPLET_TO_CHARS[thousands]; - if (thousands > 9) { - if (thousands > 99) { - b[off++] = (byte) (enc >> 16); - } - b[off++] = (byte) (enc >> 8); - } - b[off++] = (byte) enc; - // and then full - enc = TRIPLET_TO_CHARS[ones]; - b[off++] = (byte) (enc >> 16); - b[off++] = (byte) (enc >> 8); - b[off++] = (byte) enc; - return off; - } - - private static int _leading3(int t, char[] b, int off) - { - int enc = TRIPLET_TO_CHARS[t]; - if (t > 9) { - if (t > 99) { - b[off++] = (char) (enc >> 16); - } - b[off++] = (char) ((enc >> 8) & 0x7F); - } - b[off++] = (char) (enc & 0x7F); - return off; - } - - private static int _leading3(int t, byte[] b, int off) - { - int enc = TRIPLET_TO_CHARS[t]; - if (t > 9) { - if (t > 99) { - b[off++] = (byte) (enc >> 16); - } - b[off++] = (byte) (enc >> 8); - } - b[off++] = (byte) enc; - return off; - } - - private static int _full3(int t, char[] b, int off) - { - int enc = TRIPLET_TO_CHARS[t]; - b[off++] = (char) (enc >> 16); - b[off++] = (char) ((enc >> 8) & 0x7F); - b[off++] = (char) (enc & 0x7F); - return off; - } - - private static int _full3(int t, byte[] b, int off) - { - int enc = TRIPLET_TO_CHARS[t]; - b[off++] = (byte) (enc >> 16); - b[off++] = (byte) (enc >> 8); - b[off++] = (byte) enc; - return off; - } - - // // // Special cases for where we can not flip the sign bit - - private static int _outputSmallestL(char[] b, int off) - { - int len = SMALLEST_LONG.length(); - SMALLEST_LONG.getChars(0, len, b, off); - return (off + len); - } - - private static int _outputSmallestL(byte[] b, int off) - { - int len = SMALLEST_LONG.length(); - for (int i = 0; i < len; ++i) { - b[off++] = (byte) SMALLEST_LONG.charAt(i); - } - return off; - } - - private static int _outputSmallestI(char[] b, int off) - { - int len = SMALLEST_INT.length(); - SMALLEST_INT.getChars(0, len, b, off); - return (off + len); - } - - private static int _outputSmallestI(byte[] b, int off) - { - int len = SMALLEST_INT.length(); - for (int i = 0; i < len; ++i) { - b[off++] = (byte) SMALLEST_INT.charAt(i); - } - return off; - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/OutputDecorator.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/OutputDecorator.java deleted file mode 100644 index be92d750..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/OutputDecorator.java +++ /dev/null @@ -1,40 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.io; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.Writer; - -/** - * Handler class that can be used to decorate output destinations. - * Typical use is to use a filter abstraction (filtered output stream, - * writer) around original output destination, and apply additional - * processing during write operations. - */ -@SuppressWarnings("serial") -public abstract class OutputDecorator implements java.io.Serializable // since 2.1 -{ - /** - * Method called by {@link autosaveworld.zlibs.com.fasterxml.jackson.core.JsonFactory} instance when - * creating generator for given {@link OutputStream}, when this decorator - * has been registered. - * - * @param ctxt IO context in use (provides access to declared encoding) - * @param out Original output destination - * - * @return OutputStream to use; either passed in argument, or something that - * calls it - */ - public abstract OutputStream decorate(IOContext ctxt, OutputStream out) throws IOException; - - /** - * Method called by {@link autosaveworld.zlibs.com.fasterxml.jackson.core.JsonFactory} instance when - * creating generator for given {@link Writer}, when this decorator - * has been registered. - * - * @param ctxt IO context in use (provides access to declared encoding) - * @param w Original output writer - * - * @return Writer to use; either passed in argument, or something that calls it - */ - public abstract Writer decorate(IOContext ctxt, Writer w) throws IOException; -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/SegmentedStringWriter.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/SegmentedStringWriter.java deleted file mode 100644 index 461ae9c5..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/SegmentedStringWriter.java +++ /dev/null @@ -1,88 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.io; - -import java.io.StringWriter; -import java.io.Writer; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.BufferRecycler; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.TextBuffer; - -/** - * Efficient alternative to {@link StringWriter}, based on using segmented - * internal buffer. Initial input buffer is also recyclable. - *

- * This class is most useful when serializing JSON content as a String: - * if so, instance of this class can be given as the writer to - * JsonGenerator. - */ -public final class SegmentedStringWriter extends Writer -{ - final private TextBuffer _buffer; - - public SegmentedStringWriter(BufferRecycler br) { - super(); - _buffer = new TextBuffer(br); - } - - /* - /********************************************************** - /* java.io.Writer implementation - /********************************************************** - */ - - @Override - public Writer append(char c) { - write(c); - return this; - } - - @Override - public Writer append(CharSequence csq) { - String str = csq.toString(); - _buffer.append(str, 0, str.length()); - return this; - } - - @Override - public Writer append(CharSequence csq, int start, int end) { - String str = csq.subSequence(start, end).toString(); - _buffer.append(str, 0, str.length()); - return this; - } - - @Override public void close() { } // NOP - @Override public void flush() { } // NOP - - @Override - public void write(char[] cbuf) { _buffer.append(cbuf, 0, cbuf.length); } - - @Override - public void write(char[] cbuf, int off, int len) { _buffer.append(cbuf, off, len); } - - @Override - public void write(int c) { _buffer.append((char) c); } - - @Override - public void write(String str) { _buffer.append(str, 0, str.length()); } - - @Override - public void write(String str, int off, int len) { _buffer.append(str, off, len); } - - /* - /********************************************************** - /* Extended API - /********************************************************** - */ - - /** - * Main access method that will construct a String that contains - * all the contents, release all internal buffers we may have, - * and return result String. - * Note that the method is not idempotent -- if called second time, - * will just return an empty String. - */ - public String getAndClear() { - String result = _buffer.contentsAsString(); - _buffer.releaseBuffers(); - return result; - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/SerializedString.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/SerializedString.java deleted file mode 100644 index 60b6f404..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/SerializedString.java +++ /dev/null @@ -1,274 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.io; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.OutputStream; -import java.nio.ByteBuffer; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.SerializableString; - -/** - * String token that can lazily serialize String contained and then reuse that - * serialization later on. This is similar to JDBC prepared statements, for example, - * in that instances should only be created when they are used more than use; - * prime candidates are various serializers. - *

- * Class is final for performance reasons and since this is not designed to - * be extensible or customizable (customizations would occur in calling code) - */ -public class SerializedString - implements SerializableString, java.io.Serializable -{ - private static final long serialVersionUID = 1L; - - protected final String _value; - - /* 13-Dec-2010, tatu: Whether use volatile or not is actually an important - * decision for multi-core use cases. Cost of volatility can be non-trivial - * for heavy use cases, and serialized-string instances are accessed often. - * Given that all code paths with common Jackson usage patterns go through - * a few memory barriers (mostly with cache/reuse pool access) it seems safe - * enough to omit volatiles here, given how simple lazy initialization is. - * This can be compared to how {@link String#hashCode} works; lazily and - * without synchronization or use of volatile keyword. - * - * Change to remove volatile was a request by implementors of a high-throughput - * search framework; and they believed this is an important optimization for - * heaviest, multi-core deployed use cases. - */ - /* - * 22-Sep-2013, tatu: FWIW, there have been no reports of problems in this - * area, or anything pointing to it. So I think we are safe up to JDK7 - * and hopefully beyond. - */ - - protected /*volatile*/ byte[] _quotedUTF8Ref; - - protected /*volatile*/ byte[] _unquotedUTF8Ref; - - protected /*volatile*/ char[] _quotedChars; - - public SerializedString(String v) { - if (v == null) { - throw new IllegalStateException("Null String illegal for SerializedString"); - } - _value = v; - } - - /* - /********************************************************** - /* Serializable overrides - /********************************************************** - */ - - /** - * Ugly hack, to work through the requirement that _value is indeed final, - * and that JDK serialization won't call ctor(s). - * - * @since 2.1 - */ - protected transient String _jdkSerializeValue; - - private void readObject(ObjectInputStream in) throws IOException { - _jdkSerializeValue = in.readUTF(); - } - - private void writeObject(ObjectOutputStream out) throws IOException { - out.writeUTF(_value); - } - - protected Object readResolve() { - return new SerializedString(_jdkSerializeValue); - } - - /* - /********************************************************** - /* API - /********************************************************** - */ - - @Override - public final String getValue() { return _value; } - - /** - * Returns length of the String as characters - */ - @Override - public final int charLength() { return _value.length(); } - - @Override - public final char[] asQuotedChars() { - char[] result = _quotedChars; - if (result == null) { - result = JsonStringEncoder.getInstance().quoteAsString(_value); - _quotedChars = result; - } - return result; - } - - /** - * Accessor for accessing value that has been quoted using JSON - * quoting rules, and encoded using UTF-8 encoding. - */ - @Override - public final byte[] asUnquotedUTF8() { - byte[] result = _unquotedUTF8Ref; - if (result == null) { - result = JsonStringEncoder.getInstance().encodeAsUTF8(_value); - _unquotedUTF8Ref = result; - } - return result; - } - - /** - * Accessor for accessing value as is (without JSON quoting) - * encoded using UTF-8 encoding. - */ - @Override - public final byte[] asQuotedUTF8() { - byte[] result = _quotedUTF8Ref; - if (result == null) { - result = JsonStringEncoder.getInstance().quoteAsUTF8(_value); - _quotedUTF8Ref = result; - } - return result; - } - - /* - /********************************************************** - /* Additional 2.0 methods for appending/writing contents - /********************************************************** - */ - - @Override - public int appendQuotedUTF8(byte[] buffer, int offset) { - byte[] result = _quotedUTF8Ref; - if (result == null) { - result = JsonStringEncoder.getInstance().quoteAsUTF8(_value); - _quotedUTF8Ref = result; - } - final int length = result.length; - if ((offset + length) > buffer.length) { - return -1; - } - System.arraycopy(result, 0, buffer, offset, length); - return length; - } - - @Override - public int appendQuoted(char[] buffer, int offset) { - char[] result = _quotedChars; - if (result == null) { - result = JsonStringEncoder.getInstance().quoteAsString(_value); - _quotedChars = result; - } - final int length = result.length; - if ((offset + length) > buffer.length) { - return -1; - } - System.arraycopy(result, 0, buffer, offset, length); - return length; - } - - @Override - public int appendUnquotedUTF8(byte[] buffer, int offset) { - byte[] result = _unquotedUTF8Ref; - if (result == null) { - result = JsonStringEncoder.getInstance().encodeAsUTF8(_value); - _unquotedUTF8Ref = result; - } - final int length = result.length; - if ((offset + length) > buffer.length) { - return -1; - } - System.arraycopy(result, 0, buffer, offset, length); - return length; - } - - @Override - public int appendUnquoted(char[] buffer, int offset) { - String str = _value; - final int length = str.length(); - if ((offset + length) > buffer.length) { - return -1; - } - str.getChars(0, length, buffer, offset); - return length; - } - - @Override - public int writeQuotedUTF8(OutputStream out) throws IOException { - byte[] result = _quotedUTF8Ref; - if (result == null) { - result = JsonStringEncoder.getInstance().quoteAsUTF8(_value); - _quotedUTF8Ref = result; - } - final int length = result.length; - out.write(result, 0, length); - return length; - } - - @Override - public int writeUnquotedUTF8(OutputStream out) throws IOException { - byte[] result = _unquotedUTF8Ref; - if (result == null) { - result = JsonStringEncoder.getInstance().encodeAsUTF8(_value); - _unquotedUTF8Ref = result; - } - final int length = result.length; - out.write(result, 0, length); - return length; - } - - @Override - public int putQuotedUTF8(ByteBuffer buffer) { - byte[] result = _quotedUTF8Ref; - if (result == null) { - result = JsonStringEncoder.getInstance().quoteAsUTF8(_value); - _quotedUTF8Ref = result; - } - final int length = result.length; - if (length > buffer.remaining()) { - return -1; - } - buffer.put(result, 0, length); - return length; - } - - @Override - public int putUnquotedUTF8(ByteBuffer buffer) { - byte[] result = _unquotedUTF8Ref; - if (result == null) { - result = JsonStringEncoder.getInstance().encodeAsUTF8(_value); - _unquotedUTF8Ref = result; - } - final int length = result.length; - if (length > buffer.remaining()) { - return -1; - } - buffer.put(result, 0, length); - return length; - } - - - /* - /********************************************************** - /* Standard method overrides - /********************************************************** - */ - - @Override - public final String toString() { return _value; } - - @Override - public final int hashCode() { return _value.hashCode(); } - - @Override - public final boolean equals(Object o) { - if (o == this) return true; - if (o == null || o.getClass() != getClass()) return false; - SerializedString other = (SerializedString) o; - return _value.equals(other._value); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/UTF32Reader.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/UTF32Reader.java deleted file mode 100644 index f16df44d..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/UTF32Reader.java +++ /dev/null @@ -1,271 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.io; - -import java.io.CharConversionException; -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; - - -/** - * Since JDK does not come with UTF-32/UCS-4, let's implement a simple - * decoder to use. - */ -public class UTF32Reader extends Reader -{ - /** - * JSON actually limits available Unicode range in the high end - * to the same as xml (to basically limit UTF-8 max byte sequence - * length to 4) - */ - final protected static int LAST_VALID_UNICODE_CHAR = 0x10FFFF; - - final protected static char NC = (char) 0; - - final protected IOContext _context; - - protected InputStream _in; - - protected byte[] _buffer; - - protected int _ptr; - protected int _length; - - protected final boolean _bigEndian; - - /** - * Although input is fine with full Unicode set, Java still uses - * 16-bit chars, so we may have to split high-order chars into - * surrogate pairs. - */ - protected char _surrogate = NC; - - /** - * Total read character count; used for error reporting purposes - */ - protected int _charCount; - - /** - * Total read byte count; used for error reporting purposes - */ - protected int _byteCount; - - protected final boolean _managedBuffers; - - /* - /********************************************************** - /* Life-cycle - /********************************************************** - */ - - public UTF32Reader(IOContext ctxt, InputStream in, byte[] buf, int ptr, int len, boolean isBigEndian) { - _context = ctxt; - _in = in; - _buffer = buf; - _ptr = ptr; - _length = len; - _bigEndian = isBigEndian; - _managedBuffers = (in != null); - } - - /* - /********************************************************** - /* Public API - /********************************************************** - */ - - @Override - public void close() throws IOException { - InputStream in = _in; - - if (in != null) { - _in = null; - freeBuffers(); - in.close(); - } - } - - protected char[] _tmpBuf; - - /** - * Although this method is implemented by the base class, AND it should - * never be called by main code, let's still implement it bit more - * efficiently just in case - */ - @Override - public int read() throws IOException { - if (_tmpBuf == null) { - _tmpBuf = new char[1]; - } - if (read(_tmpBuf, 0, 1) < 1) { - return -1; - } - return _tmpBuf[0]; - } - - @Override - public int read(char[] cbuf, int start, int len) throws IOException { - // Already EOF? - if (_buffer == null) { return -1; } - if (len < 1) { return len; } - // Let's then ensure there's enough room... - if (start < 0 || (start+len) > cbuf.length) { - reportBounds(cbuf, start, len); - } - - len += start; - int outPtr = start; - - // Ok, first; do we have a surrogate from last round? - if (_surrogate != NC) { - cbuf[outPtr++] = _surrogate; - _surrogate = NC; - // No need to load more, already got one char - } else { - /* Note: we'll try to avoid blocking as much as possible. As a - * result, we only need to get 4 bytes for a full char. - */ - int left = (_length - _ptr); - if (left < 4) { - if (!loadMore(left)) { // (legal) EOF? - return -1; - } - } - } - - main_loop: - while (outPtr < len) { - int ptr = _ptr; - int ch; - - if (_bigEndian) { - ch = (_buffer[ptr] << 24) | ((_buffer[ptr+1] & 0xFF) << 16) - | ((_buffer[ptr+2] & 0xFF) << 8) | (_buffer[ptr+3] & 0xFF); - } else { - ch = (_buffer[ptr] & 0xFF) | ((_buffer[ptr+1] & 0xFF) << 8) - | ((_buffer[ptr+2] & 0xFF) << 16) | (_buffer[ptr+3] << 24); - } - _ptr += 4; - - // Does it need to be split to surrogates? - // (also, we can and need to verify illegal chars) - if (ch > 0xFFFF) { // need to split into surrogates? - if (ch > LAST_VALID_UNICODE_CHAR) { - reportInvalid(ch, outPtr-start, - "(above "+Integer.toHexString(LAST_VALID_UNICODE_CHAR)+") "); - } - ch -= 0x10000; // to normalize it starting with 0x0 - cbuf[outPtr++] = (char) (0xD800 + (ch >> 10)); - // hmmh. can this ever be 0? (not legal, at least?) - ch = (0xDC00 | (ch & 0x03FF)); - // Room for second part? - if (outPtr >= len) { // nope - _surrogate = (char) ch; - break main_loop; - } - } - cbuf[outPtr++] = (char) ch; - if (_ptr >= _length) { - break main_loop; - } - } - - len = outPtr - start; - _charCount += len; - return len; - } - - /* - /********************************************************** - /* Internal methods - /********************************************************** - */ - - private void reportUnexpectedEOF(int gotBytes, int needed) throws IOException { - int bytePos = _byteCount + gotBytes, charPos = _charCount; - - throw new CharConversionException("Unexpected EOF in the middle of a 4-byte UTF-32 char: got "+gotBytes+", needed "+needed+", at char #"+charPos+", byte #"+bytePos+")"); - } - - private void reportInvalid(int value, int offset, String msg) throws IOException { - int bytePos = _byteCount + _ptr - 1, charPos = _charCount + offset; - - throw new CharConversionException("Invalid UTF-32 character 0x"+Integer.toHexString(value)+msg+" at char #"+charPos+", byte #"+bytePos+")"); - } - - /** - * @param available Number of "unused" bytes in the input buffer - * - * @return True, if enough bytes were read to allow decoding of at least - * one full character; false if EOF was encountered instead. - */ - private boolean loadMore(int available) throws IOException { - _byteCount += (_length - available); - - // Bytes that need to be moved to the beginning of buffer? - if (available > 0) { - if (_ptr > 0) { - System.arraycopy(_buffer, _ptr, _buffer, 0, available); - _ptr = 0; - } - _length = available; - } else { - /* Ok; here we can actually reasonably expect an EOF, - * so let's do a separate read right away: - */ - _ptr = 0; - int count = (_in == null) ? -1 : _in.read(_buffer); - if (count < 1) { - _length = 0; - if (count < 0) { // -1 - if (_managedBuffers) { - freeBuffers(); // to help GC? - } - return false; - } - // 0 count is no good; let's err out - reportStrangeStream(); - } - _length = count; - } - - /* Need at least 4 bytes; if we don't get that many, it's an - * error. - */ - while (_length < 4) { - int count = (_in == null) ? -1 : _in.read(_buffer, _length, _buffer.length - _length); - if (count < 1) { - if (count < 0) { // -1, EOF... no good! - if (_managedBuffers) { - freeBuffers(); // to help GC? - } - reportUnexpectedEOF(_length, 4); - } - // 0 count is no good; let's err out - reportStrangeStream(); - } - _length += count; - } - return true; - } - - /** - * This method should be called along with (or instead of) normal - * close. After calling this method, no further reads should be tried. - * Method will try to recycle read buffers (if any). - */ - private void freeBuffers() { - byte[] buf = _buffer; - if (buf != null) { - _buffer = null; - _context.releaseReadIOBuffer(buf); - } - } - - private void reportBounds(char[] cbuf, int start, int len) throws IOException { - throw new ArrayIndexOutOfBoundsException("read(buf,"+start+","+len+"), cbuf["+cbuf.length+"]"); - } - - private void reportStrangeStream() throws IOException { - throw new IOException("Strange I/O stream, returned 0 bytes on read"); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/UTF8Writer.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/UTF8Writer.java deleted file mode 100644 index 069c1996..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/io/UTF8Writer.java +++ /dev/null @@ -1,389 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.io; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.Writer; - -public final class UTF8Writer extends Writer -{ - final static int SURR1_FIRST = 0xD800; - final static int SURR1_LAST = 0xDBFF; - final static int SURR2_FIRST = 0xDC00; - final static int SURR2_LAST = 0xDFFF; - - final private IOContext _context; - - private OutputStream _out; - - private byte[] _outBuffer; - - final private int _outBufferEnd; - - private int _outPtr; - - /** - * When outputting chars from BMP, surrogate pairs need to be coalesced. - * To do this, both pairs must be known first; and since it is possible - * pairs may be split, we need temporary storage for the first half - */ - private int _surrogate; - - public UTF8Writer(IOContext ctxt, OutputStream out) - { - _context = ctxt; - _out = out; - - _outBuffer = ctxt.allocWriteEncodingBuffer(); - /* Max. expansion for a single char (in unmodified UTF-8) is - * 4 bytes (or 3 depending on how you view it -- 4 when recombining - * surrogate pairs) - */ - _outBufferEnd = _outBuffer.length - 4; - _outPtr = 0; - } - - @Override - public Writer append(char c) - throws IOException - { - write(c); - return this; - } - - @Override - public void close() - throws IOException - { - if (_out != null) { - if (_outPtr > 0) { - _out.write(_outBuffer, 0, _outPtr); - _outPtr = 0; - } - OutputStream out = _out; - _out = null; - - byte[] buf = _outBuffer; - if (buf != null) { - _outBuffer = null; - _context.releaseWriteEncodingBuffer(buf); - } - - out.close(); - - /* Let's 'flush' orphan surrogate, no matter what; but only - * after cleanly closing everything else. - */ - int code = _surrogate; - _surrogate = 0; - if (code > 0) { - illegalSurrogate(code); - } - } - } - - @Override - public void flush() - throws IOException - { - if (_out != null) { - if (_outPtr > 0) { - _out.write(_outBuffer, 0, _outPtr); - _outPtr = 0; - } - _out.flush(); - } - } - - @Override - public void write(char[] cbuf) - throws IOException - { - write(cbuf, 0, cbuf.length); - } - - @Override - public void write(char[] cbuf, int off, int len) - throws IOException - { - if (len < 2) { - if (len == 1) { - write(cbuf[off]); - } - return; - } - - // First: do we have a leftover surrogate to deal with? - if (_surrogate > 0) { - char second = cbuf[off++]; - --len; - write(convertSurrogate(second)); - // will have at least one more char - } - - int outPtr = _outPtr; - byte[] outBuf = _outBuffer; - int outBufLast = _outBufferEnd; // has 4 'spare' bytes - - // All right; can just loop it nice and easy now: - len += off; // len will now be the end of input buffer - - output_loop: - for (; off < len; ) { - /* First, let's ensure we can output at least 4 bytes - * (longest UTF-8 encoded codepoint): - */ - if (outPtr >= outBufLast) { - _out.write(outBuf, 0, outPtr); - outPtr = 0; - } - - int c = cbuf[off++]; - // And then see if we have an Ascii char: - if (c < 0x80) { // If so, can do a tight inner loop: - outBuf[outPtr++] = (byte)c; - // Let's calc how many ascii chars we can copy at most: - int maxInCount = (len - off); - int maxOutCount = (outBufLast - outPtr); - - if (maxInCount > maxOutCount) { - maxInCount = maxOutCount; - } - maxInCount += off; - ascii_loop: - while (true) { - if (off >= maxInCount) { // done with max. ascii seq - continue output_loop; - } - c = cbuf[off++]; - if (c >= 0x80) { - break ascii_loop; - } - outBuf[outPtr++] = (byte) c; - } - } - - // Nope, multi-byte: - if (c < 0x800) { // 2-byte - outBuf[outPtr++] = (byte) (0xc0 | (c >> 6)); - outBuf[outPtr++] = (byte) (0x80 | (c & 0x3f)); - } else { // 3 or 4 bytes - // Surrogates? - if (c < SURR1_FIRST || c > SURR2_LAST) { - outBuf[outPtr++] = (byte) (0xe0 | (c >> 12)); - outBuf[outPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f)); - outBuf[outPtr++] = (byte) (0x80 | (c & 0x3f)); - continue; - } - // Yup, a surrogate: - if (c > SURR1_LAST) { // must be from first range - _outPtr = outPtr; - illegalSurrogate(c); - } - _surrogate = c; - // and if so, followed by another from next range - if (off >= len) { // unless we hit the end? - break; - } - c = convertSurrogate(cbuf[off++]); - if (c > 0x10FFFF) { // illegal in JSON as well as in XML - _outPtr = outPtr; - illegalSurrogate(c); - } - outBuf[outPtr++] = (byte) (0xf0 | (c >> 18)); - outBuf[outPtr++] = (byte) (0x80 | ((c >> 12) & 0x3f)); - outBuf[outPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f)); - outBuf[outPtr++] = (byte) (0x80 | (c & 0x3f)); - } - } - _outPtr = outPtr; - } - - @Override - public void write(int c) throws IOException - { - // First; do we have a left over surrogate? - if (_surrogate > 0) { - c = convertSurrogate(c); - // If not, do we start with a surrogate? - } else if (c >= SURR1_FIRST && c <= SURR2_LAST) { - // Illegal to get second part without first: - if (c > SURR1_LAST) { - illegalSurrogate(c); - } - // First part just needs to be held for now - _surrogate = c; - return; - } - - if (_outPtr >= _outBufferEnd) { // let's require enough room, first - _out.write(_outBuffer, 0, _outPtr); - _outPtr = 0; - } - - if (c < 0x80) { // ascii - _outBuffer[_outPtr++] = (byte) c; - } else { - int ptr = _outPtr; - if (c < 0x800) { // 2-byte - _outBuffer[ptr++] = (byte) (0xc0 | (c >> 6)); - _outBuffer[ptr++] = (byte) (0x80 | (c & 0x3f)); - } else if (c <= 0xFFFF) { // 3 bytes - _outBuffer[ptr++] = (byte) (0xe0 | (c >> 12)); - _outBuffer[ptr++] = (byte) (0x80 | ((c >> 6) & 0x3f)); - _outBuffer[ptr++] = (byte) (0x80 | (c & 0x3f)); - } else { // 4 bytes - if (c > 0x10FFFF) { // illegal - illegalSurrogate(c); - } - _outBuffer[ptr++] = (byte) (0xf0 | (c >> 18)); - _outBuffer[ptr++] = (byte) (0x80 | ((c >> 12) & 0x3f)); - _outBuffer[ptr++] = (byte) (0x80 | ((c >> 6) & 0x3f)); - _outBuffer[ptr++] = (byte) (0x80 | (c & 0x3f)); - } - _outPtr = ptr; - } - } - - @Override - public void write(String str) throws IOException - { - write(str, 0, str.length()); - } - - @Override - public void write(String str, int off, int len) throws IOException - { - if (len < 2) { - if (len == 1) { - write(str.charAt(off)); - } - return; - } - - // First: do we have a leftover surrogate to deal with? - if (_surrogate > 0) { - char second = str.charAt(off++); - --len; - write(convertSurrogate(second)); - // will have at least one more char (case of 1 char was checked earlier on) - } - - int outPtr = _outPtr; - byte[] outBuf = _outBuffer; - int outBufLast = _outBufferEnd; // has 4 'spare' bytes - - // All right; can just loop it nice and easy now: - len += off; // len will now be the end of input buffer - - output_loop: - for (; off < len; ) { - /* First, let's ensure we can output at least 4 bytes - * (longest UTF-8 encoded codepoint): - */ - if (outPtr >= outBufLast) { - _out.write(outBuf, 0, outPtr); - outPtr = 0; - } - - int c = str.charAt(off++); - // And then see if we have an Ascii char: - if (c < 0x80) { // If so, can do a tight inner loop: - outBuf[outPtr++] = (byte)c; - // Let's calc how many ascii chars we can copy at most: - int maxInCount = (len - off); - int maxOutCount = (outBufLast - outPtr); - - if (maxInCount > maxOutCount) { - maxInCount = maxOutCount; - } - maxInCount += off; - ascii_loop: - while (true) { - if (off >= maxInCount) { // done with max. ascii seq - continue output_loop; - } - c = str.charAt(off++); - if (c >= 0x80) { - break ascii_loop; - } - outBuf[outPtr++] = (byte) c; - } - } - - // Nope, multi-byte: - if (c < 0x800) { // 2-byte - outBuf[outPtr++] = (byte) (0xc0 | (c >> 6)); - outBuf[outPtr++] = (byte) (0x80 | (c & 0x3f)); - } else { // 3 or 4 bytes - // Surrogates? - if (c < SURR1_FIRST || c > SURR2_LAST) { - outBuf[outPtr++] = (byte) (0xe0 | (c >> 12)); - outBuf[outPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f)); - outBuf[outPtr++] = (byte) (0x80 | (c & 0x3f)); - continue; - } - // Yup, a surrogate: - if (c > SURR1_LAST) { // must be from first range - _outPtr = outPtr; - illegalSurrogate(c); - } - _surrogate = c; - // and if so, followed by another from next range - if (off >= len) { // unless we hit the end? - break; - } - c = convertSurrogate(str.charAt(off++)); - if (c > 0x10FFFF) { // illegal, as per RFC 4627 - _outPtr = outPtr; - illegalSurrogate(c); - } - outBuf[outPtr++] = (byte) (0xf0 | (c >> 18)); - outBuf[outPtr++] = (byte) (0x80 | ((c >> 12) & 0x3f)); - outBuf[outPtr++] = (byte) (0x80 | ((c >> 6) & 0x3f)); - outBuf[outPtr++] = (byte) (0x80 | (c & 0x3f)); - } - } - _outPtr = outPtr; - } - - /* - /********************************************************** - /* Internal methods - /********************************************************** - */ - - /** - * Method called to calculate UTF codepoint, from a surrogate pair. - */ - protected int convertSurrogate(int secondPart) - throws IOException - { - int firstPart = _surrogate; - _surrogate = 0; - - // Ok, then, is the second part valid? - if (secondPart < SURR2_FIRST || secondPart > SURR2_LAST) { - throw new IOException("Broken surrogate pair: first char 0x"+Integer.toHexString(firstPart)+", second 0x"+Integer.toHexString(secondPart)+"; illegal combination"); - } - return 0x10000 + ((firstPart - SURR1_FIRST) << 10) + (secondPart - SURR2_FIRST); - } - - protected static void illegalSurrogate(int code) throws IOException { - throw new IOException(illegalSurrogateDesc(code)); - } - - protected static String illegalSurrogateDesc(int code) - { - if (code > 0x10FFFF) { // over max? - return "Illegal character point (0x"+Integer.toHexString(code)+") to output; max is 0x10FFFF as per RFC 4627"; - } - if (code >= SURR1_FIRST) { - if (code <= SURR1_LAST) { // Unmatched first part (closing without second part?) - return "Unmatched first part of surrogate pair (0x"+Integer.toHexString(code)+")"; - } - return "Unmatched second part of surrogate pair (0x"+Integer.toHexString(code)+")"; - } - // should we ever get this? - return "Illegal character point (0x"+Integer.toHexString(code)+") to output"; - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/ByteSourceJsonBootstrapper.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/ByteSourceJsonBootstrapper.java deleted file mode 100644 index f688f3d5..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/ByteSourceJsonBootstrapper.java +++ /dev/null @@ -1,543 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.json; - -import java.io.ByteArrayInputStream; -import java.io.CharConversionException; -import java.io.DataInput; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonEncoding; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonFactory; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.ObjectCodec; -import autosaveworld.zlibs.com.fasterxml.jackson.core.format.InputAccessor; -import autosaveworld.zlibs.com.fasterxml.jackson.core.format.MatchStrength; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.IOContext; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.MergedStream; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.UTF32Reader; -import autosaveworld.zlibs.com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.sym.CharsToNameCanonicalizer; - -/** - * This class is used to determine the encoding of byte stream - * that is to contain JSON content. Rules are fairly simple, and - * defined in JSON specification (RFC-4627 or newer), except - * for BOM handling, which is a property of underlying - * streams. - */ -public final class ByteSourceJsonBootstrapper -{ - final static byte UTF8_BOM_1 = (byte) 0xEF; - final static byte UTF8_BOM_2 = (byte) 0xBB; - final static byte UTF8_BOM_3 = (byte) 0xBF; - - /* - /********************************************************** - /* Configuration - /********************************************************** - */ - - private final IOContext _context; - - private final InputStream _in; - - /* - /********************************************************** - /* Input buffering - /********************************************************** - */ - - private final byte[] _inputBuffer; - - private int _inputPtr; - - private int _inputEnd; - - /** - * Flag that indicates whether buffer above is to be recycled - * after being used or not. - */ - private final boolean _bufferRecyclable; - - /* - /********************************************************** - /* Input location - /********************************************************** - */ - - /** - * Current number of input units (bytes or chars) that were processed in - * previous blocks, - * before contents of current input buffer. - *

- * Note: includes possible BOMs, if those were part of the input. - */ -// private int _inputProcessed; - - /* - /********************************************************** - /* Data gathered - /********************************************************** - */ - - /** - * Whether input has been detected to be in Big-Endian encoding or not. - */ - private boolean _bigEndian = true; - - private int _bytesPerChar; // 0 means "dunno yet" - - /* - /********************************************************** - /* Life-cycle - /********************************************************** - */ - - public ByteSourceJsonBootstrapper(IOContext ctxt, InputStream in) { - _context = ctxt; - _in = in; - _inputBuffer = ctxt.allocReadIOBuffer(); - _inputEnd = _inputPtr = 0; -// _inputProcessed = 0; - _bufferRecyclable = true; - } - - public ByteSourceJsonBootstrapper(IOContext ctxt, byte[] inputBuffer, int inputStart, int inputLen) { - _context = ctxt; - _in = null; - _inputBuffer = inputBuffer; - _inputPtr = inputStart; - _inputEnd = (inputStart + inputLen); - // Need to offset this for correct location info -// _inputProcessed = -inputStart; - _bufferRecyclable = false; - } - - /* - /********************************************************** - /* Encoding detection during bootstrapping - /********************************************************** - */ - - /** - * Method that should be called after constructing an instace. - * It will figure out encoding that content uses, to allow - * for instantiating a proper scanner object. - */ - public JsonEncoding detectEncoding() throws IOException - { - boolean foundEncoding = false; - - // First things first: BOM handling - /* Note: we can require 4 bytes to be read, since no - * combination of BOM + valid JSON content can have - * shorter length (shortest valid JSON content is single - * digit char, but BOMs are chosen such that combination - * is always at least 4 chars long) - */ - if (ensureLoaded(4)) { - int quad = (_inputBuffer[_inputPtr] << 24) - | ((_inputBuffer[_inputPtr+1] & 0xFF) << 16) - | ((_inputBuffer[_inputPtr+2] & 0xFF) << 8) - | (_inputBuffer[_inputPtr+3] & 0xFF); - - if (handleBOM(quad)) { - foundEncoding = true; - } else { - /* If no BOM, need to auto-detect based on first char; - * this works since it must be 7-bit ascii (wrt. unicode - * compatible encodings, only ones JSON can be transferred - * over) - */ - // UTF-32? - if (checkUTF32(quad)) { - foundEncoding = true; - } else if (checkUTF16(quad >>> 16)) { - foundEncoding = true; - } - } - } else if (ensureLoaded(2)) { - int i16 = ((_inputBuffer[_inputPtr] & 0xFF) << 8) - | (_inputBuffer[_inputPtr+1] & 0xFF); - if (checkUTF16(i16)) { - foundEncoding = true; - } - } - - JsonEncoding enc; - - /* Not found yet? As per specs, this means it must be UTF-8. */ - if (!foundEncoding) { - enc = JsonEncoding.UTF8; - } else { - switch (_bytesPerChar) { - case 1: enc = JsonEncoding.UTF8; - break; - case 2: enc = _bigEndian ? JsonEncoding.UTF16_BE : JsonEncoding.UTF16_LE; - break; - case 4: enc = _bigEndian ? JsonEncoding.UTF32_BE : JsonEncoding.UTF32_LE; - break; - default: throw new RuntimeException("Internal error"); // should never get here - } - } - _context.setEncoding(enc); - return enc; - } - - /** - * Helper method that may be called to see if given {@link DataInput} - * has BOM marker, and if so, to skip it. - * @throws IOException - * - * @since 2.8 - */ - public static int skipUTF8BOM(DataInput input) throws IOException - { - int b = input.readUnsignedByte(); - if (b != 0xEF) { - return b; - } - // since this is not legal byte in JSON otherwise, except - // that we do get BOM; if not, report error - b = input.readUnsignedByte(); - if (b != 0xBB) { - throw new IOException("Unexpected byte 0x"+Integer.toHexString(b) - +" following 0xEF; should get 0xBB as part of UTF-8 BOM"); - } - b = input.readUnsignedByte(); - if (b != 0xBF) { - throw new IOException("Unexpected byte 0x"+Integer.toHexString(b) - +" following 0xEF 0xBB; should get 0xBF as part of UTF-8 BOM"); - } - return input.readUnsignedByte(); - } - - /* - /********************************************************** - /* Constructing a Reader - /********************************************************** - */ - - @SuppressWarnings("resource") - public Reader constructReader() throws IOException - { - JsonEncoding enc = _context.getEncoding(); - switch (enc.bits()) { - case 8: // only in non-common case where we don't want to do direct mapping - case 16: - { - // First: do we have a Stream? If not, need to create one: - InputStream in = _in; - - if (in == null) { - in = new ByteArrayInputStream(_inputBuffer, _inputPtr, _inputEnd); - } else { - /* Also, if we have any read but unused input (usually true), - * need to merge that input in: - */ - if (_inputPtr < _inputEnd) { - in = new MergedStream(_context, in, _inputBuffer, _inputPtr, _inputEnd); - } - } - return new InputStreamReader(in, enc.getJavaName()); - } - case 32: - return new UTF32Reader(_context, _in, _inputBuffer, _inputPtr, _inputEnd, - _context.getEncoding().isBigEndian()); - } - throw new RuntimeException("Internal error"); // should never get here - } - - public JsonParser constructParser(int parserFeatures, ObjectCodec codec, - ByteQuadsCanonicalizer rootByteSymbols, CharsToNameCanonicalizer rootCharSymbols, - int factoryFeatures) throws IOException - { - JsonEncoding enc = detectEncoding(); - - if (enc == JsonEncoding.UTF8) { - /* and without canonicalization, byte-based approach is not performant; just use std UTF-8 reader - * (which is ok for larger input; not so hot for smaller; but this is not a common case) - */ - if (JsonFactory.Feature.CANONICALIZE_FIELD_NAMES.enabledIn(factoryFeatures)) { - ByteQuadsCanonicalizer can = rootByteSymbols.makeChild(factoryFeatures); - return new UTF8StreamJsonParser(_context, parserFeatures, _in, codec, can, - _inputBuffer, _inputPtr, _inputEnd, _bufferRecyclable); - } - } - return new ReaderBasedJsonParser(_context, parserFeatures, constructReader(), codec, - rootCharSymbols.makeChild(factoryFeatures)); - } - - /* - /********************************************************** - /* Encoding detection for data format auto-detection - /********************************************************** - */ - - /** - * Current implementation is not as thorough as other functionality - * ({@link autosaveworld.zlibs.com.fasterxml.jackson.core.json.ByteSourceJsonBootstrapper}); - * supports UTF-8, for example. But it should work, for now, and can - * be improved as necessary. - */ - public static MatchStrength hasJSONFormat(InputAccessor acc) throws IOException - { - // Ideally we should see "[" or "{"; but if not, we'll accept double-quote (String) - // in future could also consider accepting non-standard matches? - - if (!acc.hasMoreBytes()) { - return MatchStrength.INCONCLUSIVE; - } - byte b = acc.nextByte(); - // Very first thing, a UTF-8 BOM? - if (b == UTF8_BOM_1) { // yes, looks like UTF-8 BOM - if (!acc.hasMoreBytes()) { - return MatchStrength.INCONCLUSIVE; - } - if (acc.nextByte() != UTF8_BOM_2) { - return MatchStrength.NO_MATCH; - } - if (!acc.hasMoreBytes()) { - return MatchStrength.INCONCLUSIVE; - } - if (acc.nextByte() != UTF8_BOM_3) { - return MatchStrength.NO_MATCH; - } - if (!acc.hasMoreBytes()) { - return MatchStrength.INCONCLUSIVE; - } - b = acc.nextByte(); - } - // Then possible leading space - int ch = skipSpace(acc, b); - if (ch < 0) { - return MatchStrength.INCONCLUSIVE; - } - // First, let's see if it looks like a structured type: - if (ch == '{') { // JSON object? - // Ideally we need to find either double-quote or closing bracket - ch = skipSpace(acc); - if (ch < 0) { - return MatchStrength.INCONCLUSIVE; - } - if (ch == '"' || ch == '}') { - return MatchStrength.SOLID_MATCH; - } - // ... should we allow non-standard? Let's not yet... can add if need be - return MatchStrength.NO_MATCH; - } - MatchStrength strength; - - if (ch == '[') { - ch = skipSpace(acc); - if (ch < 0) { - return MatchStrength.INCONCLUSIVE; - } - // closing brackets is easy; but for now, let's also accept opening... - if (ch == ']' || ch == '[') { - return MatchStrength.SOLID_MATCH; - } - return MatchStrength.SOLID_MATCH; - } else { - // plain old value is not very convincing... - strength = MatchStrength.WEAK_MATCH; - } - - if (ch == '"') { // string value - return strength; - } - if (ch <= '9' && ch >= '0') { // number - return strength; - } - if (ch == '-') { // negative number - ch = skipSpace(acc); - if (ch < 0) { - return MatchStrength.INCONCLUSIVE; - } - return (ch <= '9' && ch >= '0') ? strength : MatchStrength.NO_MATCH; - } - // or one of literals - if (ch == 'n') { // null - return tryMatch(acc, "ull", strength); - } - if (ch == 't') { // true - return tryMatch(acc, "rue", strength); - } - if (ch == 'f') { // false - return tryMatch(acc, "alse", strength); - } - return MatchStrength.NO_MATCH; - } - - private static MatchStrength tryMatch(InputAccessor acc, String matchStr, MatchStrength fullMatchStrength) - throws IOException - { - for (int i = 0, len = matchStr.length(); i < len; ++i) { - if (!acc.hasMoreBytes()) { - return MatchStrength.INCONCLUSIVE; - } - if (acc.nextByte() != matchStr.charAt(i)) { - return MatchStrength.NO_MATCH; - } - } - return fullMatchStrength; - } - - private static int skipSpace(InputAccessor acc) throws IOException - { - if (!acc.hasMoreBytes()) { - return -1; - } - return skipSpace(acc, acc.nextByte()); - } - - private static int skipSpace(InputAccessor acc, byte b) throws IOException - { - while (true) { - int ch = (int) b & 0xFF; - if (!(ch == ' ' || ch == '\r' || ch == '\n' || ch == '\t')) { - return ch; - } - if (!acc.hasMoreBytes()) { - return -1; - } - b = acc.nextByte(); - } - } - - /* - /********************************************************** - /* Internal methods, parsing - /********************************************************** - */ - - /** - * @return True if a BOM was succesfully found, and encoding - * thereby recognized. - */ - private boolean handleBOM(int quad) throws IOException - { - /* Handling of (usually) optional BOM (required for - * multi-byte formats); first 32-bit charsets: - */ - switch (quad) { - case 0x0000FEFF: - _bigEndian = true; - _inputPtr += 4; - _bytesPerChar = 4; - return true; - case 0xFFFE0000: // UCS-4, LE? - _inputPtr += 4; - _bytesPerChar = 4; - _bigEndian = false; - return true; - case 0x0000FFFE: // UCS-4, in-order... - reportWeirdUCS4("2143"); // throws exception - break; // never gets here - case 0xFEFF0000: // UCS-4, in-order... - reportWeirdUCS4("3412"); // throws exception - break; // never gets here - default: - } - // Ok, if not, how about 16-bit encoding BOMs? - int msw = quad >>> 16; - if (msw == 0xFEFF) { // UTF-16, BE - _inputPtr += 2; - _bytesPerChar = 2; - _bigEndian = true; - return true; - } - if (msw == 0xFFFE) { // UTF-16, LE - _inputPtr += 2; - _bytesPerChar = 2; - _bigEndian = false; - return true; - } - // And if not, then UTF-8 BOM? - if ((quad >>> 8) == 0xEFBBBF) { // UTF-8 - _inputPtr += 3; - _bytesPerChar = 1; - _bigEndian = true; // doesn't really matter - return true; - } - return false; - } - - private boolean checkUTF32(int quad) throws IOException - { - /* Handling of (usually) optional BOM (required for - * multi-byte formats); first 32-bit charsets: - */ - if ((quad >> 8) == 0) { // 0x000000?? -> UTF32-BE - _bigEndian = true; - } else if ((quad & 0x00FFFFFF) == 0) { // 0x??000000 -> UTF32-LE - _bigEndian = false; - } else if ((quad & ~0x00FF0000) == 0) { // 0x00??0000 -> UTF32-in-order - reportWeirdUCS4("3412"); - } else if ((quad & ~0x0000FF00) == 0) { // 0x0000??00 -> UTF32-in-order - reportWeirdUCS4("2143"); - } else { - // Can not be valid UTF-32 encoded JSON... - return false; - } - // Not BOM (just regular content), nothing to skip past: - //_inputPtr += 4; - _bytesPerChar = 4; - return true; - } - - private boolean checkUTF16(int i16) - { - if ((i16 & 0xFF00) == 0) { // UTF-16BE - _bigEndian = true; - } else if ((i16 & 0x00FF) == 0) { // UTF-16LE - _bigEndian = false; - } else { // nope, not UTF-16 - return false; - } - // Not BOM (just regular content), nothing to skip past: - //_inputPtr += 2; - _bytesPerChar = 2; - return true; - } - - /* - /********************************************************** - /* Internal methods, problem reporting - /********************************************************** - */ - - private void reportWeirdUCS4(String type) throws IOException { - throw new CharConversionException("Unsupported UCS-4 endianness ("+type+") detected"); - } - - /* - /********************************************************** - /* Internal methods, raw input access - /********************************************************** - */ - - protected boolean ensureLoaded(int minimum) throws IOException { - /* Let's assume here buffer has enough room -- this will always - * be true for the limited used this method gets - */ - int gotten = (_inputEnd - _inputPtr); - while (gotten < minimum) { - int count; - - if (_in == null) { // block source - count = -1; - } else { - count = _in.read(_inputBuffer, _inputEnd, _inputBuffer.length - _inputEnd); - } - if (count < 1) { - return false; - } - _inputEnd += count; - gotten += count; - } - return true; - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/DupDetector.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/DupDetector.java deleted file mode 100644 index 01c776fa..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/DupDetector.java +++ /dev/null @@ -1,100 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.json; - -import java.util.HashSet; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonLocation; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; - -/** - * Helper class used if - * {@link autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser.Feature#STRICT_DUPLICATE_DETECTION} - * is enabled. - * Optimized to try to limit memory usage and processing overhead for smallest - * entries, but without adding trashing (immutable objects would achieve optimal - * memory usage but lead to significant number of discarded temp objects for - * scopes with large number of entries). Another consideration is trying to limit - * actual number of compiled classes as it contributes significantly to overall - * jar size (due to linkage etc). - * - * @since 2.3 - */ -public class DupDetector -{ - /** - * We need to store a back-reference here to parser/generator. - */ - protected final Object _source; - - protected String _firstName; - - protected String _secondName; - - /** - * Lazily constructed set of names already seen within this context. - */ - protected HashSet _seen; - - private DupDetector(Object src) { - _source = src; - } - - public static DupDetector rootDetector(JsonParser p) { - return new DupDetector(p); - } - - public static DupDetector rootDetector(JsonGenerator g) { - return new DupDetector(g); - } - - public DupDetector child() { - return new DupDetector(_source); - } - - public void reset() { - _firstName = null; - _secondName = null; - _seen = null; - } - - public JsonLocation findLocation() { - // ugly but: - if (_source instanceof JsonParser) { - return ((JsonParser)_source).getCurrentLocation(); - } - // do generators have a way to provide Location? Apparently not... - return null; - } - - /** - * @since 2.7 - */ - public Object getSource() { - return _source; - } - - public boolean isDup(String name) throws JsonParseException - { - if (_firstName == null) { - _firstName = name; - return false; - } - if (name.equals(_firstName)) { - return true; - } - if (_secondName == null) { - _secondName = name; - return false; - } - if (name.equals(_secondName)) { - return true; - } - if (_seen == null) { - _seen = new HashSet(16); // 16 is default, seems reasonable - _seen.add(_firstName); - _seen.add(_secondName); - } - return !_seen.add(name); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/JsonGeneratorImpl.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/JsonGeneratorImpl.java deleted file mode 100644 index ffe4c3d6..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/JsonGeneratorImpl.java +++ /dev/null @@ -1,250 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.json; - -import java.io.IOException; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.ObjectCodec; -import autosaveworld.zlibs.com.fasterxml.jackson.core.SerializableString; -import autosaveworld.zlibs.com.fasterxml.jackson.core.Version; -import autosaveworld.zlibs.com.fasterxml.jackson.core.base.GeneratorBase; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.CharTypes; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.CharacterEscapes; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.IOContext; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.DefaultPrettyPrinter; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.VersionUtil; - -/** - * Intermediate base class shared by JSON-backed generators - * like {@link UTF8JsonGenerator} and {@link WriterBasedJsonGenerator}. - * - * @since 2.1 - */ -public abstract class JsonGeneratorImpl extends GeneratorBase -{ - /* - /********************************************************** - /* Constants - /********************************************************** - */ - - /** - * This is the default set of escape codes, over 7-bit ASCII range - * (first 128 character codes), used for single-byte UTF-8 characters. - */ - protected final static int[] sOutputEscapes = CharTypes.get7BitOutputEscapes(); - - /* - /********************************************************** - /* Configuration, basic I/O - /********************************************************** - */ - - final protected IOContext _ioContext; - - /* - /********************************************************** - /* Configuration, output escaping - /********************************************************** - */ - - /** - * Currently active set of output escape code definitions (whether - * and how to escape or not) for 7-bit ASCII range (first 128 - * character codes). Defined separately to make potentially - * customizable - */ - protected int[] _outputEscapes = sOutputEscapes; - - /** - * Value between 128 (0x80) and 65535 (0xFFFF) that indicates highest - * Unicode code point that will not need escaping; or 0 to indicate - * that all characters can be represented without escaping. - * Typically used to force escaping of some portion of character set; - * for example to always escape non-ASCII characters (if value was 127). - *

- * NOTE: not all sub-classes make use of this setting. - */ - protected int _maximumNonEscapedChar; - - /** - * Definition of custom character escapes to use for generators created - * by this factory, if any. If null, standard data format specific - * escapes are used. - */ - protected CharacterEscapes _characterEscapes; - - /* - /********************************************************** - /* Configuration, other - /********************************************************** - */ - - /** - * Separator to use, if any, between root-level values. - * - * @since 2.1 - */ - protected SerializableString _rootValueSeparator - = DefaultPrettyPrinter.DEFAULT_ROOT_VALUE_SEPARATOR; - - /** - * Flag that is set if quoting is not to be added around - * JSON Object property names. - * - * @since 2.7 - */ - protected boolean _cfgUnqNames; - - /* - /********************************************************** - /* Life-cycle - /********************************************************** - */ - - public JsonGeneratorImpl(IOContext ctxt, int features, ObjectCodec codec) - { - super(features, codec); - _ioContext = ctxt; - if (Feature.ESCAPE_NON_ASCII.enabledIn(features)) { - // inlined `setHighestNonEscapedChar()` - _maximumNonEscapedChar = 127; - } - _cfgUnqNames = !Feature.QUOTE_FIELD_NAMES.enabledIn(features); - } - - /* - /********************************************************** - /* Versioned - /********************************************************** - */ - - @Override - public Version version() { - return VersionUtil.versionFor(getClass()); - } - - /* - /********************************************************** - /* Overridden configuration methods - /********************************************************** - */ - - @Override - public JsonGenerator enable(Feature f) { - super.enable(f); - if (f == Feature.QUOTE_FIELD_NAMES) { - _cfgUnqNames = false; - } - return this; - } - - @Override - public JsonGenerator disable(Feature f) { - super.disable(f); - if (f == Feature.QUOTE_FIELD_NAMES) { - _cfgUnqNames = true; - } - return this; - } - - @Override - protected void _checkStdFeatureChanges(int newFeatureFlags, int changedFeatures) { - super._checkStdFeatureChanges(newFeatureFlags, changedFeatures); - _cfgUnqNames = !Feature.QUOTE_FIELD_NAMES.enabledIn(newFeatureFlags); - } - - @Override - public JsonGenerator setHighestNonEscapedChar(int charCode) { - _maximumNonEscapedChar = (charCode < 0) ? 0 : charCode; - return this; - } - - @Override - public int getHighestEscapedChar() { - return _maximumNonEscapedChar; - } - - @Override - public JsonGenerator setCharacterEscapes(CharacterEscapes esc) - { - _characterEscapes = esc; - if (esc == null) { // revert to standard escapes - _outputEscapes = sOutputEscapes; - } else { - _outputEscapes = esc.getEscapeCodesForAscii(); - } - return this; - } - - /** - * Method for accessing custom escapes factory uses for {@link JsonGenerator}s - * it creates. - */ - @Override - public CharacterEscapes getCharacterEscapes() { - return _characterEscapes; - } - - @Override - public JsonGenerator setRootValueSeparator(SerializableString sep) { - _rootValueSeparator = sep; - return this; - } - - /* - /********************************************************** - /* Partial API - /********************************************************** - */ - - // // Overrides just to make things final, to possibly help with inlining - - @Override - public final void writeStringField(String fieldName, String value) throws IOException - { - writeFieldName(fieldName); - writeString(value); - } - - /* - /********************************************************** - /* Shared helper methods - /********************************************************** - */ - - protected void _verifyPrettyValueWrite(String typeMsg, int status) throws IOException - { - // If we have a pretty printer, it knows what to do: - switch (status) { - case JsonWriteContext.STATUS_OK_AFTER_COMMA: // array - _cfgPrettyPrinter.writeArrayValueSeparator(this); - break; - case JsonWriteContext.STATUS_OK_AFTER_COLON: - _cfgPrettyPrinter.writeObjectFieldValueSeparator(this); - break; - case JsonWriteContext.STATUS_OK_AFTER_SPACE: - _cfgPrettyPrinter.writeRootValueSeparator(this); - break; - case JsonWriteContext.STATUS_OK_AS_IS: - // First entry, but of which context? - if (_writeContext.inArray()) { - _cfgPrettyPrinter.beforeArrayValues(this); - } else if (_writeContext.inObject()) { - _cfgPrettyPrinter.beforeObjectEntries(this); - } - break; - case JsonWriteContext.STATUS_EXPECT_NAME: - _reportCantWriteValueExpectName(typeMsg); - break; - default: - _throwInternal(); - break; - } - } - - protected void _reportCantWriteValueExpectName(String typeMsg) throws IOException - { - _reportError(String.format("Can not %s, expecting field name (context: %s)", - typeMsg, _writeContext.typeDesc())); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/JsonReadContext.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/JsonReadContext.java deleted file mode 100644 index 064d3aa8..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/JsonReadContext.java +++ /dev/null @@ -1,251 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.json; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonLocation; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonProcessingException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonStreamContext; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.CharTypes; - -/** - * Extension of {@link JsonStreamContext}, which implements - * core methods needed, and also exposes - * more complete API to parser implementation classes. - */ -public final class JsonReadContext extends JsonStreamContext -{ - // // // Configuration - - /** - * Parent context for this context; null for root context. - */ - protected final JsonReadContext _parent; - - // // // Optional duplicate detection - - protected DupDetector _dups; - - /* - /********************************************************** - /* Simple instance reuse slots; speeds up things - /* a bit (10-15%) for docs with lots of small - /* arrays/objects (for which allocation was - /* visible in profile stack frames) - /********************************************************** - */ - - protected JsonReadContext _child; - - /* - /********************************************************** - /* Location/state information (minus source reference) - /********************************************************** - */ - - protected String _currentName; - - /** - * @since 2.5 - */ - protected Object _currentValue; - - protected int _lineNr; - protected int _columnNr; - - /* - /********************************************************** - /* Instance construction, config, reuse - /********************************************************** - */ - - public JsonReadContext(JsonReadContext parent, DupDetector dups, int type, int lineNr, int colNr) { - super(); - _parent = parent; - _dups = dups; - _type = type; - _lineNr = lineNr; - _columnNr = colNr; - _index = -1; - } - - protected void reset(int type, int lineNr, int colNr) { - _type = type; - _index = -1; - _lineNr = lineNr; - _columnNr = colNr; - _currentName = null; - _currentValue = null; - if (_dups != null) { - _dups.reset(); - } - } - - /* - public void trackDups(JsonParser jp) { - _dups = DupDetector.rootDetector(jp); - } - */ - - public JsonReadContext withDupDetector(DupDetector dups) { - _dups = dups; - return this; - } - - @Override - public Object getCurrentValue() { - return _currentValue; - } - - @Override - public void setCurrentValue(Object v) { - _currentValue = v; - } - - /* - /********************************************************** - /* Factory methods - /********************************************************** - */ - - public static JsonReadContext createRootContext(int lineNr, int colNr, DupDetector dups) { - return new JsonReadContext(null, dups, TYPE_ROOT, lineNr, colNr); - } - - public static JsonReadContext createRootContext(DupDetector dups) { - return new JsonReadContext(null, dups, TYPE_ROOT, 1, 0); - } - - public JsonReadContext createChildArrayContext(int lineNr, int colNr) { - JsonReadContext ctxt = _child; - if (ctxt == null) { - _child = ctxt = new JsonReadContext(this, - (_dups == null) ? null : _dups.child(), TYPE_ARRAY, lineNr, colNr); - } else { - ctxt.reset(TYPE_ARRAY, lineNr, colNr); - } - return ctxt; - } - - public JsonReadContext createChildObjectContext(int lineNr, int colNr) { - JsonReadContext ctxt = _child; - if (ctxt == null) { - _child = ctxt = new JsonReadContext(this, - (_dups == null) ? null : _dups.child(), TYPE_OBJECT, lineNr, colNr); - return ctxt; - } - ctxt.reset(TYPE_OBJECT, lineNr, colNr); - return ctxt; - } - - /* - /********************************************************** - /* Abstract method implementation - /********************************************************** - */ - - @Override public String getCurrentName() { return _currentName; } - @Override public JsonReadContext getParent() { return _parent; } - - /** - * Method that can be used to both clear the accumulated references - * (specifically value set with {@link #setCurrentValue(Object)}) - * that should not be retained, and returns parent (as would - * {@link #getParent()} do). Typically called when closing the active - * context when encountering {@link JsonToken#END_ARRAY} or - * {@link JsonToken#END_OBJECT}. - * - * @since 2.7 - */ - public JsonReadContext clearAndGetParent() { - _currentValue = null; - // could also clear the current name, but seems cheap enough to leave? - return _parent; - } - - /* - /********************************************************** - /* Extended API - /********************************************************** - */ - - /** - * @return Location pointing to the point where the context - * start marker was found - */ - public JsonLocation getStartLocation(Object srcRef) { - // We don't keep track of offsets at this level (only reader does) - long totalChars = -1L; - return new JsonLocation(srcRef, totalChars, _lineNr, _columnNr); - } - - public DupDetector getDupDetector() { - return _dups; - } - - /* - /********************************************************** - /* State changes - /********************************************************** - */ - - public boolean expectComma() { - /* Assumption here is that we will be getting a value (at least - * before calling this method again), and - * so will auto-increment index to avoid having to do another call - */ - int ix = ++_index; // starts from -1 - return (_type != TYPE_ROOT && ix > 0); - } - - public void setCurrentName(String name) throws JsonProcessingException { - _currentName = name; - if (_dups != null) { _checkDup(_dups, name); } - } - - private void _checkDup(DupDetector dd, String name) throws JsonProcessingException { - if (dd.isDup(name)) { - Object src = dd.getSource(); - throw new JsonParseException(((src instanceof JsonParser) ? ((JsonParser) src) : null), - "Duplicate field '"+name+"'"); - } - } - - /* - /********************************************************** - /* Overridden standard methods - /********************************************************** - */ - - /** - * Overridden to provide developer readable "JsonPath" representation - * of the context. - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(64); - switch (_type) { - case TYPE_ROOT: - sb.append("/"); - break; - case TYPE_ARRAY: - sb.append('['); - sb.append(getCurrentIndex()); - sb.append(']'); - break; - case TYPE_OBJECT: - default: - sb.append('{'); - if (_currentName != null) { - sb.append('"'); - CharTypes.appendQuoted(sb, _currentName); - sb.append('"'); - } else { - sb.append('?'); - } - sb.append('}'); - break; - } - return sb.toString(); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/JsonWriteContext.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/JsonWriteContext.java deleted file mode 100644 index 5633c29f..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/JsonWriteContext.java +++ /dev/null @@ -1,245 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.json; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonProcessingException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonStreamContext; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * Extension of {@link JsonStreamContext}, which implements - * core methods needed, and also exposes - * more complete API to generator implementation classes. - */ -public class JsonWriteContext extends JsonStreamContext -{ - // // // Return values for writeValue() - - public final static int STATUS_OK_AS_IS = 0; - public final static int STATUS_OK_AFTER_COMMA = 1; - public final static int STATUS_OK_AFTER_COLON = 2; - public final static int STATUS_OK_AFTER_SPACE = 3; // in root context - public final static int STATUS_EXPECT_VALUE = 4; - public final static int STATUS_EXPECT_NAME = 5; - - /** - * Parent context for this context; null for root context. - */ - protected final JsonWriteContext _parent; - - // // // Optional duplicate detection - - protected DupDetector _dups; - - /* - /********************************************************** - /* Simple instance reuse slots; speed up things - /* a bit (10-15%) for docs with lots of small - /* arrays/objects - /********************************************************** - */ - - protected JsonWriteContext _child; - - /* - /********************************************************** - /* Location/state information (minus source reference) - /********************************************************** - */ - - /** - * Name of the field of which value is to be written; only - * used for OBJECT contexts - */ - protected String _currentName; - - /** - * @since 2.5 - */ - protected Object _currentValue; - - /** - * Marker used to indicate that we just wrote a name, and - * now expect a value to write - */ - protected boolean _gotName; - - /* - /********************************************************** - /* Life-cycle - /********************************************************** - */ - - protected JsonWriteContext(int type, JsonWriteContext parent, DupDetector dups) { - super(); - _type = type; - _parent = parent; - _dups = dups; - _index = -1; - } - - protected JsonWriteContext reset(int type) { - _type = type; - _index = -1; - _currentName = null; - _gotName = false; - _currentValue = null; - if (_dups != null) { _dups.reset(); } - return this; - } - - public JsonWriteContext withDupDetector(DupDetector dups) { - _dups = dups; - return this; - } - - @Override - public Object getCurrentValue() { - return _currentValue; - } - - @Override - public void setCurrentValue(Object v) { - _currentValue = v; - } - - /* - /********************************************************** - /* Factory methods - /********************************************************** - */ - - /** - * @deprecated Since 2.3; use method that takes argument - */ - @Deprecated - public static JsonWriteContext createRootContext() { return createRootContext(null); } - - public static JsonWriteContext createRootContext(DupDetector dd) { - return new JsonWriteContext(TYPE_ROOT, null, dd); - } - - public JsonWriteContext createChildArrayContext() { - JsonWriteContext ctxt = _child; - if (ctxt == null) { - _child = ctxt = new JsonWriteContext(TYPE_ARRAY, this, (_dups == null) ? null : _dups.child()); - return ctxt; - } - return ctxt.reset(TYPE_ARRAY); - } - - public JsonWriteContext createChildObjectContext() { - JsonWriteContext ctxt = _child; - if (ctxt == null) { - _child = ctxt = new JsonWriteContext(TYPE_OBJECT, this, (_dups == null) ? null : _dups.child()); - return ctxt; - } - return ctxt.reset(TYPE_OBJECT); - } - - @Override public final JsonWriteContext getParent() { return _parent; } - @Override public final String getCurrentName() { return _currentName; } - - /** - * Method that can be used to both clear the accumulated references - * (specifically value set with {@link #setCurrentValue(Object)}) - * that should not be retained, and returns parent (as would - * {@link #getParent()} do). Typically called when closing the active - * context when encountering {@link JsonToken#END_ARRAY} or - * {@link JsonToken#END_OBJECT}. - * - * @since 2.7 - */ - public JsonWriteContext clearAndGetParent() { - _currentValue = null; - // could also clear the current name, but seems cheap enough to leave? - return _parent; - } - - public DupDetector getDupDetector() { - return _dups; - } - - /** - * Method that writer is to call before it writes a field name. - * - * @return Index of the field entry (0-based) - */ - public int writeFieldName(String name) throws JsonProcessingException { - if ((_type != TYPE_OBJECT) || _gotName) { - return STATUS_EXPECT_VALUE; - } - _gotName = true; - _currentName = name; - if (_dups != null) { _checkDup(_dups, name); } - return (_index < 0) ? STATUS_OK_AS_IS : STATUS_OK_AFTER_COMMA; - } - - private final void _checkDup(DupDetector dd, String name) throws JsonProcessingException { - if (dd.isDup(name)) { - Object src = dd.getSource(); - throw new JsonGenerationException("Duplicate field '"+name+"'", - ((src instanceof JsonGenerator) ? ((JsonGenerator) src) : null)); - } - } - - public int writeValue() { - // Most likely, object: - if (_type == TYPE_OBJECT) { - if (!_gotName) { - return STATUS_EXPECT_NAME; - } - _gotName = false; - ++_index; - return STATUS_OK_AFTER_COLON; - } - - // Ok, array? - if (_type == TYPE_ARRAY) { - int ix = _index; - ++_index; - return (ix < 0) ? STATUS_OK_AS_IS : STATUS_OK_AFTER_COMMA; - } - - // Nope, root context - // No commas within root context, but need space - ++_index; - return (_index == 0) ? STATUS_OK_AS_IS : STATUS_OK_AFTER_SPACE; - } - - // // // Internally used abstract methods - - protected void appendDesc(StringBuilder sb) { - if (_type == TYPE_OBJECT) { - sb.append('{'); - if (_currentName != null) { - sb.append('"'); - // !!! TODO: Name chars should be escaped? - sb.append(_currentName); - sb.append('"'); - } else { - sb.append('?'); - } - sb.append('}'); - } else if (_type == TYPE_ARRAY) { - sb.append('['); - sb.append(getCurrentIndex()); - sb.append(']'); - } else { - // nah, ROOT: - sb.append("/"); - } - } - - // // // Overridden standard methods - - /** - * Overridden to provide developer writeable "JsonPath" representation - * of the context. - */ - @Override public String toString() { - StringBuilder sb = new StringBuilder(64); - appendDesc(sb); - return sb.toString(); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/ReaderBasedJsonParser.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/ReaderBasedJsonParser.java deleted file mode 100644 index c722acc9..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/ReaderBasedJsonParser.java +++ /dev/null @@ -1,2869 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.json; - -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_FALSE; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_FIELD_NAME; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_NUMBER_FLOAT; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_NUMBER_INT; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_STRING; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_TRUE; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.Base64Variant; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonLocation; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; -import autosaveworld.zlibs.com.fasterxml.jackson.core.ObjectCodec; -import autosaveworld.zlibs.com.fasterxml.jackson.core.SerializableString; -import autosaveworld.zlibs.com.fasterxml.jackson.core.base.ParserBase; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.CharTypes; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.IOContext; -import autosaveworld.zlibs.com.fasterxml.jackson.core.sym.CharsToNameCanonicalizer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.ByteArrayBuilder; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.TextBuffer; - -/** - * This is a concrete implementation of {@link JsonParser}, which is - * based on a {@link java.io.Reader} to handle low-level character - * conversion tasks. - */ -public class ReaderBasedJsonParser // final in 2.3, earlier - extends ParserBase -{ - protected final static int FEAT_MASK_TRAILING_COMMA = Feature.ALLOW_TRAILING_COMMA.getMask(); - - // Latin1 encoding is not supported, but we do use 8-bit subset for - // pre-processing task, to simplify first pass, keep it fast. - protected final static int[] _icLatin1 = CharTypes.getInputCodeLatin1(); - - /* - /********************************************************** - /* Input configuration - /********************************************************** - */ - - /** - * Reader that can be used for reading more content, if one - * buffer from input source, but in some cases pre-loaded buffer - * is handed to the parser. - */ - protected Reader _reader; - - /** - * Current buffer from which data is read; generally data is read into - * buffer from input source. - */ - protected char[] _inputBuffer; - - /** - * Flag that indicates whether the input buffer is recycable (and - * needs to be returned to recycler once we are done) or not. - *

- * If it is not, it also means that parser can NOT modify underlying - * buffer. - */ - protected boolean _bufferRecyclable; - - /* - /********************************************************** - /* Configuration - /********************************************************** - */ - - protected ObjectCodec _objectCodec; - - final protected CharsToNameCanonicalizer _symbols; - - final protected int _hashSeed; - - /* - /********************************************************** - /* Parsing state - /********************************************************** - */ - - /** - * Flag that indicates that the current token has not yet - * been fully processed, and needs to be finished for - * some access (or skipped to obtain the next token) - */ - protected boolean _tokenIncomplete; - - /** - * Value of {@link #_inputPtr} at the time when the first character of - * name token was read. Used for calculating token location when requested; - * combined with {@link #_currInputProcessed}, may be updated appropriately - * as needed. - * - * @since 2.7 - */ - protected long _nameStartOffset; - - /** - * @since 2.7 - */ - protected int _nameStartRow; - - /** - * @since 2.7 - */ - protected int _nameStartCol; - - /* - /********************************************************** - /* Life-cycle - /********************************************************** - */ - - /** - * Method called when caller wants to provide input buffer directly, - * and it may or may not be recyclable use standard recycle context. - * - * @since 2.4 - */ - public ReaderBasedJsonParser(IOContext ctxt, int features, Reader r, - ObjectCodec codec, CharsToNameCanonicalizer st, - char[] inputBuffer, int start, int end, - boolean bufferRecyclable) - { - super(ctxt, features); - _reader = r; - _inputBuffer = inputBuffer; - _inputPtr = start; - _inputEnd = end; - _objectCodec = codec; - _symbols = st; - _hashSeed = st.hashSeed(); - _bufferRecyclable = bufferRecyclable; - } - - /** - * Method called when input comes as a {@link java.io.Reader}, and buffer allocation - * can be done using default mechanism. - */ - public ReaderBasedJsonParser(IOContext ctxt, int features, Reader r, - ObjectCodec codec, CharsToNameCanonicalizer st) - { - super(ctxt, features); - _reader = r; - _inputBuffer = ctxt.allocTokenBuffer(); - _inputPtr = 0; - _inputEnd = 0; - _objectCodec = codec; - _symbols = st; - _hashSeed = st.hashSeed(); - _bufferRecyclable = true; - } - - /* - /********************************************************** - /* Base method defs, overrides - /********************************************************** - */ - - @Override public ObjectCodec getCodec() { return _objectCodec; } - @Override public void setCodec(ObjectCodec c) { _objectCodec = c; } - - @Override - public int releaseBuffered(Writer w) throws IOException { - int count = _inputEnd - _inputPtr; - if (count < 1) { return 0; } - // let's just advance ptr to end - int origPtr = _inputPtr; - w.write(_inputBuffer, origPtr, count); - return count; - } - - @Override public Object getInputSource() { return _reader; } - - @Deprecated // since 2.8 - protected char getNextChar(String eofMsg) throws IOException { - return getNextChar(eofMsg, null); - } - - protected char getNextChar(String eofMsg, JsonToken forToken) throws IOException { - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { - _reportInvalidEOF(eofMsg, forToken); - } - } - return _inputBuffer[_inputPtr++]; - } - - @Override - protected void _closeInput() throws IOException { - /* 25-Nov-2008, tatus: As per [JACKSON-16] we are not to call close() - * on the underlying Reader, unless we "own" it, or auto-closing - * feature is enabled. - * One downside is that when using our optimized - * Reader (granted, we only do that for UTF-32...) this - * means that buffer recycling won't work correctly. - */ - if (_reader != null) { - if (_ioContext.isResourceManaged() || isEnabled(Feature.AUTO_CLOSE_SOURCE)) { - _reader.close(); - } - _reader = null; - } - } - - /** - * Method called to release internal buffers owned by the base - * reader. This may be called along with {@link #_closeInput} (for - * example, when explicitly closing this reader instance), or - * separately (if need be). - */ - @Override - protected void _releaseBuffers() throws IOException { - super._releaseBuffers(); - // merge new symbols, if any - _symbols.release(); - // and release buffers, if they are recyclable ones - if (_bufferRecyclable) { - char[] buf = _inputBuffer; - if (buf != null) { - _inputBuffer = null; - _ioContext.releaseTokenBuffer(buf); - } - } - } - - /* - /********************************************************** - /* Low-level access, supporting - /********************************************************** - */ - - protected void _loadMoreGuaranteed() throws IOException { - if (!_loadMore()) { _reportInvalidEOF(); } - } - - protected boolean _loadMore() throws IOException - { - final int bufSize = _inputEnd; - - _currInputProcessed += bufSize; - _currInputRowStart -= bufSize; - - // 26-Nov-2015, tatu: Since name-offset requires it too, must offset - // this increase to avoid "moving" name-offset, resulting most likely - // in negative value, which is fine as combine value remains unchanged. - _nameStartOffset -= bufSize; - - if (_reader != null) { - int count = _reader.read(_inputBuffer, 0, _inputBuffer.length); - if (count > 0) { - _inputPtr = 0; - _inputEnd = count; - return true; - } - // End of input - _closeInput(); - // Should never return 0, so let's fail - if (count == 0) { - throw new IOException("Reader returned 0 characters when trying to read "+_inputEnd); - } - } - return false; - } - - /* - /********************************************************** - /* Public API, data access - /********************************************************** - */ - - /** - * Method for accessing textual representation of the current event; - * if no current event (before first call to {@link #nextToken}, or - * after encountering end-of-input), returns null. - * Method can be called for any event. - */ - @Override - public final String getText() throws IOException - { - JsonToken t = _currToken; - if (t == JsonToken.VALUE_STRING) { - if (_tokenIncomplete) { - _tokenIncomplete = false; - _finishString(); // only strings can be incomplete - } - return _textBuffer.contentsAsString(); - } - return _getText2(t); - } - - @Override // since 2.8 - public int getText(Writer writer) throws IOException - { - JsonToken t = _currToken; - if (t == JsonToken.VALUE_STRING) { - if (_tokenIncomplete) { - _tokenIncomplete = false; - _finishString(); // only strings can be incomplete - } - return _textBuffer.contentsToWriter(writer); - } - if (t == JsonToken.FIELD_NAME) { - String n = _parsingContext.getCurrentName(); - writer.write(n); - return n.length(); - } - if (t != null) { - if (t.isNumeric()) { - return _textBuffer.contentsToWriter(writer); - } - char[] ch = t.asCharArray(); - writer.write(ch); - return ch.length; - } - return 0; - } - - // // // Let's override default impls for improved performance - - // @since 2.1 - @Override - public final String getValueAsString() throws IOException - { - if (_currToken == JsonToken.VALUE_STRING) { - if (_tokenIncomplete) { - _tokenIncomplete = false; - _finishString(); // only strings can be incomplete - } - return _textBuffer.contentsAsString(); - } - if (_currToken == JsonToken.FIELD_NAME) { - return getCurrentName(); - } - return super.getValueAsString(null); - } - - // @since 2.1 - @Override - public final String getValueAsString(String defValue) throws IOException { - if (_currToken == JsonToken.VALUE_STRING) { - if (_tokenIncomplete) { - _tokenIncomplete = false; - _finishString(); // only strings can be incomplete - } - return _textBuffer.contentsAsString(); - } - if (_currToken == JsonToken.FIELD_NAME) { - return getCurrentName(); - } - return super.getValueAsString(defValue); - } - - protected final String _getText2(JsonToken t) { - if (t == null) { - return null; - } - switch (t.id()) { - case ID_FIELD_NAME: - return _parsingContext.getCurrentName(); - - case ID_STRING: - // fall through - case ID_NUMBER_INT: - case ID_NUMBER_FLOAT: - return _textBuffer.contentsAsString(); - default: - return t.asString(); - } - } - - @Override - public final char[] getTextCharacters() throws IOException - { - if (_currToken != null) { // null only before/after document - switch (_currToken.id()) { - case ID_FIELD_NAME: - if (!_nameCopied) { - String name = _parsingContext.getCurrentName(); - int nameLen = name.length(); - if (_nameCopyBuffer == null) { - _nameCopyBuffer = _ioContext.allocNameCopyBuffer(nameLen); - } else if (_nameCopyBuffer.length < nameLen) { - _nameCopyBuffer = new char[nameLen]; - } - name.getChars(0, nameLen, _nameCopyBuffer, 0); - _nameCopied = true; - } - return _nameCopyBuffer; - case ID_STRING: - if (_tokenIncomplete) { - _tokenIncomplete = false; - _finishString(); // only strings can be incomplete - } - // fall through - case ID_NUMBER_INT: - case ID_NUMBER_FLOAT: - return _textBuffer.getTextBuffer(); - default: - return _currToken.asCharArray(); - } - } - return null; - } - - @Override - public final int getTextLength() throws IOException - { - if (_currToken != null) { // null only before/after document - switch (_currToken.id()) { - case ID_FIELD_NAME: - return _parsingContext.getCurrentName().length(); - case ID_STRING: - if (_tokenIncomplete) { - _tokenIncomplete = false; - _finishString(); // only strings can be incomplete - } - // fall through - case ID_NUMBER_INT: - case ID_NUMBER_FLOAT: - return _textBuffer.size(); - default: - return _currToken.asCharArray().length; - } - } - return 0; - } - - @Override - public final int getTextOffset() throws IOException - { - // Most have offset of 0, only some may have other values: - if (_currToken != null) { - switch (_currToken.id()) { - case ID_FIELD_NAME: - return 0; - case ID_STRING: - if (_tokenIncomplete) { - _tokenIncomplete = false; - _finishString(); // only strings can be incomplete - } - // fall through - case ID_NUMBER_INT: - case ID_NUMBER_FLOAT: - return _textBuffer.getTextOffset(); - default: - } - } - return 0; - } - - @Override - public byte[] getBinaryValue(Base64Variant b64variant) throws IOException - { - if ((_currToken == JsonToken.VALUE_EMBEDDED_OBJECT) && (_binaryValue != null)) { - return _binaryValue; - } - if (_currToken != JsonToken.VALUE_STRING) { - _reportError("Current token ("+_currToken+") not VALUE_STRING or VALUE_EMBEDDED_OBJECT, can not access as binary"); - } - // To ensure that we won't see inconsistent data, better clear up state - if (_tokenIncomplete) { - try { - _binaryValue = _decodeBase64(b64variant); - } catch (IllegalArgumentException iae) { - throw _constructError("Failed to decode VALUE_STRING as base64 ("+b64variant+"): "+iae.getMessage()); - } - /* let's clear incomplete only now; allows for accessing other - * textual content in error cases - */ - _tokenIncomplete = false; - } else { // may actually require conversion... - if (_binaryValue == null) { - ByteArrayBuilder builder = _getByteArrayBuilder(); - _decodeBase64(getText(), builder, b64variant); - _binaryValue = builder.toByteArray(); - } - } - return _binaryValue; - } - - @Override - public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws IOException - { - // if we have already read the token, just use whatever we may have - if (!_tokenIncomplete || _currToken != JsonToken.VALUE_STRING) { - byte[] b = getBinaryValue(b64variant); - out.write(b); - return b.length; - } - // otherwise do "real" incremental parsing... - byte[] buf = _ioContext.allocBase64Buffer(); - try { - return _readBinary(b64variant, out, buf); - } finally { - _ioContext.releaseBase64Buffer(buf); - } - } - - protected int _readBinary(Base64Variant b64variant, OutputStream out, byte[] buffer) throws IOException - { - int outputPtr = 0; - final int outputEnd = buffer.length - 3; - int outputCount = 0; - - while (true) { - // first, we'll skip preceding white space, if any - char ch; - do { - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - ch = _inputBuffer[_inputPtr++]; - } while (ch <= INT_SPACE); - int bits = b64variant.decodeBase64Char(ch); - if (bits < 0) { // reached the end, fair and square? - if (ch == '"') { - break; - } - bits = _decodeBase64Escape(b64variant, ch, 0); - if (bits < 0) { // white space to skip - continue; - } - } - - // enough room? If not, flush - if (outputPtr > outputEnd) { - outputCount += outputPtr; - out.write(buffer, 0, outputPtr); - outputPtr = 0; - } - - int decodedData = bits; - - // then second base64 char; can't get padding yet, nor ws - - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - ch = _inputBuffer[_inputPtr++]; - bits = b64variant.decodeBase64Char(ch); - if (bits < 0) { - bits = _decodeBase64Escape(b64variant, ch, 1); - } - decodedData = (decodedData << 6) | bits; - - // third base64 char; can be padding, but not ws - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - ch = _inputBuffer[_inputPtr++]; - bits = b64variant.decodeBase64Char(ch); - - // First branch: can get padding (-> 1 byte) - if (bits < 0) { - if (bits != Base64Variant.BASE64_VALUE_PADDING) { - // as per [JACKSON-631], could also just be 'missing' padding - if (ch == '"' && !b64variant.usesPadding()) { - decodedData >>= 4; - buffer[outputPtr++] = (byte) decodedData; - break; - } - bits = _decodeBase64Escape(b64variant, ch, 2); - } - if (bits == Base64Variant.BASE64_VALUE_PADDING) { - // Ok, must get padding - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - ch = _inputBuffer[_inputPtr++]; - if (!b64variant.usesPaddingChar(ch)) { - throw reportInvalidBase64Char(b64variant, ch, 3, "expected padding character '"+b64variant.getPaddingChar()+"'"); - } - // Got 12 bits, only need 8, need to shift - decodedData >>= 4; - buffer[outputPtr++] = (byte) decodedData; - continue; - } - } - // Nope, 2 or 3 bytes - decodedData = (decodedData << 6) | bits; - // fourth and last base64 char; can be padding, but not ws - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - ch = _inputBuffer[_inputPtr++]; - bits = b64variant.decodeBase64Char(ch); - if (bits < 0) { - if (bits != Base64Variant.BASE64_VALUE_PADDING) { - // as per [JACKSON-631], could also just be 'missing' padding - if (ch == '"' && !b64variant.usesPadding()) { - decodedData >>= 2; - buffer[outputPtr++] = (byte) (decodedData >> 8); - buffer[outputPtr++] = (byte) decodedData; - break; - } - bits = _decodeBase64Escape(b64variant, ch, 3); - } - if (bits == Base64Variant.BASE64_VALUE_PADDING) { - /* With padding we only get 2 bytes; but we have - * to shift it a bit so it is identical to triplet - * case with partial output. - * 3 chars gives 3x6 == 18 bits, of which 2 are - * dummies, need to discard: - */ - decodedData >>= 2; - buffer[outputPtr++] = (byte) (decodedData >> 8); - buffer[outputPtr++] = (byte) decodedData; - continue; - } - } - // otherwise, our triplet is now complete - decodedData = (decodedData << 6) | bits; - buffer[outputPtr++] = (byte) (decodedData >> 16); - buffer[outputPtr++] = (byte) (decodedData >> 8); - buffer[outputPtr++] = (byte) decodedData; - } - _tokenIncomplete = false; - if (outputPtr > 0) { - outputCount += outputPtr; - out.write(buffer, 0, outputPtr); - } - return outputCount; - } - - /* - /********************************************************** - /* Public API, traversal - /********************************************************** - */ - - /** - * @return Next token from the stream, if any found, or null - * to indicate end-of-input - */ - @Override - public final JsonToken nextToken() throws IOException - { - /* First: field names are special -- we will always tokenize - * (part of) value along with field name to simplify - * state handling. If so, can and need to use secondary token: - */ - if (_currToken == JsonToken.FIELD_NAME) { - return _nextAfterName(); - } - // But if we didn't already have a name, and (partially?) decode number, - // need to ensure no numeric information is leaked - _numTypesValid = NR_UNKNOWN; - if (_tokenIncomplete) { - _skipString(); // only strings can be partial - } - int i = _skipWSOrEnd(); - if (i < 0) { // end-of-input - // Should actually close/release things - // like input source, symbol table and recyclable buffers now. - close(); - return (_currToken = null); - } - // clear any data retained so far - _binaryValue = null; - - // Closing scope? - if (i == INT_RBRACKET || i == INT_RCURLY) { - _closeScope(i); - return _currToken; - } - - // Nope: do we then expect a comma? - if (_parsingContext.expectComma()) { - i = _skipComma(i); - - // Was that a trailing comma? - if ((_features & FEAT_MASK_TRAILING_COMMA) != 0) { - if ((i == INT_RBRACKET) || (i == INT_RCURLY)) { - _closeScope(i); - return _currToken; - } - } - } - - /* And should we now have a name? Always true for Object contexts, since - * the intermediate 'expect-value' state is never retained. - */ - boolean inObject = _parsingContext.inObject(); - if (inObject) { - // First, field name itself: - _updateNameLocation(); - String name = (i == INT_QUOTE) ? _parseName() : _handleOddName(i); - _parsingContext.setCurrentName(name); - _currToken = JsonToken.FIELD_NAME; - i = _skipColon(); - } - _updateLocation(); - - // Ok: we must have a value... what is it? - - JsonToken t; - - switch (i) { - case '"': - _tokenIncomplete = true; - t = JsonToken.VALUE_STRING; - break; - case '[': - if (!inObject) { - _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); - } - t = JsonToken.START_ARRAY; - break; - case '{': - if (!inObject) { - _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); - } - t = JsonToken.START_OBJECT; - break; - case '}': - // Error: } is not valid at this point; valid closers have - // been handled earlier - _reportUnexpectedChar(i, "expected a value"); - case 't': - _matchTrue(); - t = JsonToken.VALUE_TRUE; - break; - case 'f': - _matchFalse(); - t = JsonToken.VALUE_FALSE; - break; - case 'n': - _matchNull(); - t = JsonToken.VALUE_NULL; - break; - - case '-': - /* Should we have separate handling for plus? Although - * it is not allowed per se, it may be erroneously used, - * and could be indicate by a more specific error message. - */ - t = _parseNegNumber(); - break; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - t = _parsePosNumber(i); - break; - default: - t = _handleOddValue(i); - break; - } - - if (inObject) { - _nextToken = t; - return _currToken; - } - _currToken = t; - return t; - } - - private final JsonToken _nextAfterName() - { - _nameCopied = false; // need to invalidate if it was copied - JsonToken t = _nextToken; - _nextToken = null; - -// !!! 16-Nov-2015, tatu: TODO: fix [databind#37], copy next location to current here - - // Also: may need to start new context? - if (t == JsonToken.START_ARRAY) { - _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); - } else if (t == JsonToken.START_OBJECT) { - _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); - } - return (_currToken = t); - } - - @Override - public void finishToken() throws IOException { - if (_tokenIncomplete) { - _tokenIncomplete = false; - _finishString(); // only strings can be incomplete - } - } - - /* - /********************************************************** - /* Public API, nextXxx() overrides - /********************************************************** - */ - - // Implemented since 2.7 - @Override - public boolean nextFieldName(SerializableString sstr) throws IOException - { - // // // Note: most of code below is copied from nextToken() - - _numTypesValid = NR_UNKNOWN; - if (_currToken == JsonToken.FIELD_NAME) { - _nextAfterName(); - return false; - } - if (_tokenIncomplete) { - _skipString(); - } - int i = _skipWSOrEnd(); - if (i < 0) { - close(); - _currToken = null; - return false; - } - _binaryValue = null; - - // Closing scope? - if (i == INT_RBRACKET || i == INT_RCURLY) { - _closeScope(i); - return false; - } - - if (_parsingContext.expectComma()) { - i = _skipComma(i); - - // Was that a trailing comma? - if ((_features & FEAT_MASK_TRAILING_COMMA) != 0) { - if ((i == INT_RBRACKET) || (i == INT_RCURLY)) { - _closeScope(i); - return false; - } - } - } - - if (!_parsingContext.inObject()) { - _updateLocation(); - _nextTokenNotInObject(i); - return false; - } - - _updateNameLocation(); - if (i == INT_QUOTE) { - // when doing literal match, must consider escaping: - char[] nameChars = sstr.asQuotedChars(); - final int len = nameChars.length; - - // Require 4 more bytes for faster skipping of colon that follows name - if ((_inputPtr + len + 4) < _inputEnd) { // maybe... - // first check length match by - final int end = _inputPtr+len; - if (_inputBuffer[end] == '"') { - int offset = 0; - int ptr = _inputPtr; - while (true) { - if (ptr == end) { // yes, match! - _parsingContext.setCurrentName(sstr.getValue()); - _isNextTokenNameYes(_skipColonFast(ptr+1)); - return true; - } - if (nameChars[offset] != _inputBuffer[ptr]) { - break; - } - ++offset; - ++ptr; - } - } - } - } - return _isNextTokenNameMaybe(i, sstr.getValue()); - } - - @Override - public String nextFieldName() throws IOException - { - // // // Note: this is almost a verbatim copy of nextToken() (minus comments) - - _numTypesValid = NR_UNKNOWN; - if (_currToken == JsonToken.FIELD_NAME) { - _nextAfterName(); - return null; - } - if (_tokenIncomplete) { - _skipString(); - } - int i = _skipWSOrEnd(); - if (i < 0) { - close(); - _currToken = null; - return null; - } - _binaryValue = null; - if (i == INT_RBRACKET) { - _updateLocation(); - if (!_parsingContext.inArray()) { - _reportMismatchedEndMarker(i, '}'); - } - _parsingContext = _parsingContext.clearAndGetParent(); - _currToken = JsonToken.END_ARRAY; - return null; - } - if (i == INT_RCURLY) { - _updateLocation(); - if (!_parsingContext.inObject()) { - _reportMismatchedEndMarker(i, ']'); - } - _parsingContext = _parsingContext.clearAndGetParent(); - _currToken = JsonToken.END_OBJECT; - return null; - } - if (_parsingContext.expectComma()) { - i = _skipComma(i); - } - if (!_parsingContext.inObject()) { - _updateLocation(); - _nextTokenNotInObject(i); - return null; - } - - _updateNameLocation(); - String name = (i == INT_QUOTE) ? _parseName() : _handleOddName(i); - _parsingContext.setCurrentName(name); - _currToken = JsonToken.FIELD_NAME; - i = _skipColon(); - - _updateLocation(); - if (i == INT_QUOTE) { - _tokenIncomplete = true; - _nextToken = JsonToken.VALUE_STRING; - return name; - } - - // Ok: we must have a value... what is it? - - JsonToken t; - - switch (i) { - case '-': - t = _parseNegNumber(); - break; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - t = _parsePosNumber(i); - break; - case 'f': - _matchFalse(); - t = JsonToken.VALUE_FALSE; - break; - case 'n': - _matchNull(); - t = JsonToken.VALUE_NULL; - break; - case 't': - _matchTrue(); - t = JsonToken.VALUE_TRUE; - break; - case '[': - t = JsonToken.START_ARRAY; - break; - case '{': - t = JsonToken.START_OBJECT; - break; - default: - t = _handleOddValue(i); - break; - } - _nextToken = t; - return name; - } - - private final void _isNextTokenNameYes(int i) throws IOException - { - _currToken = JsonToken.FIELD_NAME; - _updateLocation(); - - switch (i) { - case '"': - _tokenIncomplete = true; - _nextToken = JsonToken.VALUE_STRING; - return; - case '[': - _nextToken = JsonToken.START_ARRAY; - return; - case '{': - _nextToken = JsonToken.START_OBJECT; - return; - case 't': - _matchToken("true", 1); - _nextToken = JsonToken.VALUE_TRUE; - return; - case 'f': - _matchToken("false", 1); - _nextToken = JsonToken.VALUE_FALSE; - return; - case 'n': - _matchToken("null", 1); - _nextToken = JsonToken.VALUE_NULL; - return; - case '-': - _nextToken = _parseNegNumber(); - return; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - _nextToken = _parsePosNumber(i); - return; - } - _nextToken = _handleOddValue(i); - } - - protected boolean _isNextTokenNameMaybe(int i, String nameToMatch) throws IOException - { - // // // and this is back to standard nextToken() - String name = (i == INT_QUOTE) ? _parseName() : _handleOddName(i); - _parsingContext.setCurrentName(name); - _currToken = JsonToken.FIELD_NAME; - i = _skipColon(); - _updateLocation(); - if (i == INT_QUOTE) { - _tokenIncomplete = true; - _nextToken = JsonToken.VALUE_STRING; - return nameToMatch.equals(name); - } - // Ok: we must have a value... what is it? - JsonToken t; - switch (i) { - case '-': - t = _parseNegNumber(); - break; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - t = _parsePosNumber(i); - break; - case 'f': - _matchFalse(); - t = JsonToken.VALUE_FALSE; - break; - case 'n': - _matchNull(); - t = JsonToken.VALUE_NULL; - break; - case 't': - _matchTrue(); - t = JsonToken.VALUE_TRUE; - break; - case '[': - t = JsonToken.START_ARRAY; - break; - case '{': - t = JsonToken.START_OBJECT; - break; - default: - t = _handleOddValue(i); - break; - } - _nextToken = t; - return nameToMatch.equals(name); - } - - private final JsonToken _nextTokenNotInObject(int i) throws IOException - { - if (i == INT_QUOTE) { - _tokenIncomplete = true; - return (_currToken = JsonToken.VALUE_STRING); - } - switch (i) { - case '[': - _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); - return (_currToken = JsonToken.START_ARRAY); - case '{': - _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); - return (_currToken = JsonToken.START_OBJECT); - case 't': - _matchToken("true", 1); - return (_currToken = JsonToken.VALUE_TRUE); - case 'f': - _matchToken("false", 1); - return (_currToken = JsonToken.VALUE_FALSE); - case 'n': - _matchToken("null", 1); - return (_currToken = JsonToken.VALUE_NULL); - case '-': - return (_currToken = _parseNegNumber()); - /* Should we have separate handling for plus? Although - * it is not allowed per se, it may be erroneously used, - * and could be indicated by a more specific error message. - */ - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - return (_currToken = _parsePosNumber(i)); - /* - * This check proceeds only if the Feature.ALLOW_MISSING_VALUES is enabled - * The Check is for missing values. Incase of missing values in an array, the next token will be either ',' or ']'. - * This case, decrements the already incremented _inputPtr in the buffer in case of comma(,) - * so that the existing flow goes back to checking the next token which will be comma again and - * it continues the parsing. - * Also the case returns NULL as current token in case of ',' or ']'. - */ - case ',': - case ']': - if(isEnabled(Feature.ALLOW_MISSING_VALUES)) { - _inputPtr--; - return (_currToken = JsonToken.VALUE_NULL); - } - } - return (_currToken = _handleOddValue(i)); - } - - // note: identical to one in UTF8StreamJsonParser - @Override - public final String nextTextValue() throws IOException - { - if (_currToken == JsonToken.FIELD_NAME) { // mostly copied from '_nextAfterName' - _nameCopied = false; - JsonToken t = _nextToken; - _nextToken = null; - _currToken = t; - if (t == JsonToken.VALUE_STRING) { - if (_tokenIncomplete) { - _tokenIncomplete = false; - _finishString(); - } - return _textBuffer.contentsAsString(); - } - if (t == JsonToken.START_ARRAY) { - _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); - } else if (t == JsonToken.START_OBJECT) { - _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); - } - return null; - } - // !!! TODO: optimize this case as well - return (nextToken() == JsonToken.VALUE_STRING) ? getText() : null; - } - - // note: identical to one in Utf8StreamParser - @Override - public final int nextIntValue(int defaultValue) throws IOException - { - if (_currToken == JsonToken.FIELD_NAME) { - _nameCopied = false; - JsonToken t = _nextToken; - _nextToken = null; - _currToken = t; - if (t == JsonToken.VALUE_NUMBER_INT) { - return getIntValue(); - } - if (t == JsonToken.START_ARRAY) { - _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); - } else if (t == JsonToken.START_OBJECT) { - _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); - } - return defaultValue; - } - // !!! TODO: optimize this case as well - return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getIntValue() : defaultValue; - } - - // note: identical to one in Utf8StreamParser - @Override - public final long nextLongValue(long defaultValue) throws IOException - { - if (_currToken == JsonToken.FIELD_NAME) { // mostly copied from '_nextAfterName' - _nameCopied = false; - JsonToken t = _nextToken; - _nextToken = null; - _currToken = t; - if (t == JsonToken.VALUE_NUMBER_INT) { - return getLongValue(); - } - if (t == JsonToken.START_ARRAY) { - _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); - } else if (t == JsonToken.START_OBJECT) { - _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); - } - return defaultValue; - } - // !!! TODO: optimize this case as well - return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getLongValue() : defaultValue; - } - - // note: identical to one in UTF8StreamJsonParser - @Override - public final Boolean nextBooleanValue() throws IOException - { - if (_currToken == JsonToken.FIELD_NAME) { // mostly copied from '_nextAfterName' - _nameCopied = false; - JsonToken t = _nextToken; - _nextToken = null; - _currToken = t; - if (t == JsonToken.VALUE_TRUE) { - return Boolean.TRUE; - } - if (t == JsonToken.VALUE_FALSE) { - return Boolean.FALSE; - } - if (t == JsonToken.START_ARRAY) { - _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); - } else if (t == JsonToken.START_OBJECT) { - _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); - } - return null; - } - JsonToken t = nextToken(); - if (t != null) { - int id = t.id(); - if (id == ID_TRUE) return Boolean.TRUE; - if (id == ID_FALSE) return Boolean.FALSE; - } - return null; - } - - /* - /********************************************************** - /* Internal methods, number parsing - /********************************************************** - */ - - /** - * Initial parsing method for number values. It needs to be able - * to parse enough input to be able to determine whether the - * value is to be considered a simple integer value, or a more - * generic decimal value: latter of which needs to be expressed - * as a floating point number. The basic rule is that if the number - * has no fractional or exponential part, it is an integer; otherwise - * a floating point number. - *

- * Because much of input has to be processed in any case, no partial - * parsing is done: all input text will be stored for further - * processing. However, actual numeric value conversion will be - * deferred, since it is usually the most complicated and costliest - * part of processing. - */ - protected final JsonToken _parsePosNumber(int ch) throws IOException - { - /* Although we will always be complete with respect to textual - * representation (that is, all characters will be parsed), - * actual conversion to a number is deferred. Thus, need to - * note that no representations are valid yet - */ - int ptr = _inputPtr; - int startPtr = ptr-1; // to include digit already read - final int inputLen = _inputEnd; - - // One special case, leading zero(es): - if (ch == INT_0) { - return _parseNumber2(false, startPtr); - } - - /* First, let's see if the whole number is contained within - * the input buffer unsplit. This should be the common case; - * and to simplify processing, we will just reparse contents - * in the alternative case (number split on buffer boundary) - */ - - int intLen = 1; // already got one - - // First let's get the obligatory integer part: - int_loop: - while (true) { - if (ptr >= inputLen) { - _inputPtr = startPtr; - return _parseNumber2(false, startPtr); - } - ch = (int) _inputBuffer[ptr++]; - if (ch < INT_0 || ch > INT_9) { - break int_loop; - } - ++intLen; - } - if (ch == INT_PERIOD || ch == INT_e || ch == INT_E) { - _inputPtr = ptr; - return _parseFloat(ch, startPtr, ptr, false, intLen); - } - // Got it all: let's add to text buffer for parsing, access - --ptr; // need to push back following separator - _inputPtr = ptr; - // As per #105, need separating space between root values; check here - if (_parsingContext.inRoot()) { - _verifyRootSpace(ch); - } - int len = ptr-startPtr; - _textBuffer.resetWithShared(_inputBuffer, startPtr, len); - return resetInt(false, intLen); - } - - private final JsonToken _parseFloat(int ch, int startPtr, int ptr, boolean neg, int intLen) - throws IOException - { - final int inputLen = _inputEnd; - int fractLen = 0; - - // And then see if we get other parts - if (ch == '.') { // yes, fraction - fract_loop: - while (true) { - if (ptr >= inputLen) { - return _parseNumber2(neg, startPtr); - } - ch = (int) _inputBuffer[ptr++]; - if (ch < INT_0 || ch > INT_9) { - break fract_loop; - } - ++fractLen; - } - // must be followed by sequence of ints, one minimum - if (fractLen == 0) { - reportUnexpectedNumberChar(ch, "Decimal point not followed by a digit"); - } - } - int expLen = 0; - if (ch == 'e' || ch == 'E') { // and/or exponent - if (ptr >= inputLen) { - _inputPtr = startPtr; - return _parseNumber2(neg, startPtr); - } - // Sign indicator? - ch = (int) _inputBuffer[ptr++]; - if (ch == INT_MINUS || ch == INT_PLUS) { // yup, skip for now - if (ptr >= inputLen) { - _inputPtr = startPtr; - return _parseNumber2(neg, startPtr); - } - ch = (int) _inputBuffer[ptr++]; - } - while (ch <= INT_9 && ch >= INT_0) { - ++expLen; - if (ptr >= inputLen) { - _inputPtr = startPtr; - return _parseNumber2(neg, startPtr); - } - ch = (int) _inputBuffer[ptr++]; - } - // must be followed by sequence of ints, one minimum - if (expLen == 0) { - reportUnexpectedNumberChar(ch, "Exponent indicator not followed by a digit"); - } - } - --ptr; // need to push back following separator - _inputPtr = ptr; - // As per #105, need separating space between root values; check here - if (_parsingContext.inRoot()) { - _verifyRootSpace(ch); - } - int len = ptr-startPtr; - _textBuffer.resetWithShared(_inputBuffer, startPtr, len); - // And there we have it! - return resetFloat(neg, intLen, fractLen, expLen); - } - - protected final JsonToken _parseNegNumber() throws IOException - { - int ptr = _inputPtr; - int startPtr = ptr-1; // to include sign/digit already read - final int inputLen = _inputEnd; - - if (ptr >= inputLen) { - return _parseNumber2(true, startPtr); - } - int ch = _inputBuffer[ptr++]; - // First check: must have a digit to follow minus sign - if (ch > INT_9 || ch < INT_0) { - _inputPtr = ptr; - return _handleInvalidNumberStart(ch, true); - } - // One special case, leading zero(es): - if (ch == INT_0) { - return _parseNumber2(true, startPtr); - } - int intLen = 1; // already got one - - // First let's get the obligatory integer part: - int_loop: - while (true) { - if (ptr >= inputLen) { - return _parseNumber2(true, startPtr); - } - ch = (int) _inputBuffer[ptr++]; - if (ch < INT_0 || ch > INT_9) { - break int_loop; - } - ++intLen; - } - - if (ch == INT_PERIOD || ch == INT_e || ch == INT_E) { - _inputPtr = ptr; - return _parseFloat(ch, startPtr, ptr, true, intLen); - } - --ptr; - _inputPtr = ptr; - if (_parsingContext.inRoot()) { - _verifyRootSpace(ch); - } - int len = ptr-startPtr; - _textBuffer.resetWithShared(_inputBuffer, startPtr, len); - return resetInt(true, intLen); - } - - /** - * Method called to parse a number, when the primary parse - * method has failed to parse it, due to it being split on - * buffer boundary. As a result code is very similar, except - * that it has to explicitly copy contents to the text buffer - * instead of just sharing the main input buffer. - */ - private final JsonToken _parseNumber2(boolean neg, int startPtr) throws IOException - { - _inputPtr = neg ? (startPtr+1) : startPtr; - char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); - int outPtr = 0; - - // Need to prepend sign? - if (neg) { - outBuf[outPtr++] = '-'; - } - - // This is the place to do leading-zero check(s) too: - int intLen = 0; - char c = (_inputPtr < _inputEnd) ? _inputBuffer[_inputPtr++] - : getNextChar("No digit following minus sign", JsonToken.VALUE_NUMBER_INT); - if (c == '0') { - c = _verifyNoLeadingZeroes(); - } - boolean eof = false; - - // Ok, first the obligatory integer part: - int_loop: - while (c >= '0' && c <= '9') { - ++intLen; - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - outBuf[outPtr++] = c; - if (_inputPtr >= _inputEnd && !_loadMore()) { - // EOF is legal for main level int values - c = CHAR_NULL; - eof = true; - break int_loop; - } - c = _inputBuffer[_inputPtr++]; - } - // Also, integer part is not optional - if (intLen == 0) { - return _handleInvalidNumberStart(c, neg); - } - - int fractLen = 0; - // And then see if we get other parts - if (c == '.') { // yes, fraction - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - outBuf[outPtr++] = c; - - fract_loop: - while (true) { - if (_inputPtr >= _inputEnd && !_loadMore()) { - eof = true; - break fract_loop; - } - c = _inputBuffer[_inputPtr++]; - if (c < INT_0 || c > INT_9) { - break fract_loop; - } - ++fractLen; - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - outBuf[outPtr++] = c; - } - // must be followed by sequence of ints, one minimum - if (fractLen == 0) { - reportUnexpectedNumberChar(c, "Decimal point not followed by a digit"); - } - } - - int expLen = 0; - if (c == 'e' || c == 'E') { // exponent? - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - outBuf[outPtr++] = c; - // Not optional, can require that we get one more char - c = (_inputPtr < _inputEnd) ? _inputBuffer[_inputPtr++] - : getNextChar("expected a digit for number exponent"); - // Sign indicator? - if (c == '-' || c == '+') { - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - outBuf[outPtr++] = c; - // Likewise, non optional: - c = (_inputPtr < _inputEnd) ? _inputBuffer[_inputPtr++] - : getNextChar("expected a digit for number exponent"); - } - - exp_loop: - while (c <= INT_9 && c >= INT_0) { - ++expLen; - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - outBuf[outPtr++] = c; - if (_inputPtr >= _inputEnd && !_loadMore()) { - eof = true; - break exp_loop; - } - c = _inputBuffer[_inputPtr++]; - } - // must be followed by sequence of ints, one minimum - if (expLen == 0) { - reportUnexpectedNumberChar(c, "Exponent indicator not followed by a digit"); - } - } - - // Ok; unless we hit end-of-input, need to push last char read back - if (!eof) { - --_inputPtr; - if (_parsingContext.inRoot()) { - _verifyRootSpace(c); - } - } - _textBuffer.setCurrentLength(outPtr); - // And there we have it! - return reset(neg, intLen, fractLen, expLen); - } - - /** - * Method called when we have seen one zero, and want to ensure - * it is not followed by another - */ - private final char _verifyNoLeadingZeroes() throws IOException - { - // Fast case first: - if (_inputPtr < _inputEnd) { - char ch = _inputBuffer[_inputPtr]; - // if not followed by a number (probably '.'); return zero as is, to be included - if (ch < '0' || ch > '9') { - return '0'; - } - } - // and offline the less common case - return _verifyNLZ2(); - } - - private char _verifyNLZ2() throws IOException - { - if (_inputPtr >= _inputEnd && !_loadMore()) { - return '0'; - } - char ch = _inputBuffer[_inputPtr]; - if (ch < '0' || ch > '9') { - return '0'; - } - if (!isEnabled(Feature.ALLOW_NUMERIC_LEADING_ZEROS)) { - reportInvalidNumber("Leading zeroes not allowed"); - } - // if so, just need to skip either all zeroes (if followed by number); or all but one (if non-number) - ++_inputPtr; // Leading zero to be skipped - if (ch == INT_0) { - while (_inputPtr < _inputEnd || _loadMore()) { - ch = _inputBuffer[_inputPtr]; - if (ch < '0' || ch > '9') { // followed by non-number; retain one zero - return '0'; - } - ++_inputPtr; // skip previous zero - if (ch != '0') { // followed by other number; return - break; - } - } - } - return ch; - } - - /** - * Method called if expected numeric value (due to leading sign) does not - * look like a number - */ - protected JsonToken _handleInvalidNumberStart(int ch, boolean negative) throws IOException - { - if (ch == 'I') { - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { - _reportInvalidEOFInValue(JsonToken.VALUE_NUMBER_INT); - } - } - ch = _inputBuffer[_inputPtr++]; - if (ch == 'N') { - String match = negative ? "-INF" :"+INF"; - _matchToken(match, 3); - if (isEnabled(Feature.ALLOW_NON_NUMERIC_NUMBERS)) { - return resetAsNaN(match, negative ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY); - } - _reportError("Non-standard token '"+match+"': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow"); - } else if (ch == 'n') { - String match = negative ? "-Infinity" :"+Infinity"; - _matchToken(match, 3); - if (isEnabled(Feature.ALLOW_NON_NUMERIC_NUMBERS)) { - return resetAsNaN(match, negative ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY); - } - _reportError("Non-standard token '"+match+"': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow"); - } - } - reportUnexpectedNumberChar(ch, "expected digit (0-9) to follow minus sign, for valid numeric value"); - return null; - } - - /** - * Method called to ensure that a root-value is followed by a space - * token. - *

- * NOTE: caller MUST ensure there is at least one character available; - * and that input pointer is AT given char (not past) - */ - private final void _verifyRootSpace(int ch) throws IOException - { - // caller had pushed it back, before calling; reset - ++_inputPtr; - switch (ch) { - case ' ': - case '\t': - return; - case '\r': - _skipCR(); - return; - case '\n': - ++_currInputRow; - _currInputRowStart = _inputPtr; - return; - } - _reportMissingRootWS(ch); - } - - /* - /********************************************************** - /* Internal methods, secondary parsing - /********************************************************** - */ - - protected final String _parseName() throws IOException - { - // First: let's try to see if we have a simple name: one that does - // not cross input buffer boundary, and does not contain escape sequences. - int ptr = _inputPtr; - int hash = _hashSeed; - final int[] codes = _icLatin1; - - while (ptr < _inputEnd) { - int ch = _inputBuffer[ptr]; - if (ch < codes.length && codes[ch] != 0) { - if (ch == '"') { - int start = _inputPtr; - _inputPtr = ptr+1; // to skip the quote - return _symbols.findSymbol(_inputBuffer, start, ptr - start, hash); - } - break; - } - hash = (hash * CharsToNameCanonicalizer.HASH_MULT) + ch; - ++ptr; - } - int start = _inputPtr; - _inputPtr = ptr; - return _parseName2(start, hash, INT_QUOTE); - } - - private String _parseName2(int startPtr, int hash, int endChar) throws IOException - { - _textBuffer.resetWithShared(_inputBuffer, startPtr, (_inputPtr - startPtr)); - - /* Output pointers; calls will also ensure that the buffer is - * not shared and has room for at least one more char. - */ - char[] outBuf = _textBuffer.getCurrentSegment(); - int outPtr = _textBuffer.getCurrentSegmentSize(); - - while (true) { - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { - _reportInvalidEOF(" in field name", JsonToken.FIELD_NAME); - } - } - char c = _inputBuffer[_inputPtr++]; - int i = (int) c; - if (i <= INT_BACKSLASH) { - if (i == INT_BACKSLASH) { - /* Although chars outside of BMP are to be escaped as - * an UTF-16 surrogate pair, does that affect decoding? - * For now let's assume it does not. - */ - c = _decodeEscaped(); - } else if (i <= endChar) { - if (i == endChar) { - break; - } - if (i < INT_SPACE) { - _throwUnquotedSpace(i, "name"); - } - } - } - hash = (hash * CharsToNameCanonicalizer.HASH_MULT) + c; - // Ok, let's add char to output: - outBuf[outPtr++] = c; - - // Need more room? - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - } - _textBuffer.setCurrentLength(outPtr); - { - TextBuffer tb = _textBuffer; - char[] buf = tb.getTextBuffer(); - int start = tb.getTextOffset(); - int len = tb.size(); - return _symbols.findSymbol(buf, start, len, hash); - } - } - - /** - * Method called when we see non-white space character other - * than double quote, when expecting a field name. - * In standard mode will just throw an expection; but - * in non-standard modes may be able to parse name. - */ - protected String _handleOddName(int i) throws IOException - { - // [JACKSON-173]: allow single quotes - if (i == '\'' && isEnabled(Feature.ALLOW_SINGLE_QUOTES)) { - return _parseAposName(); - } - // [JACKSON-69]: allow unquoted names if feature enabled: - if (!isEnabled(Feature.ALLOW_UNQUOTED_FIELD_NAMES)) { - _reportUnexpectedChar(i, "was expecting double-quote to start field name"); - } - final int[] codes = CharTypes.getInputCodeLatin1JsNames(); - final int maxCode = codes.length; - - // Also: first char must be a valid name char, but NOT be number - boolean firstOk; - - if (i < maxCode) { // identifier, or a number ([Issue#102]) - firstOk = (codes[i] == 0); - } else { - firstOk = Character.isJavaIdentifierPart((char) i); - } - if (!firstOk) { - _reportUnexpectedChar(i, "was expecting either valid name character (for unquoted name) or double-quote (for quoted) to start field name"); - } - int ptr = _inputPtr; - int hash = _hashSeed; - final int inputLen = _inputEnd; - - if (ptr < inputLen) { - do { - int ch = _inputBuffer[ptr]; - if (ch < maxCode) { - if (codes[ch] != 0) { - int start = _inputPtr-1; // -1 to bring back first char - _inputPtr = ptr; - return _symbols.findSymbol(_inputBuffer, start, ptr - start, hash); - } - } else if (!Character.isJavaIdentifierPart((char) ch)) { - int start = _inputPtr-1; // -1 to bring back first char - _inputPtr = ptr; - return _symbols.findSymbol(_inputBuffer, start, ptr - start, hash); - } - hash = (hash * CharsToNameCanonicalizer.HASH_MULT) + ch; - ++ptr; - } while (ptr < inputLen); - } - int start = _inputPtr-1; - _inputPtr = ptr; - return _handleOddName2(start, hash, codes); - } - - protected String _parseAposName() throws IOException - { - // Note: mostly copy of_parseFieldName - int ptr = _inputPtr; - int hash = _hashSeed; - final int inputLen = _inputEnd; - - if (ptr < inputLen) { - final int[] codes = _icLatin1; - final int maxCode = codes.length; - - do { - int ch = _inputBuffer[ptr]; - if (ch == '\'') { - int start = _inputPtr; - _inputPtr = ptr+1; // to skip the quote - return _symbols.findSymbol(_inputBuffer, start, ptr - start, hash); - } - if (ch < maxCode && codes[ch] != 0) { - break; - } - hash = (hash * CharsToNameCanonicalizer.HASH_MULT) + ch; - ++ptr; - } while (ptr < inputLen); - } - - int start = _inputPtr; - _inputPtr = ptr; - - return _parseName2(start, hash, '\''); - } - - /** - * Method for handling cases where first non-space character - * of an expected value token is not legal for standard JSON content. - */ - protected JsonToken _handleOddValue(int i) throws IOException - { - // Most likely an error, unless we are to allow single-quote-strings - switch (i) { - case '\'': - /* Allow single quotes? Unlike with regular Strings, we'll eagerly parse - * contents; this so that there'sno need to store information on quote char used. - * Also, no separation to fast/slow parsing; we'll just do - * one regular (~= slowish) parsing, to keep code simple - */ - if (isEnabled(Feature.ALLOW_SINGLE_QUOTES)) { - return _handleApos(); - } - break; - case ']': - /* 28-Mar-2016: [core#116]: If Feature.ALLOW_MISSING_VALUES is enabled - * we may allow "missing values", that is, encountering a trailing - * comma or closing marker where value would be expected - */ - if (!_parsingContext.inArray()) { - break; - } - // fall through - case ',': - if (isEnabled(Feature.ALLOW_MISSING_VALUES)) { - --_inputPtr; - return JsonToken.VALUE_NULL; - } - break; - case 'N': - _matchToken("NaN", 1); - if (isEnabled(Feature.ALLOW_NON_NUMERIC_NUMBERS)) { - return resetAsNaN("NaN", Double.NaN); - } - _reportError("Non-standard token 'NaN': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow"); - break; - case 'I': - _matchToken("Infinity", 1); - if (isEnabled(Feature.ALLOW_NON_NUMERIC_NUMBERS)) { - return resetAsNaN("Infinity", Double.POSITIVE_INFINITY); - } - _reportError("Non-standard token 'Infinity': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow"); - break; - case '+': // note: '-' is taken as number - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { - _reportInvalidEOFInValue(JsonToken.VALUE_NUMBER_INT); - } - } - return _handleInvalidNumberStart(_inputBuffer[_inputPtr++], false); - } - // [core#77] Try to decode most likely token - if (Character.isJavaIdentifierStart(i)) { - _reportInvalidToken(""+((char) i), "('true', 'false' or 'null')"); - } - // but if it doesn't look like a token: - _reportUnexpectedChar(i, "expected a valid value (number, String, array, object, 'true', 'false' or 'null')"); - return null; - } - - protected JsonToken _handleApos() throws IOException - { - char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); - int outPtr = _textBuffer.getCurrentSegmentSize(); - - while (true) { - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { - _reportInvalidEOF(": was expecting closing quote for a string value", - JsonToken.VALUE_STRING); - } - } - char c = _inputBuffer[_inputPtr++]; - int i = (int) c; - if (i <= '\\') { - if (i == '\\') { - /* Although chars outside of BMP are to be escaped as - * an UTF-16 surrogate pair, does that affect decoding? - * For now let's assume it does not. - */ - c = _decodeEscaped(); - } else if (i <= '\'') { - if (i == '\'') { - break; - } - if (i < INT_SPACE) { - _throwUnquotedSpace(i, "string value"); - } - } - } - // Need more room? - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - // Ok, let's add char to output: - outBuf[outPtr++] = c; - } - _textBuffer.setCurrentLength(outPtr); - return JsonToken.VALUE_STRING; - } - - private String _handleOddName2(int startPtr, int hash, int[] codes) throws IOException - { - _textBuffer.resetWithShared(_inputBuffer, startPtr, (_inputPtr - startPtr)); - char[] outBuf = _textBuffer.getCurrentSegment(); - int outPtr = _textBuffer.getCurrentSegmentSize(); - final int maxCode = codes.length; - - while (true) { - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { // acceptable for now (will error out later) - break; - } - } - char c = _inputBuffer[_inputPtr]; - int i = (int) c; - if (i <= maxCode) { - if (codes[i] != 0) { - break; - } - } else if (!Character.isJavaIdentifierPart(c)) { - break; - } - ++_inputPtr; - hash = (hash * CharsToNameCanonicalizer.HASH_MULT) + i; - // Ok, let's add char to output: - outBuf[outPtr++] = c; - - // Need more room? - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - } - _textBuffer.setCurrentLength(outPtr); - { - TextBuffer tb = _textBuffer; - char[] buf = tb.getTextBuffer(); - int start = tb.getTextOffset(); - int len = tb.size(); - - return _symbols.findSymbol(buf, start, len, hash); - } - } - - @Override - protected final void _finishString() throws IOException - { - /* First: let's try to see if we have simple String value: one - * that does not cross input buffer boundary, and does not - * contain escape sequences. - */ - int ptr = _inputPtr; - final int inputLen = _inputEnd; - - if (ptr < inputLen) { - final int[] codes = _icLatin1; - final int maxCode = codes.length; - - do { - int ch = _inputBuffer[ptr]; - if (ch < maxCode && codes[ch] != 0) { - if (ch == '"') { - _textBuffer.resetWithShared(_inputBuffer, _inputPtr, (ptr-_inputPtr)); - _inputPtr = ptr+1; - // Yes, we got it all - return; - } - break; - } - ++ptr; - } while (ptr < inputLen); - } - - /* Either ran out of input, or bumped into an escape - * sequence... - */ - _textBuffer.resetWithCopy(_inputBuffer, _inputPtr, (ptr-_inputPtr)); - _inputPtr = ptr; - _finishString2(); - } - - protected void _finishString2() throws IOException - { - char[] outBuf = _textBuffer.getCurrentSegment(); - int outPtr = _textBuffer.getCurrentSegmentSize(); - final int[] codes = _icLatin1; - final int maxCode = codes.length; - - while (true) { - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { - _reportInvalidEOF(": was expecting closing quote for a string value", - JsonToken.VALUE_STRING); - } - } - char c = _inputBuffer[_inputPtr++]; - int i = (int) c; - if (i < maxCode && codes[i] != 0) { - if (i == INT_QUOTE) { - break; - } else if (i == INT_BACKSLASH) { - /* Although chars outside of BMP are to be escaped as - * an UTF-16 surrogate pair, does that affect decoding? - * For now let's assume it does not. - */ - c = _decodeEscaped(); - } else if (i < INT_SPACE) { - _throwUnquotedSpace(i, "string value"); - } // anything else? - } - // Need more room? - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - // Ok, let's add char to output: - outBuf[outPtr++] = c; - } - _textBuffer.setCurrentLength(outPtr); - } - - /** - * Method called to skim through rest of unparsed String value, - * if it is not needed. This can be done bit faster if contents - * need not be stored for future access. - */ - protected final void _skipString() throws IOException - { - _tokenIncomplete = false; - - int inPtr = _inputPtr; - int inLen = _inputEnd; - char[] inBuf = _inputBuffer; - - while (true) { - if (inPtr >= inLen) { - _inputPtr = inPtr; - if (!_loadMore()) { - _reportInvalidEOF(": was expecting closing quote for a string value", - JsonToken.VALUE_STRING); - } - inPtr = _inputPtr; - inLen = _inputEnd; - } - char c = inBuf[inPtr++]; - int i = (int) c; - if (i <= INT_BACKSLASH) { - if (i == INT_BACKSLASH) { - // Although chars outside of BMP are to be escaped as an UTF-16 surrogate pair, - // does that affect decoding? For now let's assume it does not. - _inputPtr = inPtr; - /*c = */ _decodeEscaped(); - inPtr = _inputPtr; - inLen = _inputEnd; - } else if (i <= INT_QUOTE) { - if (i == INT_QUOTE) { - _inputPtr = inPtr; - break; - } - if (i < INT_SPACE) { - _inputPtr = inPtr; - _throwUnquotedSpace(i, "string value"); - } - } - } - } - } - - /* - /********************************************************** - /* Internal methods, other parsing - /********************************************************** - */ - - /** - * We actually need to check the character value here - * (to see if we have \n following \r). - */ - protected final void _skipCR() throws IOException { - if (_inputPtr < _inputEnd || _loadMore()) { - if (_inputBuffer[_inputPtr] == '\n') { - ++_inputPtr; - } - } - ++_currInputRow; - _currInputRowStart = _inputPtr; - } - - private final int _skipColon() throws IOException - { - if ((_inputPtr + 4) >= _inputEnd) { - return _skipColon2(false); - } - char c = _inputBuffer[_inputPtr]; - if (c == ':') { // common case, no leading space - int i = _inputBuffer[++_inputPtr]; - if (i > INT_SPACE) { // nor trailing - if (i == INT_SLASH || i == INT_HASH) { - return _skipColon2(true); - } - ++_inputPtr; - return i; - } - if (i == INT_SPACE || i == INT_TAB) { - i = (int) _inputBuffer[++_inputPtr]; - if (i > INT_SPACE) { - if (i == INT_SLASH || i == INT_HASH) { - return _skipColon2(true); - } - ++_inputPtr; - return i; - } - } - return _skipColon2(true); // true -> skipped colon - } - if (c == ' ' || c == '\t') { - c = _inputBuffer[++_inputPtr]; - } - if (c == ':') { - int i = _inputBuffer[++_inputPtr]; - if (i > INT_SPACE) { - if (i == INT_SLASH || i == INT_HASH) { - return _skipColon2(true); - } - ++_inputPtr; - return i; - } - if (i == INT_SPACE || i == INT_TAB) { - i = (int) _inputBuffer[++_inputPtr]; - if (i > INT_SPACE) { - if (i == INT_SLASH || i == INT_HASH) { - return _skipColon2(true); - } - ++_inputPtr; - return i; - } - } - return _skipColon2(true); - } - return _skipColon2(false); - } - - private final int _skipColon2(boolean gotColon) throws IOException - { - while (_inputPtr < _inputEnd || _loadMore()) { - int i = (int) _inputBuffer[_inputPtr++]; - if (i > INT_SPACE) { - if (i == INT_SLASH) { - _skipComment(); - continue; - } - if (i == INT_HASH) { - if (_skipYAMLComment()) { - continue; - } - } - if (gotColon) { - return i; - } - if (i != INT_COLON) { - _reportUnexpectedChar(i, "was expecting a colon to separate field name and value"); - } - gotColon = true; - continue; - } - if (i < INT_SPACE) { - if (i == INT_LF) { - ++_currInputRow; - _currInputRowStart = _inputPtr; - } else if (i == INT_CR) { - _skipCR(); - } else if (i != INT_TAB) { - _throwInvalidSpace(i); - } - } - } - _reportInvalidEOF(" within/between "+_parsingContext.typeDesc()+" entries", - null); - return -1; - } - - // Variant called when we know there's at least 4 more bytes available - private final int _skipColonFast(int ptr) throws IOException - { - int i = (int) _inputBuffer[ptr++]; - if (i == INT_COLON) { // common case, no leading space - i = _inputBuffer[ptr++]; - if (i > INT_SPACE) { // nor trailing - if (i != INT_SLASH && i != INT_HASH) { - _inputPtr = ptr; - return i; - } - } else if (i == INT_SPACE || i == INT_TAB) { - i = (int) _inputBuffer[ptr++]; - if (i > INT_SPACE) { - if (i != INT_SLASH && i != INT_HASH) { - _inputPtr = ptr; - return i; - } - } - } - _inputPtr = ptr-1; - return _skipColon2(true); // true -> skipped colon - } - if (i == INT_SPACE || i == INT_TAB) { - i = _inputBuffer[ptr++]; - } - boolean gotColon = (i == INT_COLON); - if (gotColon) { - i = _inputBuffer[ptr++]; - if (i > INT_SPACE) { - if (i != INT_SLASH && i != INT_HASH) { - _inputPtr = ptr; - return i; - } - } else if (i == INT_SPACE || i == INT_TAB) { - i = (int) _inputBuffer[ptr++]; - if (i > INT_SPACE) { - if (i != INT_SLASH && i != INT_HASH) { - _inputPtr = ptr; - return i; - } - } - } - } - _inputPtr = ptr-1; - return _skipColon2(gotColon); - } - - // Primary loop: no reloading, comment handling - private final int _skipComma(int i) throws IOException - { - if (i != INT_COMMA) { - _reportUnexpectedChar(i, "was expecting comma to separate "+_parsingContext.typeDesc()+" entries"); - } - while (_inputPtr < _inputEnd) { - i = (int) _inputBuffer[_inputPtr++]; - if (i > INT_SPACE) { - if (i == INT_SLASH || i == INT_HASH) { - --_inputPtr; - return _skipAfterComma2(); - } - return i; - } - if (i < INT_SPACE) { - if (i == INT_LF) { - ++_currInputRow; - _currInputRowStart = _inputPtr; - } else if (i == INT_CR) { - _skipCR(); - } else if (i != INT_TAB) { - _throwInvalidSpace(i); - } - } - } - return _skipAfterComma2(); - } - - private final int _skipAfterComma2() throws IOException - { - while (_inputPtr < _inputEnd || _loadMore()) { - int i = (int) _inputBuffer[_inputPtr++]; - if (i > INT_SPACE) { - if (i == INT_SLASH) { - _skipComment(); - continue; - } - if (i == INT_HASH) { - if (_skipYAMLComment()) { - continue; - } - } - return i; - } - if (i < INT_SPACE) { - if (i == INT_LF) { - ++_currInputRow; - _currInputRowStart = _inputPtr; - } else if (i == INT_CR) { - _skipCR(); - } else if (i != INT_TAB) { - _throwInvalidSpace(i); - } - } - } - throw _constructError("Unexpected end-of-input within/between "+_parsingContext.typeDesc()+" entries"); - } - - private final int _skipWSOrEnd() throws IOException - { - // Let's handle first character separately since it is likely that - // it is either non-whitespace; or we have longer run of white space - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { - return _eofAsNextChar(); - } - } - int i = _inputBuffer[_inputPtr++]; - if (i > INT_SPACE) { - if (i == INT_SLASH || i == INT_HASH) { - --_inputPtr; - return _skipWSOrEnd2(); - } - return i; - } - if (i != INT_SPACE) { - if (i == INT_LF) { - ++_currInputRow; - _currInputRowStart = _inputPtr; - } else if (i == INT_CR) { - _skipCR(); - } else if (i != INT_TAB) { - _throwInvalidSpace(i); - } - } - - while (_inputPtr < _inputEnd) { - i = (int) _inputBuffer[_inputPtr++]; - if (i > INT_SPACE) { - if (i == INT_SLASH || i == INT_HASH) { - --_inputPtr; - return _skipWSOrEnd2(); - } - return i; - } - if (i != INT_SPACE) { - if (i == INT_LF) { - ++_currInputRow; - _currInputRowStart = _inputPtr; - } else if (i == INT_CR) { - _skipCR(); - } else if (i != INT_TAB) { - _throwInvalidSpace(i); - } - } - } - return _skipWSOrEnd2(); - } - - private int _skipWSOrEnd2() throws IOException - { - while (true) { - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { // We ran out of input... - return _eofAsNextChar(); - } - } - int i = (int) _inputBuffer[_inputPtr++]; - if (i > INT_SPACE) { - if (i == INT_SLASH) { - _skipComment(); - continue; - } - if (i == INT_HASH) { - if (_skipYAMLComment()) { - continue; - } - } - return i; - } else if (i != INT_SPACE) { - if (i == INT_LF) { - ++_currInputRow; - _currInputRowStart = _inputPtr; - } else if (i == INT_CR) { - _skipCR(); - } else if (i != INT_TAB) { - _throwInvalidSpace(i); - } - } - } - } - - private void _skipComment() throws IOException - { - if (!isEnabled(Feature.ALLOW_COMMENTS)) { - _reportUnexpectedChar('/', "maybe a (non-standard) comment? (not recognized as one since Feature 'ALLOW_COMMENTS' not enabled for parser)"); - } - // First: check which comment (if either) it is: - if (_inputPtr >= _inputEnd && !_loadMore()) { - _reportInvalidEOF(" in a comment", null); - } - char c = _inputBuffer[_inputPtr++]; - if (c == '/') { - _skipLine(); - } else if (c == '*') { - _skipCComment(); - } else { - _reportUnexpectedChar(c, "was expecting either '*' or '/' for a comment"); - } - } - - private void _skipCComment() throws IOException - { - // Ok: need the matching '*/' - while ((_inputPtr < _inputEnd) || _loadMore()) { - int i = (int) _inputBuffer[_inputPtr++]; - if (i <= '*') { - if (i == '*') { // end? - if ((_inputPtr >= _inputEnd) && !_loadMore()) { - break; - } - if (_inputBuffer[_inputPtr] == INT_SLASH) { - ++_inputPtr; - return; - } - continue; - } - if (i < INT_SPACE) { - if (i == INT_LF) { - ++_currInputRow; - _currInputRowStart = _inputPtr; - } else if (i == INT_CR) { - _skipCR(); - } else if (i != INT_TAB) { - _throwInvalidSpace(i); - } - } - } - } - _reportInvalidEOF(" in a comment", null); - } - - private boolean _skipYAMLComment() throws IOException - { - if (!isEnabled(Feature.ALLOW_YAML_COMMENTS)) { - return false; - } - _skipLine(); - return true; - } - - private void _skipLine() throws IOException - { - // Ok: need to find EOF or linefeed - while ((_inputPtr < _inputEnd) || _loadMore()) { - int i = (int) _inputBuffer[_inputPtr++]; - if (i < INT_SPACE) { - if (i == INT_LF) { - ++_currInputRow; - _currInputRowStart = _inputPtr; - break; - } else if (i == INT_CR) { - _skipCR(); - break; - } else if (i != INT_TAB) { - _throwInvalidSpace(i); - } - } - } - } - - @Override - protected char _decodeEscaped() throws IOException - { - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { - _reportInvalidEOF(" in character escape sequence", JsonToken.VALUE_STRING); - } - } - char c = _inputBuffer[_inputPtr++]; - - switch ((int) c) { - // First, ones that are mapped - case 'b': - return '\b'; - case 't': - return '\t'; - case 'n': - return '\n'; - case 'f': - return '\f'; - case 'r': - return '\r'; - - // And these are to be returned as they are - case '"': - case '/': - case '\\': - return c; - - case 'u': // and finally hex-escaped - break; - - default: - return _handleUnrecognizedCharacterEscape(c); - } - - // Ok, a hex escape. Need 4 characters - int value = 0; - for (int i = 0; i < 4; ++i) { - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { - _reportInvalidEOF(" in character escape sequence", JsonToken.VALUE_STRING); - } - } - int ch = (int) _inputBuffer[_inputPtr++]; - int digit = CharTypes.charToHex(ch); - if (digit < 0) { - _reportUnexpectedChar(ch, "expected a hex-digit for character escape sequence"); - } - value = (value << 4) | digit; - } - return (char) value; - } - - private final void _matchTrue() throws IOException { - int ptr = _inputPtr; - if ((ptr + 3) < _inputEnd) { - final char[] b = _inputBuffer; - if (b[ptr] == 'r' && b[++ptr] == 'u' && b[++ptr] == 'e') { - char c = b[++ptr]; - if (c < '0' || c == ']' || c == '}') { // expected/allowed chars - _inputPtr = ptr; - return; - } - } - } - // buffer boundary, or problem, offline - _matchToken("true", 1); - } - - private final void _matchFalse() throws IOException { - int ptr = _inputPtr; - if ((ptr + 4) < _inputEnd) { - final char[] b = _inputBuffer; - if (b[ptr] == 'a' && b[++ptr] == 'l' && b[++ptr] == 's' && b[++ptr] == 'e') { - char c = b[++ptr]; - if (c < '0' || c == ']' || c == '}') { // expected/allowed chars - _inputPtr = ptr; - return; - } - } - } - // buffer boundary, or problem, offline - _matchToken("false", 1); - } - - private final void _matchNull() throws IOException { - int ptr = _inputPtr; - if ((ptr + 3) < _inputEnd) { - final char[] b = _inputBuffer; - if (b[ptr] == 'u' && b[++ptr] == 'l' && b[++ptr] == 'l') { - char c = b[++ptr]; - if (c < '0' || c == ']' || c == '}') { // expected/allowed chars - _inputPtr = ptr; - return; - } - } - } - // buffer boundary, or problem, offline - _matchToken("null", 1); - } - - /** - * Helper method for checking whether input matches expected token - */ - protected final void _matchToken(String matchStr, int i) throws IOException - { - final int len = matchStr.length(); - - do { - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { - _reportInvalidToken(matchStr.substring(0, i)); - } - } - if (_inputBuffer[_inputPtr] != matchStr.charAt(i)) { - _reportInvalidToken(matchStr.substring(0, i)); - } - ++_inputPtr; - } while (++i < len); - - // but let's also ensure we either get EOF, or non-alphanum char... - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { - return; - } - } - char c = _inputBuffer[_inputPtr]; - if (c < '0' || c == ']' || c == '}') { // expected/allowed chars - return; - } - // if Java letter, it's a problem tho - if (Character.isJavaIdentifierPart(c)) { - _reportInvalidToken(matchStr.substring(0, i)); - } - return; - } - - /* - /********************************************************** - /* Binary access - /********************************************************** - */ - - /** - * Efficient handling for incremental parsing of base64-encoded - * textual content. - */ - protected byte[] _decodeBase64(Base64Variant b64variant) throws IOException - { - ByteArrayBuilder builder = _getByteArrayBuilder(); - - //main_loop: - while (true) { - // first, we'll skip preceding white space, if any - char ch; - do { - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - ch = _inputBuffer[_inputPtr++]; - } while (ch <= INT_SPACE); - int bits = b64variant.decodeBase64Char(ch); - if (bits < 0) { - if (ch == '"') { // reached the end, fair and square? - return builder.toByteArray(); - } - bits = _decodeBase64Escape(b64variant, ch, 0); - if (bits < 0) { // white space to skip - continue; - } - } - int decodedData = bits; - - // then second base64 char; can't get padding yet, nor ws - - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - ch = _inputBuffer[_inputPtr++]; - bits = b64variant.decodeBase64Char(ch); - if (bits < 0) { - bits = _decodeBase64Escape(b64variant, ch, 1); - } - decodedData = (decodedData << 6) | bits; - - // third base64 char; can be padding, but not ws - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - ch = _inputBuffer[_inputPtr++]; - bits = b64variant.decodeBase64Char(ch); - - // First branch: can get padding (-> 1 byte) - if (bits < 0) { - if (bits != Base64Variant.BASE64_VALUE_PADDING) { - // as per [JACKSON-631], could also just be 'missing' padding - if (ch == '"' && !b64variant.usesPadding()) { - decodedData >>= 4; - builder.append(decodedData); - return builder.toByteArray(); - } - bits = _decodeBase64Escape(b64variant, ch, 2); - } - if (bits == Base64Variant.BASE64_VALUE_PADDING) { - // Ok, must get more padding chars, then - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - ch = _inputBuffer[_inputPtr++]; - if (!b64variant.usesPaddingChar(ch)) { - throw reportInvalidBase64Char(b64variant, ch, 3, "expected padding character '"+b64variant.getPaddingChar()+"'"); - } - // Got 12 bits, only need 8, need to shift - decodedData >>= 4; - builder.append(decodedData); - continue; - } - // otherwise we got escaped other char, to be processed below - } - // Nope, 2 or 3 bytes - decodedData = (decodedData << 6) | bits; - // fourth and last base64 char; can be padding, but not ws - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - ch = _inputBuffer[_inputPtr++]; - bits = b64variant.decodeBase64Char(ch); - if (bits < 0) { - if (bits != Base64Variant.BASE64_VALUE_PADDING) { - // as per [JACKSON-631], could also just be 'missing' padding - if (ch == '"' && !b64variant.usesPadding()) { - decodedData >>= 2; - builder.appendTwoBytes(decodedData); - return builder.toByteArray(); - } - bits = _decodeBase64Escape(b64variant, ch, 3); - } - if (bits == Base64Variant.BASE64_VALUE_PADDING) { - // With padding we only get 2 bytes; but we have - // to shift it a bit so it is identical to triplet - // case with partial output. - // 3 chars gives 3x6 == 18 bits, of which 2 are - // dummies, need to discard: - decodedData >>= 2; - builder.appendTwoBytes(decodedData); - continue; - } - // otherwise we got escaped other char, to be processed below - } - // otherwise, our triplet is now complete - decodedData = (decodedData << 6) | bits; - builder.appendThreeBytes(decodedData); - } - } - - /* - /********************************************************** - /* Internal methods, location updating (refactored in 2.7) - /********************************************************** - */ - - @Override - public JsonLocation getTokenLocation() - { - final Object src = _ioContext.getSourceReference(); - if (_currToken == JsonToken.FIELD_NAME) { - long total = _currInputProcessed + (_nameStartOffset-1); - return new JsonLocation(src, - -1L, total, _nameStartRow, _nameStartCol); - } - return new JsonLocation(src, - -1L, _tokenInputTotal-1, _tokenInputRow, _tokenInputCol); - } - - @Override - public JsonLocation getCurrentLocation() { - int col = _inputPtr - _currInputRowStart + 1; // 1-based - return new JsonLocation(_ioContext.getSourceReference(), - -1L, _currInputProcessed + _inputPtr, - _currInputRow, col); - } - - // @since 2.7 - private final void _updateLocation() - { - int ptr = _inputPtr; - _tokenInputTotal = _currInputProcessed + ptr; - _tokenInputRow = _currInputRow; - _tokenInputCol = ptr - _currInputRowStart; - } - - // @since 2.7 - private final void _updateNameLocation() - { - int ptr = _inputPtr; - _nameStartOffset = ptr; - _nameStartRow = _currInputRow; - _nameStartCol = ptr - _currInputRowStart; - } - - /* - /********************************************************** - /* Error reporting - /********************************************************** - */ - - protected void _reportInvalidToken(String matchedPart) throws IOException { - _reportInvalidToken(matchedPart, "'null', 'true', 'false' or NaN"); - } - - protected void _reportInvalidToken(String matchedPart, String msg) throws IOException - { - StringBuilder sb = new StringBuilder(matchedPart); - /* Let's just try to find what appears to be the token, using - * regular Java identifier character rules. It's just a heuristic, - * nothing fancy here. - */ - while (true) { - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { - break; - } - } - char c = _inputBuffer[_inputPtr]; - if (!Character.isJavaIdentifierPart(c)) { - break; - } - ++_inputPtr; - sb.append(c); - } - _reportError("Unrecognized token '"+sb.toString()+"': was expecting "+msg); - } - - /* - /********************************************************** - /* Internal methods, other - /********************************************************** - */ - - private void _closeScope(int i) throws JsonParseException { - if (i == INT_RBRACKET) { - _updateLocation(); - if (!_parsingContext.inArray()) { - _reportMismatchedEndMarker(i, '}'); - } - _parsingContext = _parsingContext.clearAndGetParent(); - _currToken = JsonToken.END_ARRAY; - } - if (i == INT_RCURLY) { - _updateLocation(); - if (!_parsingContext.inObject()) { - _reportMismatchedEndMarker(i, ']'); - } - _parsingContext = _parsingContext.clearAndGetParent(); - _currToken = JsonToken.END_OBJECT; - } - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/UTF8DataInputJsonParser.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/UTF8DataInputJsonParser.java deleted file mode 100644 index 9943ad45..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/UTF8DataInputJsonParser.java +++ /dev/null @@ -1,2866 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.json; - -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_FIELD_NAME; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_NUMBER_FLOAT; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_NUMBER_INT; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_STRING; - -import java.io.DataInput; -import java.io.EOFException; -import java.io.IOException; -import java.io.OutputStream; -import java.io.Writer; -import java.util.Arrays; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.Base64Variant; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonLocation; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; -import autosaveworld.zlibs.com.fasterxml.jackson.core.ObjectCodec; -import autosaveworld.zlibs.com.fasterxml.jackson.core.base.ParserBase; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.CharTypes; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.IOContext; -import autosaveworld.zlibs.com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.ByteArrayBuilder; - -/** - * This is a concrete implementation of {@link JsonParser}, which is - * based on a {@link java.io.DataInput} as the input source. - *

- * Due to limitations in look-ahead (basically there's none), as well - * as overhead of reading content mostly byte-by-byte, - * there are some - * minor differences from regular streaming parsing. Specifically: - *

    - *
  • Input location is not being tracked, as offsets would need to - * be updated for each read from all over the place; if caller wants - * this information, it has to track this with {@link DataInput}. - *
  • - *
  • As a consequence linefeed handling is removed so all white-space is - * equal; and checks are simplified NOT to check for control characters - *
  • - *
- * - * @since 2.8 - */ -public class UTF8DataInputJsonParser - extends ParserBase -{ - final static byte BYTE_LF = (byte) '\n'; - - // This is the main input-code lookup table, fetched eagerly - private final static int[] _icUTF8 = CharTypes.getInputCodeUtf8(); - - // Latin1 encoding is not supported, but we do use 8-bit subset for - // pre-processing task, to simplify first pass, keep it fast. - protected final static int[] _icLatin1 = CharTypes.getInputCodeLatin1(); - - /* - /********************************************************** - /* Configuration - /********************************************************** - */ - - /** - * Codec used for data binding when (if) requested; typically full - * ObjectMapper, but that abstract is not part of core - * package. - */ - protected ObjectCodec _objectCodec; - - /** - * Symbol table that contains field names encountered so far - */ - final protected ByteQuadsCanonicalizer _symbols; - - /* - /********************************************************** - /* Parsing state - /********************************************************** - */ - - /** - * Temporary buffer used for name parsing. - */ - protected int[] _quadBuffer = new int[16]; - - /** - * Flag that indicates that the current token has not yet - * been fully processed, and needs to be finished for - * some access (or skipped to obtain the next token) - */ - protected boolean _tokenIncomplete; - - /** - * Temporary storage for partially parsed name bytes. - */ - private int _quad1; - - /* - /********************************************************** - /* Current input data - /********************************************************** - */ - - protected DataInput _inputData; - - /** - * Sometimes we need buffering for just a single byte we read but - * have to "push back" - */ - protected int _nextByte = -1; - - /* - /********************************************************** - /* Life-cycle - /********************************************************** - */ - - public UTF8DataInputJsonParser(IOContext ctxt, int features, DataInput inputData, - ObjectCodec codec, ByteQuadsCanonicalizer sym, - int firstByte) - { - super(ctxt, features); - _objectCodec = codec; - _symbols = sym; - _inputData = inputData; - _nextByte = firstByte; - } - - @Override - public ObjectCodec getCodec() { - return _objectCodec; - } - - @Override - public void setCodec(ObjectCodec c) { - _objectCodec = c; - } - - /* - /********************************************************** - /* Overrides for life-cycle - /********************************************************** - */ - - @Override - public int releaseBuffered(OutputStream out) throws IOException { - return 0; - } - - @Override - public Object getInputSource() { - return _inputData; - } - - /* - /********************************************************** - /* Overrides, low-level reading - /********************************************************** - */ - - @Override - protected void _closeInput() throws IOException { } - - /** - * Method called to release internal buffers owned by the base - * reader. This may be called along with {@link #_closeInput} (for - * example, when explicitly closing this reader instance), or - * separately (if need be). - */ - @Override - protected void _releaseBuffers() throws IOException - { - super._releaseBuffers(); - // Merge found symbols, if any: - _symbols.release(); - } - - /* - /********************************************************** - /* Public API, data access - /********************************************************** - */ - - @Override - public String getText() throws IOException - { - if (_currToken == JsonToken.VALUE_STRING) { - if (_tokenIncomplete) { - _tokenIncomplete = false; - return _finishAndReturnString(); // only strings can be incomplete - } - return _textBuffer.contentsAsString(); - } - return _getText2(_currToken); - } - - @Override - public int getText(Writer writer) throws IOException - { - JsonToken t = _currToken; - if (t == JsonToken.VALUE_STRING) { - if (_tokenIncomplete) { - _tokenIncomplete = false; - _finishString(); // only strings can be incomplete - } - return _textBuffer.contentsToWriter(writer); - } - if (t == JsonToken.FIELD_NAME) { - String n = _parsingContext.getCurrentName(); - writer.write(n); - return n.length(); - } - if (t != null) { - if (t.isNumeric()) { - return _textBuffer.contentsToWriter(writer); - } - char[] ch = t.asCharArray(); - writer.write(ch); - return ch.length; - } - return 0; - } - - // // // Let's override default impls for improved performance - @Override - public String getValueAsString() throws IOException - { - if (_currToken == JsonToken.VALUE_STRING) { - if (_tokenIncomplete) { - _tokenIncomplete = false; - return _finishAndReturnString(); // only strings can be incomplete - } - return _textBuffer.contentsAsString(); - } - if (_currToken == JsonToken.FIELD_NAME) { - return getCurrentName(); - } - return super.getValueAsString(null); - } - - @Override - public String getValueAsString(String defValue) throws IOException - { - if (_currToken == JsonToken.VALUE_STRING) { - if (_tokenIncomplete) { - _tokenIncomplete = false; - return _finishAndReturnString(); // only strings can be incomplete - } - return _textBuffer.contentsAsString(); - } - if (_currToken == JsonToken.FIELD_NAME) { - return getCurrentName(); - } - return super.getValueAsString(defValue); - } - - @Override - public int getValueAsInt() throws IOException - { - JsonToken t = _currToken; - if ((t == JsonToken.VALUE_NUMBER_INT) || (t == JsonToken.VALUE_NUMBER_FLOAT)) { - // inlined 'getIntValue()' - if ((_numTypesValid & NR_INT) == 0) { - if (_numTypesValid == NR_UNKNOWN) { - return _parseIntValue(); - } - if ((_numTypesValid & NR_INT) == 0) { - convertNumberToInt(); - } - } - return _numberInt; - } - return super.getValueAsInt(0); - } - - @Override - public int getValueAsInt(int defValue) throws IOException - { - JsonToken t = _currToken; - if ((t == JsonToken.VALUE_NUMBER_INT) || (t == JsonToken.VALUE_NUMBER_FLOAT)) { - // inlined 'getIntValue()' - if ((_numTypesValid & NR_INT) == 0) { - if (_numTypesValid == NR_UNKNOWN) { - return _parseIntValue(); - } - if ((_numTypesValid & NR_INT) == 0) { - convertNumberToInt(); - } - } - return _numberInt; - } - return super.getValueAsInt(defValue); - } - - protected final String _getText2(JsonToken t) - { - if (t == null) { - return null; - } - switch (t.id()) { - case ID_FIELD_NAME: - return _parsingContext.getCurrentName(); - - case ID_STRING: - // fall through - case ID_NUMBER_INT: - case ID_NUMBER_FLOAT: - return _textBuffer.contentsAsString(); - default: - return t.asString(); - } - } - - @Override - public char[] getTextCharacters() throws IOException - { - if (_currToken != null) { // null only before/after document - switch (_currToken.id()) { - - case ID_FIELD_NAME: - if (!_nameCopied) { - String name = _parsingContext.getCurrentName(); - int nameLen = name.length(); - if (_nameCopyBuffer == null) { - _nameCopyBuffer = _ioContext.allocNameCopyBuffer(nameLen); - } else if (_nameCopyBuffer.length < nameLen) { - _nameCopyBuffer = new char[nameLen]; - } - name.getChars(0, nameLen, _nameCopyBuffer, 0); - _nameCopied = true; - } - return _nameCopyBuffer; - - case ID_STRING: - if (_tokenIncomplete) { - _tokenIncomplete = false; - _finishString(); // only strings can be incomplete - } - // fall through - case ID_NUMBER_INT: - case ID_NUMBER_FLOAT: - return _textBuffer.getTextBuffer(); - - default: - return _currToken.asCharArray(); - } - } - return null; - } - - @Override - public int getTextLength() throws IOException - { - if (_currToken == JsonToken.VALUE_STRING) { - if (_tokenIncomplete) { - _tokenIncomplete = false; - _finishString(); // only strings can be incomplete - } - return _textBuffer.size(); - } - if (_currToken == JsonToken.FIELD_NAME) { - return _parsingContext.getCurrentName().length(); - } - if (_currToken != null) { // null only before/after document - if (_currToken.isNumeric()) { - return _textBuffer.size(); - } - return _currToken.asCharArray().length; - } - return 0; - } - - @Override - public int getTextOffset() throws IOException - { - // Most have offset of 0, only some may have other values: - if (_currToken != null) { - switch (_currToken.id()) { - case ID_FIELD_NAME: - return 0; - case ID_STRING: - if (_tokenIncomplete) { - _tokenIncomplete = false; - _finishString(); // only strings can be incomplete - } - // fall through - case ID_NUMBER_INT: - case ID_NUMBER_FLOAT: - return _textBuffer.getTextOffset(); - default: - } - } - return 0; - } - - @Override - public byte[] getBinaryValue(Base64Variant b64variant) throws IOException - { - if (_currToken != JsonToken.VALUE_STRING && - (_currToken != JsonToken.VALUE_EMBEDDED_OBJECT || _binaryValue == null)) { - _reportError("Current token ("+_currToken+") not VALUE_STRING or VALUE_EMBEDDED_OBJECT, can not access as binary"); - } - /* To ensure that we won't see inconsistent data, better clear up - * state... - */ - if (_tokenIncomplete) { - try { - _binaryValue = _decodeBase64(b64variant); - } catch (IllegalArgumentException iae) { - throw _constructError("Failed to decode VALUE_STRING as base64 ("+b64variant+"): "+iae.getMessage()); - } - /* let's clear incomplete only now; allows for accessing other - * textual content in error cases - */ - _tokenIncomplete = false; - } else { // may actually require conversion... - if (_binaryValue == null) { - ByteArrayBuilder builder = _getByteArrayBuilder(); - _decodeBase64(getText(), builder, b64variant); - _binaryValue = builder.toByteArray(); - } - } - return _binaryValue; - } - - @Override - public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws IOException - { - // if we have already read the token, just use whatever we may have - if (!_tokenIncomplete || _currToken != JsonToken.VALUE_STRING) { - byte[] b = getBinaryValue(b64variant); - out.write(b); - return b.length; - } - // otherwise do "real" incremental parsing... - byte[] buf = _ioContext.allocBase64Buffer(); - try { - return _readBinary(b64variant, out, buf); - } finally { - _ioContext.releaseBase64Buffer(buf); - } - } - - protected int _readBinary(Base64Variant b64variant, OutputStream out, - byte[] buffer) throws IOException - { - int outputPtr = 0; - final int outputEnd = buffer.length - 3; - int outputCount = 0; - - while (true) { - // first, we'll skip preceding white space, if any - int ch; - do { - ch = _inputData.readUnsignedByte(); - } while (ch <= INT_SPACE); - int bits = b64variant.decodeBase64Char(ch); - if (bits < 0) { // reached the end, fair and square? - if (ch == INT_QUOTE) { - break; - } - bits = _decodeBase64Escape(b64variant, ch, 0); - if (bits < 0) { // white space to skip - continue; - } - } - - // enough room? If not, flush - if (outputPtr > outputEnd) { - outputCount += outputPtr; - out.write(buffer, 0, outputPtr); - outputPtr = 0; - } - - int decodedData = bits; - - // then second base64 char; can't get padding yet, nor ws - ch = _inputData.readUnsignedByte(); - bits = b64variant.decodeBase64Char(ch); - if (bits < 0) { - bits = _decodeBase64Escape(b64variant, ch, 1); - } - decodedData = (decodedData << 6) | bits; - - // third base64 char; can be padding, but not ws - ch = _inputData.readUnsignedByte(); - bits = b64variant.decodeBase64Char(ch); - - // First branch: can get padding (-> 1 byte) - if (bits < 0) { - if (bits != Base64Variant.BASE64_VALUE_PADDING) { - // could also just be 'missing' padding - if (ch == '"' && !b64variant.usesPadding()) { - decodedData >>= 4; - buffer[outputPtr++] = (byte) decodedData; - break; - } - bits = _decodeBase64Escape(b64variant, ch, 2); - } - if (bits == Base64Variant.BASE64_VALUE_PADDING) { - // Ok, must get padding - ch = _inputData.readUnsignedByte(); - if (!b64variant.usesPaddingChar(ch)) { - throw reportInvalidBase64Char(b64variant, ch, 3, "expected padding character '"+b64variant.getPaddingChar()+"'"); - } - // Got 12 bits, only need 8, need to shift - decodedData >>= 4; - buffer[outputPtr++] = (byte) decodedData; - continue; - } - } - // Nope, 2 or 3 bytes - decodedData = (decodedData << 6) | bits; - // fourth and last base64 char; can be padding, but not ws - ch = _inputData.readUnsignedByte(); - bits = b64variant.decodeBase64Char(ch); - if (bits < 0) { - if (bits != Base64Variant.BASE64_VALUE_PADDING) { - // could also just be 'missing' padding - if (ch == '"' && !b64variant.usesPadding()) { - decodedData >>= 2; - buffer[outputPtr++] = (byte) (decodedData >> 8); - buffer[outputPtr++] = (byte) decodedData; - break; - } - bits = _decodeBase64Escape(b64variant, ch, 3); - } - if (bits == Base64Variant.BASE64_VALUE_PADDING) { - /* With padding we only get 2 bytes; but we have - * to shift it a bit so it is identical to triplet - * case with partial output. - * 3 chars gives 3x6 == 18 bits, of which 2 are - * dummies, need to discard: - */ - decodedData >>= 2; - buffer[outputPtr++] = (byte) (decodedData >> 8); - buffer[outputPtr++] = (byte) decodedData; - continue; - } - } - // otherwise, our triplet is now complete - decodedData = (decodedData << 6) | bits; - buffer[outputPtr++] = (byte) (decodedData >> 16); - buffer[outputPtr++] = (byte) (decodedData >> 8); - buffer[outputPtr++] = (byte) decodedData; - } - _tokenIncomplete = false; - if (outputPtr > 0) { - outputCount += outputPtr; - out.write(buffer, 0, outputPtr); - } - return outputCount; - } - - /* - /********************************************************** - /* Public API, traversal, basic - /********************************************************** - */ - - /** - * @return Next token from the stream, if any found, or null - * to indicate end-of-input - */ - @Override - public JsonToken nextToken() throws IOException - { - /* First: field names are special -- we will always tokenize - * (part of) value along with field name to simplify - * state handling. If so, can and need to use secondary token: - */ - if (_currToken == JsonToken.FIELD_NAME) { - return _nextAfterName(); - } - // But if we didn't already have a name, and (partially?) decode number, - // need to ensure no numeric information is leaked - _numTypesValid = NR_UNKNOWN; - if (_tokenIncomplete) { - _skipString(); // only strings can be partial - } - int i = _skipWSOrEnd(); - if (i < 0) { // end-of-input - // Close/release things like input source, symbol table and recyclable buffers - close(); - return (_currToken = null); - } - // clear any data retained so far - _binaryValue = null; - _tokenInputRow = _currInputRow; - - // Closing scope? - if (i == INT_RBRACKET || i == INT_RCURLY) { - _closeScope(i); - return _currToken; - } - - // Nope: do we then expect a comma? - if (_parsingContext.expectComma()) { - if (i != INT_COMMA) { - _reportUnexpectedChar(i, "was expecting comma to separate "+_parsingContext.typeDesc()+" entries"); - } - i = _skipWS(); - - // Was that a trailing comma? - if (Feature.ALLOW_TRAILING_COMMA.enabledIn(_features)) { - if (i == INT_RBRACKET || i == INT_RCURLY) { - _closeScope(i); - return _currToken; - } - } - } - - /* And should we now have a name? Always true for - * Object contexts, since the intermediate 'expect-value' - * state is never retained. - */ - if (!_parsingContext.inObject()) { - return _nextTokenNotInObject(i); - } - // So first parse the field name itself: - String n = _parseName(i); - _parsingContext.setCurrentName(n); - _currToken = JsonToken.FIELD_NAME; - - i = _skipColon(); - - // Ok: we must have a value... what is it? Strings are very common, check first: - if (i == INT_QUOTE) { - _tokenIncomplete = true; - _nextToken = JsonToken.VALUE_STRING; - return _currToken; - } - JsonToken t; - - switch (i) { - case '-': - t = _parseNegNumber(); - break; - - /* Should we have separate handling for plus? Although - * it is not allowed per se, it may be erroneously used, - * and could be indicate by a more specific error message. - */ - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - t = _parsePosNumber(i); - break; - case 'f': - _matchToken("false", 1); - t = JsonToken.VALUE_FALSE; - break; - case 'n': - _matchToken("null", 1); - t = JsonToken.VALUE_NULL; - break; - case 't': - _matchToken("true", 1); - t = JsonToken.VALUE_TRUE; - break; - case '[': - t = JsonToken.START_ARRAY; - break; - case '{': - t = JsonToken.START_OBJECT; - break; - - default: - t = _handleUnexpectedValue(i); - } - _nextToken = t; - return _currToken; - } - - private final JsonToken _nextTokenNotInObject(int i) throws IOException - { - if (i == INT_QUOTE) { - _tokenIncomplete = true; - return (_currToken = JsonToken.VALUE_STRING); - } - switch (i) { - case '[': - _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); - return (_currToken = JsonToken.START_ARRAY); - case '{': - _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); - return (_currToken = JsonToken.START_OBJECT); - case 't': - _matchToken("true", 1); - return (_currToken = JsonToken.VALUE_TRUE); - case 'f': - _matchToken("false", 1); - return (_currToken = JsonToken.VALUE_FALSE); - case 'n': - _matchToken("null", 1); - return (_currToken = JsonToken.VALUE_NULL); - case '-': - return (_currToken = _parseNegNumber()); - /* Should we have separate handling for plus? Although - * it is not allowed per se, it may be erroneously used, - * and could be indicated by a more specific error message. - */ - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - return (_currToken = _parsePosNumber(i)); - } - return (_currToken = _handleUnexpectedValue(i)); - } - - private final JsonToken _nextAfterName() - { - _nameCopied = false; // need to invalidate if it was copied - JsonToken t = _nextToken; - _nextToken = null; - - // Also: may need to start new context? - if (t == JsonToken.START_ARRAY) { - _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); - } else if (t == JsonToken.START_OBJECT) { - _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); - } - return (_currToken = t); - } - - @Override - public void finishToken() throws IOException { - if (_tokenIncomplete) { - _tokenIncomplete = false; - _finishString(); // only strings can be incomplete - } - } - - /* - /********************************************************** - /* Public API, traversal, nextXxxValue/nextFieldName - /********************************************************** - */ - - // Can not implement without look-ahead... -// public boolean nextFieldName(SerializableString str) throws IOException - - @Override - public String nextFieldName() throws IOException - { - // // // Note: this is almost a verbatim copy of nextToken() - - _numTypesValid = NR_UNKNOWN; - if (_currToken == JsonToken.FIELD_NAME) { - _nextAfterName(); - return null; - } - if (_tokenIncomplete) { - _skipString(); - } - int i = _skipWS(); - _binaryValue = null; - _tokenInputRow = _currInputRow; - - if (i == INT_RBRACKET) { - if (!_parsingContext.inArray()) { - _reportMismatchedEndMarker(i, '}'); - } - _parsingContext = _parsingContext.clearAndGetParent(); - _currToken = JsonToken.END_ARRAY; - return null; - } - if (i == INT_RCURLY) { - if (!_parsingContext.inObject()) { - _reportMismatchedEndMarker(i, ']'); - } - _parsingContext = _parsingContext.clearAndGetParent(); - _currToken = JsonToken.END_OBJECT; - return null; - } - - // Nope: do we then expect a comma? - if (_parsingContext.expectComma()) { - if (i != INT_COMMA) { - _reportUnexpectedChar(i, "was expecting comma to separate "+_parsingContext.typeDesc()+" entries"); - } - i = _skipWS(); - } - if (!_parsingContext.inObject()) { - _nextTokenNotInObject(i); - return null; - } - - final String nameStr = _parseName(i); - _parsingContext.setCurrentName(nameStr); - _currToken = JsonToken.FIELD_NAME; - - i = _skipColon(); - if (i == INT_QUOTE) { - _tokenIncomplete = true; - _nextToken = JsonToken.VALUE_STRING; - return nameStr; - } - JsonToken t; - switch (i) { - case '-': - t = _parseNegNumber(); - break; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - t = _parsePosNumber(i); - break; - case 'f': - _matchToken("false", 1); - t = JsonToken.VALUE_FALSE; - break; - case 'n': - _matchToken("null", 1); - t = JsonToken.VALUE_NULL; - break; - case 't': - _matchToken("true", 1); - t = JsonToken.VALUE_TRUE; - break; - case '[': - t = JsonToken.START_ARRAY; - break; - case '{': - t = JsonToken.START_OBJECT; - break; - - default: - t = _handleUnexpectedValue(i); - } - _nextToken = t; - return nameStr; - } - - @Override - public String nextTextValue() throws IOException - { - // two distinct cases; either got name and we know next type, or 'other' - if (_currToken == JsonToken.FIELD_NAME) { // mostly copied from '_nextAfterName' - _nameCopied = false; - JsonToken t = _nextToken; - _nextToken = null; - _currToken = t; - if (t == JsonToken.VALUE_STRING) { - if (_tokenIncomplete) { - _tokenIncomplete = false; - return _finishAndReturnString(); - } - return _textBuffer.contentsAsString(); - } - if (t == JsonToken.START_ARRAY) { - _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); - } else if (t == JsonToken.START_OBJECT) { - _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); - } - return null; - } - return (nextToken() == JsonToken.VALUE_STRING) ? getText() : null; - } - - @Override - public int nextIntValue(int defaultValue) throws IOException - { - // two distinct cases; either got name and we know next type, or 'other' - if (_currToken == JsonToken.FIELD_NAME) { // mostly copied from '_nextAfterName' - _nameCopied = false; - JsonToken t = _nextToken; - _nextToken = null; - _currToken = t; - if (t == JsonToken.VALUE_NUMBER_INT) { - return getIntValue(); - } - if (t == JsonToken.START_ARRAY) { - _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); - } else if (t == JsonToken.START_OBJECT) { - _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); - } - return defaultValue; - } - return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getIntValue() : defaultValue; - } - - @Override - public long nextLongValue(long defaultValue) throws IOException - { - // two distinct cases; either got name and we know next type, or 'other' - if (_currToken == JsonToken.FIELD_NAME) { // mostly copied from '_nextAfterName' - _nameCopied = false; - JsonToken t = _nextToken; - _nextToken = null; - _currToken = t; - if (t == JsonToken.VALUE_NUMBER_INT) { - return getLongValue(); - } - if (t == JsonToken.START_ARRAY) { - _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); - } else if (t == JsonToken.START_OBJECT) { - _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); - } - return defaultValue; - } - return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getLongValue() : defaultValue; - } - - @Override - public Boolean nextBooleanValue() throws IOException - { - // two distinct cases; either got name and we know next type, or 'other' - if (_currToken == JsonToken.FIELD_NAME) { // mostly copied from '_nextAfterName' - _nameCopied = false; - JsonToken t = _nextToken; - _nextToken = null; - _currToken = t; - if (t == JsonToken.VALUE_TRUE) { - return Boolean.TRUE; - } - if (t == JsonToken.VALUE_FALSE) { - return Boolean.FALSE; - } - if (t == JsonToken.START_ARRAY) { - _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); - } else if (t == JsonToken.START_OBJECT) { - _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); - } - return null; - } - - JsonToken t = nextToken(); - if (t == JsonToken.VALUE_TRUE) { - return Boolean.TRUE; - } - if (t == JsonToken.VALUE_FALSE) { - return Boolean.FALSE; - } - return null; - } - - /* - /********************************************************** - /* Internal methods, number parsing - /********************************************************** - */ - - /** - * Initial parsing method for number values. It needs to be able - * to parse enough input to be able to determine whether the - * value is to be considered a simple integer value, or a more - * generic decimal value: latter of which needs to be expressed - * as a floating point number. The basic rule is that if the number - * has no fractional or exponential part, it is an integer; otherwise - * a floating point number. - *

- * Because much of input has to be processed in any case, no partial - * parsing is done: all input text will be stored for further - * processing. However, actual numeric value conversion will be - * deferred, since it is usually the most complicated and costliest - * part of processing. - */ - protected JsonToken _parsePosNumber(int c) throws IOException - { - char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); - int outPtr; - - // One special case: if first char is 0, must not be followed by a digit. - // Gets bit tricky as we only want to retain 0 if it's the full value - if (c == INT_0) { - c = _handleLeadingZeroes(); - if (c <= INT_9 && c >= INT_0) { // skip if followed by digit - outPtr = 0; - } else { - outBuf[0] = '0'; - outPtr = 1; - } - } else { - outBuf[0] = (char) c; - c = _inputData.readUnsignedByte(); - outPtr = 1; - } - int intLen = outPtr; - - // With this, we have a nice and tight loop: - while (c <= INT_9 && c >= INT_0) { - ++intLen; - outBuf[outPtr++] = (char) c; - c = _inputData.readUnsignedByte(); - } - if (c == '.' || c == 'e' || c == 'E') { - return _parseFloat(outBuf, outPtr, c, false, intLen); - } - _textBuffer.setCurrentLength(outPtr); - // As per [core#105], need separating space between root values; check here - if (_parsingContext.inRoot()) { - _verifyRootSpace(); - } else { - _nextByte = c; - } - // And there we have it! - return resetInt(false, intLen); - } - - protected JsonToken _parseNegNumber() throws IOException - { - char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); - int outPtr = 0; - - // Need to prepend sign? - outBuf[outPtr++] = '-'; - int c = _inputData.readUnsignedByte(); - outBuf[outPtr++] = (char) c; - // Note: must be followed by a digit - if (c <= INT_0) { - // One special case: if first char is 0 need to check no leading zeroes - if (c == INT_0) { - c = _handleLeadingZeroes(); - } else { - return _handleInvalidNumberStart(c, true); - } - } else { - if (c > INT_9) { - return _handleInvalidNumberStart(c, true); - } - c = _inputData.readUnsignedByte(); - } - // Ok: we can first just add digit we saw first: - int intLen = 1; - - // With this, we have a nice and tight loop: - while (c <= INT_9 && c >= INT_0) { - ++intLen; - outBuf[outPtr++] = (char) c; - c = _inputData.readUnsignedByte(); - } - if (c == '.' || c == 'e' || c == 'E') { - return _parseFloat(outBuf, outPtr, c, true, intLen); - } - _textBuffer.setCurrentLength(outPtr); - // As per [core#105], need separating space between root values; check here - _nextByte = c; - if (_parsingContext.inRoot()) { - _verifyRootSpace(); - } - // And there we have it! - return resetInt(true, intLen); - } - - /** - * Method called when we have seen one zero, and want to ensure - * it is not followed by another, or, if leading zeroes allowed, - * skipped redundant ones. - * - * @return Character immediately following zeroes - */ - private final int _handleLeadingZeroes() throws IOException - { - int ch = _inputData.readUnsignedByte(); - // if not followed by a number (probably '.'); return zero as is, to be included - if (ch < INT_0 || ch > INT_9) { - return ch; - } - // we may want to allow leading zeroes them, after all... - if (!isEnabled(Feature.ALLOW_NUMERIC_LEADING_ZEROS)) { - reportInvalidNumber("Leading zeroes not allowed"); - } - // if so, just need to skip either all zeroes (if followed by number); or all but one (if non-number) - while (ch == INT_0) { - ch = _inputData.readUnsignedByte(); - } - return ch; - } - - private final JsonToken _parseFloat(char[] outBuf, int outPtr, int c, - boolean negative, int integerPartLength) throws IOException - { - int fractLen = 0; - - // And then see if we get other parts - if (c == INT_PERIOD) { // yes, fraction - outBuf[outPtr++] = (char) c; - - fract_loop: - while (true) { - c = _inputData.readUnsignedByte(); - if (c < INT_0 || c > INT_9) { - break fract_loop; - } - ++fractLen; - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - outBuf[outPtr++] = (char) c; - } - // must be followed by sequence of ints, one minimum - if (fractLen == 0) { - reportUnexpectedNumberChar(c, "Decimal point not followed by a digit"); - } - } - - int expLen = 0; - if (c == INT_e || c == INT_E) { // exponent? - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - outBuf[outPtr++] = (char) c; - c = _inputData.readUnsignedByte(); - // Sign indicator? - if (c == '-' || c == '+') { - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - outBuf[outPtr++] = (char) c; - c = _inputData.readUnsignedByte(); - } - while (c <= INT_9 && c >= INT_0) { - ++expLen; - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - outBuf[outPtr++] = (char) c; - c = _inputData.readUnsignedByte(); - } - // must be followed by sequence of ints, one minimum - if (expLen == 0) { - reportUnexpectedNumberChar(c, "Exponent indicator not followed by a digit"); - } - } - - // Ok; unless we hit end-of-input, need to push last char read back - // As per #105, need separating space between root values; check here - _nextByte = c; - if (_parsingContext.inRoot()) { - _verifyRootSpace(); - } - _textBuffer.setCurrentLength(outPtr); - - // And there we have it! - return resetFloat(negative, integerPartLength, fractLen, expLen); - } - - /** - * Method called to ensure that a root-value is followed by a space token, - * if possible. - *

- * NOTE: with {@link DataInput} source, not really feasible, up-front. - * If we did want, we could rearrange things to require space before - * next read, but initially let's just do nothing. - */ - private final void _verifyRootSpace() throws IOException - { - int ch = _nextByte; - if (ch <= INT_SPACE) { - _nextByte = -1; - if (ch == INT_CR || ch == INT_LF) { - ++_currInputRow; - } - return; - } - _reportMissingRootWS(ch); - } - - /* - /********************************************************** - /* Internal methods, secondary parsing - /********************************************************** - */ - - protected final String _parseName(int i) throws IOException - { - if (i != INT_QUOTE) { - return _handleOddName(i); - } - // If so, can also unroll loops nicely - /* 25-Nov-2008, tatu: This may seem weird, but here we do - * NOT want to worry about UTF-8 decoding. Rather, we'll - * assume that part is ok (if not it will get caught - * later on), and just handle quotes and backslashes here. - */ - final int[] codes = _icLatin1; - - int q = _inputData.readUnsignedByte(); - - if (codes[q] == 0) { - i = _inputData.readUnsignedByte(); - if (codes[i] == 0) { - q = (q << 8) | i; - i = _inputData.readUnsignedByte(); - if (codes[i] == 0) { - q = (q << 8) | i; - i = _inputData.readUnsignedByte(); - if (codes[i] == 0) { - q = (q << 8) | i; - i = _inputData.readUnsignedByte(); - if (codes[i] == 0) { - _quad1 = q; - return _parseMediumName(i); - } - if (i == INT_QUOTE) { // 4 byte/char case or broken - return findName(q, 4); - } - return parseName(q, i, 4); - } - if (i == INT_QUOTE) { // 3 byte/char case or broken - return findName(q, 3); - } - return parseName(q, i, 3); - } - if (i == INT_QUOTE) { // 2 byte/char case or broken - return findName(q, 2); - } - return parseName(q, i, 2); - } - if (i == INT_QUOTE) { // one byte/char case or broken - return findName(q, 1); - } - return parseName(q, i, 1); - } - if (q == INT_QUOTE) { // special case, "" - return ""; - } - return parseName(0, q, 0); // quoting or invalid char - } - - private final String _parseMediumName(int q2) throws IOException - { - final int[] codes = _icLatin1; - - // Ok, got 5 name bytes so far - int i = _inputData.readUnsignedByte(); - if (codes[i] != 0) { - if (i == INT_QUOTE) { // 5 bytes - return findName(_quad1, q2, 1); - } - return parseName(_quad1, q2, i, 1); // quoting or invalid char - } - q2 = (q2 << 8) | i; - i = _inputData.readUnsignedByte(); - if (codes[i] != 0) { - if (i == INT_QUOTE) { // 6 bytes - return findName(_quad1, q2, 2); - } - return parseName(_quad1, q2, i, 2); - } - q2 = (q2 << 8) | i; - i = _inputData.readUnsignedByte(); - if (codes[i] != 0) { - if (i == INT_QUOTE) { // 7 bytes - return findName(_quad1, q2, 3); - } - return parseName(_quad1, q2, i, 3); - } - q2 = (q2 << 8) | i; - i = _inputData.readUnsignedByte(); - if (codes[i] != 0) { - if (i == INT_QUOTE) { // 8 bytes - return findName(_quad1, q2, 4); - } - return parseName(_quad1, q2, i, 4); - } - return _parseMediumName2(i, q2); - } - - private final String _parseMediumName2(int q3, final int q2) throws IOException - { - final int[] codes = _icLatin1; - - // Got 9 name bytes so far - int i = _inputData.readUnsignedByte(); - if (codes[i] != 0) { - if (i == INT_QUOTE) { // 9 bytes - return findName(_quad1, q2, q3, 1); - } - return parseName(_quad1, q2, q3, i, 1); - } - q3 = (q3 << 8) | i; - i = _inputData.readUnsignedByte(); - if (codes[i] != 0) { - if (i == INT_QUOTE) { // 10 bytes - return findName(_quad1, q2, q3, 2); - } - return parseName(_quad1, q2, q3, i, 2); - } - q3 = (q3 << 8) | i; - i = _inputData.readUnsignedByte(); - if (codes[i] != 0) { - if (i == INT_QUOTE) { // 11 bytes - return findName(_quad1, q2, q3, 3); - } - return parseName(_quad1, q2, q3, i, 3); - } - q3 = (q3 << 8) | i; - i = _inputData.readUnsignedByte(); - if (codes[i] != 0) { - if (i == INT_QUOTE) { // 12 bytes - return findName(_quad1, q2, q3, 4); - } - return parseName(_quad1, q2, q3, i, 4); - } - return _parseLongName(i, q2, q3); - } - - private final String _parseLongName(int q, final int q2, int q3) throws IOException - { - _quadBuffer[0] = _quad1; - _quadBuffer[1] = q2; - _quadBuffer[2] = q3; - - // As explained above, will ignore UTF-8 encoding at this point - final int[] codes = _icLatin1; - int qlen = 3; - - while (true) { - int i = _inputData.readUnsignedByte(); - if (codes[i] != 0) { - if (i == INT_QUOTE) { - return findName(_quadBuffer, qlen, q, 1); - } - return parseEscapedName(_quadBuffer, qlen, q, i, 1); - } - - q = (q << 8) | i; - i = _inputData.readUnsignedByte(); - if (codes[i] != 0) { - if (i == INT_QUOTE) { - return findName(_quadBuffer, qlen, q, 2); - } - return parseEscapedName(_quadBuffer, qlen, q, i, 2); - } - - q = (q << 8) | i; - i = _inputData.readUnsignedByte(); - if (codes[i] != 0) { - if (i == INT_QUOTE) { - return findName(_quadBuffer, qlen, q, 3); - } - return parseEscapedName(_quadBuffer, qlen, q, i, 3); - } - - q = (q << 8) | i; - i = _inputData.readUnsignedByte(); - if (codes[i] != 0) { - if (i == INT_QUOTE) { - return findName(_quadBuffer, qlen, q, 4); - } - return parseEscapedName(_quadBuffer, qlen, q, i, 4); - } - - // Nope, no end in sight. Need to grow quad array etc - if (qlen >= _quadBuffer.length) { - _quadBuffer = _growArrayBy(_quadBuffer, qlen); - } - _quadBuffer[qlen++] = q; - q = i; - } - } - - private final String parseName(int q1, int ch, int lastQuadBytes) throws IOException { - return parseEscapedName(_quadBuffer, 0, q1, ch, lastQuadBytes); - } - - private final String parseName(int q1, int q2, int ch, int lastQuadBytes) throws IOException { - _quadBuffer[0] = q1; - return parseEscapedName(_quadBuffer, 1, q2, ch, lastQuadBytes); - } - - private final String parseName(int q1, int q2, int q3, int ch, int lastQuadBytes) throws IOException { - _quadBuffer[0] = q1; - _quadBuffer[1] = q2; - return parseEscapedName(_quadBuffer, 2, q3, ch, lastQuadBytes); - } - - /** - * Slower parsing method which is generally branched to when - * an escape sequence is detected (or alternatively for long - * names, one crossing input buffer boundary). - * Needs to be able to handle more exceptional cases, gets slower, - * and hance is offlined to a separate method. - */ - protected final String parseEscapedName(int[] quads, int qlen, int currQuad, int ch, - int currQuadBytes) throws IOException - { - /* 25-Nov-2008, tatu: This may seem weird, but here we do not want to worry about - * UTF-8 decoding yet. Rather, we'll assume that part is ok (if not it will get - * caught later on), and just handle quotes and backslashes here. - */ - final int[] codes = _icLatin1; - - while (true) { - if (codes[ch] != 0) { - if (ch == INT_QUOTE) { // we are done - break; - } - // Unquoted white space? - if (ch != INT_BACKSLASH) { - // As per [JACKSON-208], call can now return: - _throwUnquotedSpace(ch, "name"); - } else { - // Nope, escape sequence - ch = _decodeEscaped(); - } - /* Oh crap. May need to UTF-8 (re-)encode it, if it's - * beyond 7-bit ascii. Gets pretty messy. - * If this happens often, may want to use different name - * canonicalization to avoid these hits. - */ - if (ch > 127) { - // Ok, we'll need room for first byte right away - if (currQuadBytes >= 4) { - if (qlen >= quads.length) { - _quadBuffer = quads = _growArrayBy(quads, quads.length); - } - quads[qlen++] = currQuad; - currQuad = 0; - currQuadBytes = 0; - } - if (ch < 0x800) { // 2-byte - currQuad = (currQuad << 8) | (0xc0 | (ch >> 6)); - ++currQuadBytes; - // Second byte gets output below: - } else { // 3 bytes; no need to worry about surrogates here - currQuad = (currQuad << 8) | (0xe0 | (ch >> 12)); - ++currQuadBytes; - // need room for middle byte? - if (currQuadBytes >= 4) { - if (qlen >= quads.length) { - _quadBuffer = quads = _growArrayBy(quads, quads.length); - } - quads[qlen++] = currQuad; - currQuad = 0; - currQuadBytes = 0; - } - currQuad = (currQuad << 8) | (0x80 | ((ch >> 6) & 0x3f)); - ++currQuadBytes; - } - // And same last byte in both cases, gets output below: - ch = 0x80 | (ch & 0x3f); - } - } - // Ok, we have one more byte to add at any rate: - if (currQuadBytes < 4) { - ++currQuadBytes; - currQuad = (currQuad << 8) | ch; - } else { - if (qlen >= quads.length) { - _quadBuffer = quads = _growArrayBy(quads, quads.length); - } - quads[qlen++] = currQuad; - currQuad = ch; - currQuadBytes = 1; - } - ch = _inputData.readUnsignedByte(); - } - - if (currQuadBytes > 0) { - if (qlen >= quads.length) { - _quadBuffer = quads = _growArrayBy(quads, quads.length); - } - quads[qlen++] = pad(currQuad, currQuadBytes); - } - String name = _symbols.findName(quads, qlen); - if (name == null) { - name = addName(quads, qlen, currQuadBytes); - } - return name; - } - - /** - * Method called when we see non-white space character other - * than double quote, when expecting a field name. - * In standard mode will just throw an exception; but - * in non-standard modes may be able to parse name. - */ - protected String _handleOddName(int ch) throws IOException - { - if (ch == '\'' && isEnabled(Feature.ALLOW_SINGLE_QUOTES)) { - return _parseAposName(); - } - if (!isEnabled(Feature.ALLOW_UNQUOTED_FIELD_NAMES)) { - char c = (char) _decodeCharForError(ch); - _reportUnexpectedChar(c, "was expecting double-quote to start field name"); - } - /* Also: note that although we use a different table here, - * it does NOT handle UTF-8 decoding. It'll just pass those - * high-bit codes as acceptable for later decoding. - */ - final int[] codes = CharTypes.getInputCodeUtf8JsNames(); - // Also: must start with a valid character... - if (codes[ch] != 0) { - _reportUnexpectedChar(ch, "was expecting either valid name character (for unquoted name) or double-quote (for quoted) to start field name"); - } - - /* Ok, now; instead of ultra-optimizing parsing here (as with - * regular JSON names), let's just use the generic "slow" - * variant. Can measure its impact later on if need be - */ - int[] quads = _quadBuffer; - int qlen = 0; - int currQuad = 0; - int currQuadBytes = 0; - - while (true) { - // Ok, we have one more byte to add at any rate: - if (currQuadBytes < 4) { - ++currQuadBytes; - currQuad = (currQuad << 8) | ch; - } else { - if (qlen >= quads.length) { - _quadBuffer = quads = _growArrayBy(quads, quads.length); - } - quads[qlen++] = currQuad; - currQuad = ch; - currQuadBytes = 1; - } - ch = _inputData.readUnsignedByte(); - if (codes[ch] != 0) { - break; - } - } - // Note: we must "push back" character read here for future consumption - _nextByte = ch; - if (currQuadBytes > 0) { - if (qlen >= quads.length) { - _quadBuffer = quads = _growArrayBy(quads, quads.length); - } - quads[qlen++] = currQuad; - } - String name = _symbols.findName(quads, qlen); - if (name == null) { - name = addName(quads, qlen, currQuadBytes); - } - return name; - } - - /* Parsing to allow optional use of non-standard single quotes. - * Plenty of duplicated code; - * main reason being to try to avoid slowing down fast path - * for valid JSON -- more alternatives, more code, generally - * bit slower execution. - */ - protected String _parseAposName() throws IOException - { - int ch = _inputData.readUnsignedByte(); - if (ch == '\'') { // special case, '' - return ""; - } - int[] quads = _quadBuffer; - int qlen = 0; - int currQuad = 0; - int currQuadBytes = 0; - - // Copied from parseEscapedFieldName, with minor mods: - - final int[] codes = _icLatin1; - - while (true) { - if (ch == '\'') { - break; - } - // additional check to skip handling of double-quotes - if (ch != '"' && codes[ch] != 0) { - if (ch != '\\') { - // Unquoted white space? - // As per [JACKSON-208], call can now return: - _throwUnquotedSpace(ch, "name"); - } else { - // Nope, escape sequence - ch = _decodeEscaped(); - } - /* Oh crap. May need to UTF-8 (re-)encode it, if it's beyond - * 7-bit ASCII. Gets pretty messy. If this happens often, may want - * to use different name canonicalization to avoid these hits. - */ - if (ch > 127) { - // Ok, we'll need room for first byte right away - if (currQuadBytes >= 4) { - if (qlen >= quads.length) { - _quadBuffer = quads = _growArrayBy(quads, quads.length); - } - quads[qlen++] = currQuad; - currQuad = 0; - currQuadBytes = 0; - } - if (ch < 0x800) { // 2-byte - currQuad = (currQuad << 8) | (0xc0 | (ch >> 6)); - ++currQuadBytes; - // Second byte gets output below: - } else { // 3 bytes; no need to worry about surrogates here - currQuad = (currQuad << 8) | (0xe0 | (ch >> 12)); - ++currQuadBytes; - // need room for middle byte? - if (currQuadBytes >= 4) { - if (qlen >= quads.length) { - _quadBuffer = quads = _growArrayBy(quads, quads.length); - } - quads[qlen++] = currQuad; - currQuad = 0; - currQuadBytes = 0; - } - currQuad = (currQuad << 8) | (0x80 | ((ch >> 6) & 0x3f)); - ++currQuadBytes; - } - // And same last byte in both cases, gets output below: - ch = 0x80 | (ch & 0x3f); - } - } - // Ok, we have one more byte to add at any rate: - if (currQuadBytes < 4) { - ++currQuadBytes; - currQuad = (currQuad << 8) | ch; - } else { - if (qlen >= quads.length) { - _quadBuffer = quads = _growArrayBy(quads, quads.length); - } - quads[qlen++] = currQuad; - currQuad = ch; - currQuadBytes = 1; - } - ch = _inputData.readUnsignedByte(); - } - - if (currQuadBytes > 0) { - if (qlen >= quads.length) { - _quadBuffer = quads = _growArrayBy(quads, quads.length); - } - quads[qlen++] = pad(currQuad, currQuadBytes); - } - String name = _symbols.findName(quads, qlen); - if (name == null) { - name = addName(quads, qlen, currQuadBytes); - } - return name; - } - - /* - /********************************************************** - /* Internal methods, symbol (name) handling - /********************************************************** - */ - - private final String findName(int q1, int lastQuadBytes) throws JsonParseException - { - q1 = pad(q1, lastQuadBytes); - // Usually we'll find it from the canonical symbol table already - String name = _symbols.findName(q1); - if (name != null) { - return name; - } - // If not, more work. We'll need add stuff to buffer - _quadBuffer[0] = q1; - return addName(_quadBuffer, 1, lastQuadBytes); - } - - private final String findName(int q1, int q2, int lastQuadBytes) throws JsonParseException - { - q2 = pad(q2, lastQuadBytes); - // Usually we'll find it from the canonical symbol table already - String name = _symbols.findName(q1, q2); - if (name != null) { - return name; - } - // If not, more work. We'll need add stuff to buffer - _quadBuffer[0] = q1; - _quadBuffer[1] = q2; - return addName(_quadBuffer, 2, lastQuadBytes); - } - - private final String findName(int q1, int q2, int q3, int lastQuadBytes) throws JsonParseException - { - q3 = pad(q3, lastQuadBytes); - String name = _symbols.findName(q1, q2, q3); - if (name != null) { - return name; - } - int[] quads = _quadBuffer; - quads[0] = q1; - quads[1] = q2; - quads[2] = pad(q3, lastQuadBytes); - return addName(quads, 3, lastQuadBytes); - } - - private final String findName(int[] quads, int qlen, int lastQuad, int lastQuadBytes) throws JsonParseException - { - if (qlen >= quads.length) { - _quadBuffer = quads = _growArrayBy(quads, quads.length); - } - quads[qlen++] = pad(lastQuad, lastQuadBytes); - String name = _symbols.findName(quads, qlen); - if (name == null) { - return addName(quads, qlen, lastQuadBytes); - } - return name; - } - - /** - * This is the main workhorse method used when we take a symbol - * table miss. It needs to demultiplex individual bytes, decode - * multi-byte chars (if any), and then construct Name instance - * and add it to the symbol table. - */ - private final String addName(int[] quads, int qlen, int lastQuadBytes) throws JsonParseException - { - /* Ok: must decode UTF-8 chars. No other validation is - * needed, since unescaping has been done earlier as necessary - * (as well as error reporting for unescaped control chars) - */ - // 4 bytes per quad, except last one maybe less - int byteLen = (qlen << 2) - 4 + lastQuadBytes; - - /* And last one is not correctly aligned (leading zero bytes instead - * need to shift a bit, instead of trailing). Only need to shift it - * for UTF-8 decoding; need revert for storage (since key will not - * be aligned, to optimize lookup speed) - */ - int lastQuad; - - if (lastQuadBytes < 4) { - lastQuad = quads[qlen-1]; - // 8/16/24 bit left shift - quads[qlen-1] = (lastQuad << ((4 - lastQuadBytes) << 3)); - } else { - lastQuad = 0; - } - - // Need some working space, TextBuffer works well: - char[] cbuf = _textBuffer.emptyAndGetCurrentSegment(); - int cix = 0; - - for (int ix = 0; ix < byteLen; ) { - int ch = quads[ix >> 2]; // current quad, need to shift+mask - int byteIx = (ix & 3); - ch = (ch >> ((3 - byteIx) << 3)) & 0xFF; - ++ix; - - if (ch > 127) { // multi-byte - int needed; - if ((ch & 0xE0) == 0xC0) { // 2 bytes (0x0080 - 0x07FF) - ch &= 0x1F; - needed = 1; - } else if ((ch & 0xF0) == 0xE0) { // 3 bytes (0x0800 - 0xFFFF) - ch &= 0x0F; - needed = 2; - } else if ((ch & 0xF8) == 0xF0) { // 4 bytes; double-char with surrogates and all... - ch &= 0x07; - needed = 3; - } else { // 5- and 6-byte chars not valid xml chars - _reportInvalidInitial(ch); - needed = ch = 1; // never really gets this far - } - if ((ix + needed) > byteLen) { - _reportInvalidEOF(" in field name", JsonToken.FIELD_NAME); - } - - // Ok, always need at least one more: - int ch2 = quads[ix >> 2]; // current quad, need to shift+mask - byteIx = (ix & 3); - ch2 = (ch2 >> ((3 - byteIx) << 3)); - ++ix; - - if ((ch2 & 0xC0) != 0x080) { - _reportInvalidOther(ch2); - } - ch = (ch << 6) | (ch2 & 0x3F); - if (needed > 1) { - ch2 = quads[ix >> 2]; - byteIx = (ix & 3); - ch2 = (ch2 >> ((3 - byteIx) << 3)); - ++ix; - - if ((ch2 & 0xC0) != 0x080) { - _reportInvalidOther(ch2); - } - ch = (ch << 6) | (ch2 & 0x3F); - if (needed > 2) { // 4 bytes? (need surrogates on output) - ch2 = quads[ix >> 2]; - byteIx = (ix & 3); - ch2 = (ch2 >> ((3 - byteIx) << 3)); - ++ix; - if ((ch2 & 0xC0) != 0x080) { - _reportInvalidOther(ch2 & 0xFF); - } - ch = (ch << 6) | (ch2 & 0x3F); - } - } - if (needed > 2) { // surrogate pair? once again, let's output one here, one later on - ch -= 0x10000; // to normalize it starting with 0x0 - if (cix >= cbuf.length) { - cbuf = _textBuffer.expandCurrentSegment(); - } - cbuf[cix++] = (char) (0xD800 + (ch >> 10)); - ch = 0xDC00 | (ch & 0x03FF); - } - } - if (cix >= cbuf.length) { - cbuf = _textBuffer.expandCurrentSegment(); - } - cbuf[cix++] = (char) ch; - } - - // Ok. Now we have the character array, and can construct the String - String baseName = new String(cbuf, 0, cix); - // And finally, un-align if necessary - if (lastQuadBytes < 4) { - quads[qlen-1] = lastQuad; - } - return _symbols.addName(baseName, quads, qlen); - } - - /* - /********************************************************** - /* Internal methods, String value parsing - /********************************************************** - */ - - @Override - protected void _finishString() throws IOException - { - int outPtr = 0; - char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); - final int[] codes = _icUTF8; - final int outEnd = outBuf.length; - - do { - int c = _inputData.readUnsignedByte(); - if (codes[c] != 0) { - if (c == INT_QUOTE) { - _textBuffer.setCurrentLength(outPtr); - return; - } - _finishString2(outBuf, outPtr, c); - return; - } - outBuf[outPtr++] = (char) c; - } while (outPtr < outEnd); - _finishString2(outBuf, outPtr, _inputData.readUnsignedByte()); - } - - private String _finishAndReturnString() throws IOException - { - int outPtr = 0; - char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); - final int[] codes = _icUTF8; - final int outEnd = outBuf.length; - - do { - int c = _inputData.readUnsignedByte(); - if (codes[c] != 0) { - if (c == INT_QUOTE) { - return _textBuffer.setCurrentAndReturn(outPtr); - } - _finishString2(outBuf, outPtr, c); - return _textBuffer.contentsAsString(); - } - outBuf[outPtr++] = (char) c; - } while (outPtr < outEnd); - _finishString2(outBuf, outPtr, _inputData.readUnsignedByte()); - return _textBuffer.contentsAsString(); - } - - private final void _finishString2(char[] outBuf, int outPtr, int c) - throws IOException - { - // Here we do want to do full decoding, hence: - final int[] codes = _icUTF8; - int outEnd = outBuf.length; - - main_loop: - for (;; c = _inputData.readUnsignedByte()) { - // Then the tight ASCII non-funny-char loop: - while (codes[c] == 0) { - if (outPtr >= outEnd) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - outEnd = outBuf.length; - } - outBuf[outPtr++] = (char) c; - c = _inputData.readUnsignedByte(); - } - // Ok: end marker, escape or multi-byte? - if (c == INT_QUOTE) { - break main_loop; - } - switch (codes[c]) { - case 1: // backslash - c = _decodeEscaped(); - break; - case 2: // 2-byte UTF - c = _decodeUtf8_2(c); - break; - case 3: // 3-byte UTF - c = _decodeUtf8_3(c); - break; - case 4: // 4-byte UTF - c = _decodeUtf8_4(c); - // Let's add first part right away: - outBuf[outPtr++] = (char) (0xD800 | (c >> 10)); - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - outEnd = outBuf.length; - } - c = 0xDC00 | (c & 0x3FF); - // And let the other char output down below - break; - default: - if (c < INT_SPACE) { - _throwUnquotedSpace(c, "string value"); - } else { - // Is this good enough error message? - _reportInvalidChar(c); - } - } - // Need more room? - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - outEnd = outBuf.length; - } - // Ok, let's add char to output: - outBuf[outPtr++] = (char) c; - } - _textBuffer.setCurrentLength(outPtr); - } - - /** - * Method called to skim through rest of unparsed String value, - * if it is not needed. This can be done bit faster if contents - * need not be stored for future access. - */ - protected void _skipString() throws IOException - { - _tokenIncomplete = false; - - // Need to be fully UTF-8 aware here: - final int[] codes = _icUTF8; - - main_loop: - while (true) { - int c; - - ascii_loop: - while (true) { - c = _inputData.readUnsignedByte(); - if (codes[c] != 0) { - break ascii_loop; - } - } - // Ok: end marker, escape or multi-byte? - if (c == INT_QUOTE) { - break main_loop; - } - - switch (codes[c]) { - case 1: // backslash - _decodeEscaped(); - break; - case 2: // 2-byte UTF - _skipUtf8_2(); - break; - case 3: // 3-byte UTF - _skipUtf8_3(); - break; - case 4: // 4-byte UTF - _skipUtf8_4(); - break; - default: - if (c < INT_SPACE) { - _throwUnquotedSpace(c, "string value"); - } else { - // Is this good enough error message? - _reportInvalidChar(c); - } - } - } - } - - /** - * Method for handling cases where first non-space character - * of an expected value token is not legal for standard JSON content. - */ - protected JsonToken _handleUnexpectedValue(int c) - throws IOException - { - // Most likely an error, unless we are to allow single-quote-strings - switch (c) { - case ']': - if (!_parsingContext.inArray()) { - break; - } - // fall through - case ',': - /* !!! TODO: 08-May-2016, tatu: To support `Feature.ALLOW_MISSING_VALUES` would - * need handling here... - */ - if (isEnabled(Feature.ALLOW_MISSING_VALUES)) { -// _inputPtr--; - _nextByte = c; - return JsonToken.VALUE_NULL; - } - // fall through - case '}': - // Error: neither is valid at this point; valid closers have - // been handled earlier - _reportUnexpectedChar(c, "expected a value"); - case '\'': - if (isEnabled(Feature.ALLOW_SINGLE_QUOTES)) { - return _handleApos(); - } - break; - case 'N': - _matchToken("NaN", 1); - if (isEnabled(Feature.ALLOW_NON_NUMERIC_NUMBERS)) { - return resetAsNaN("NaN", Double.NaN); - } - _reportError("Non-standard token 'NaN': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow"); - break; - case 'I': - _matchToken("Infinity", 1); - if (isEnabled(Feature.ALLOW_NON_NUMERIC_NUMBERS)) { - return resetAsNaN("Infinity", Double.POSITIVE_INFINITY); - } - _reportError("Non-standard token 'Infinity': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow"); - break; - case '+': // note: '-' is taken as number - return _handleInvalidNumberStart(_inputData.readUnsignedByte(), false); - } - // [core#77] Try to decode most likely token - if (Character.isJavaIdentifierStart(c)) { - _reportInvalidToken(c, ""+((char) c), "('true', 'false' or 'null')"); - } - // but if it doesn't look like a token: - _reportUnexpectedChar(c, "expected a valid value (number, String, array, object, 'true', 'false' or 'null')"); - return null; - } - - protected JsonToken _handleApos() throws IOException - { - int c = 0; - // Otherwise almost verbatim copy of _finishString() - int outPtr = 0; - char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); - - // Here we do want to do full decoding, hence: - final int[] codes = _icUTF8; - - main_loop: - while (true) { - // Then the tight ascii non-funny-char loop: - ascii_loop: - while (true) { - int outEnd = outBuf.length; - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - outEnd = outBuf.length; - } - do { - c = _inputData.readUnsignedByte(); - if (c == '\'') { - break main_loop; - } - if (codes[c] != 0) { - break ascii_loop; - } - outBuf[outPtr++] = (char) c; - } while (outPtr < outEnd); - } - switch (codes[c]) { - case 1: // backslash - c = _decodeEscaped(); - break; - case 2: // 2-byte UTF - c = _decodeUtf8_2(c); - break; - case 3: // 3-byte UTF - c = _decodeUtf8_3(c); - break; - case 4: // 4-byte UTF - c = _decodeUtf8_4(c); - // Let's add first part right away: - outBuf[outPtr++] = (char) (0xD800 | (c >> 10)); - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - c = 0xDC00 | (c & 0x3FF); - // And let the other char output down below - break; - default: - if (c < INT_SPACE) { - _throwUnquotedSpace(c, "string value"); - } - // Is this good enough error message? - _reportInvalidChar(c); - } - // Need more room? - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - // Ok, let's add char to output: - outBuf[outPtr++] = (char) c; - } - _textBuffer.setCurrentLength(outPtr); - - return JsonToken.VALUE_STRING; - } - - /** - * Method called if expected numeric value (due to leading sign) does not - * look like a number - */ - protected JsonToken _handleInvalidNumberStart(int ch, boolean neg) - throws IOException - { - while (ch == 'I') { - ch = _inputData.readUnsignedByte(); - String match; - if (ch == 'N') { - match = neg ? "-INF" :"+INF"; - } else if (ch == 'n') { - match = neg ? "-Infinity" :"+Infinity"; - } else { - break; - } - _matchToken(match, 3); - if (isEnabled(Feature.ALLOW_NON_NUMERIC_NUMBERS)) { - return resetAsNaN(match, neg ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY); - } - _reportError("Non-standard token '"+match+"': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow"); - } - reportUnexpectedNumberChar(ch, "expected digit (0-9) to follow minus sign, for valid numeric value"); - return null; - } - - protected final void _matchToken(String matchStr, int i) throws IOException - { - final int len = matchStr.length(); - do { - int ch = _inputData.readUnsignedByte(); - if (ch != matchStr.charAt(i)) { - _reportInvalidToken(ch, matchStr.substring(0, i)); - } - } while (++i < len); - - int ch = _inputData.readUnsignedByte(); - if (ch >= '0' && ch != ']' && ch != '}') { // expected/allowed chars - _checkMatchEnd(matchStr, i, ch); - } - _nextByte = ch; - } - - private final void _checkMatchEnd(String matchStr, int i, int ch) throws IOException { - // but actually only alphanums are problematic - char c = (char) _decodeCharForError(ch); - if (Character.isJavaIdentifierPart(c)) { - _reportInvalidToken(c, matchStr.substring(0, i)); - } - } - - /* - /********************************************************** - /* Internal methods, ws skipping, escape/unescape - /********************************************************** - */ - - private final int _skipWS() throws IOException - { - int i = _nextByte; - if (i < 0) { - i = _inputData.readUnsignedByte(); - } else { - _nextByte = -1; - } - while (true) { - if (i > INT_SPACE) { - if (i == INT_SLASH || i == INT_HASH) { - return _skipWSComment(i); - } - return i; - } else { - // 06-May-2016, tatu: Could verify validity of WS, but for now why bother. - // ... but line number is useful thingy - if (i == INT_CR || i == INT_LF) { - ++_currInputRow; - } - } - i = _inputData.readUnsignedByte(); - } - } - - /** - * Alternative to {@link #_skipWS} that handles possible {@link EOFException} - * caused by trying to read past the end of {@link InputData}. - * - * @since 2.9 - */ - private final int _skipWSOrEnd() throws IOException - { - int i = _nextByte; - if (i < 0) { - try { - i = _inputData.readUnsignedByte(); - } catch (EOFException e) { - return _eofAsNextChar(); - } - } else { - _nextByte = -1; - } - while (true) { - if (i > INT_SPACE) { - if (i == INT_SLASH || i == INT_HASH) { - return _skipWSComment(i); - } - return i; - } else { - // 06-May-2016, tatu: Could verify validity of WS, but for now why bother. - // ... but line number is useful thingy - if (i == INT_CR || i == INT_LF) { - ++_currInputRow; - } - } - try { - i = _inputData.readUnsignedByte(); - } catch (EOFException e) { - return _eofAsNextChar(); - } - } - } - - private final int _skipWSComment(int i) throws IOException - { - while (true) { - if (i > INT_SPACE) { - if (i == INT_SLASH) { - _skipComment(); - } else if (i == INT_HASH) { - if (!_skipYAMLComment()) { - return i; - } - } else { - return i; - } - } else { - // 06-May-2016, tatu: Could verify validity of WS, but for now why bother. - // ... but line number is useful thingy - if (i == INT_CR || i == INT_LF) { - ++_currInputRow; - } - /* - if ((i != INT_SPACE) && (i != INT_LF) && (i != INT_CR)) { - _throwInvalidSpace(i); - } - */ - } - i = _inputData.readUnsignedByte(); - } - } - - private final int _skipColon() throws IOException - { - int i = _nextByte; - if (i < 0) { - i = _inputData.readUnsignedByte(); - } else { - _nextByte = -1; - } - // Fast path: colon with optional single-space/tab before and/or after: - if (i == INT_COLON) { // common case, no leading space - i = _inputData.readUnsignedByte(); - if (i > INT_SPACE) { // nor trailing - if (i == INT_SLASH || i == INT_HASH) { - return _skipColon2(i, true); - } - return i; - } - if (i == INT_SPACE || i == INT_TAB) { - i = _inputData.readUnsignedByte(); - if (i > INT_SPACE) { - if (i == INT_SLASH || i == INT_HASH) { - return _skipColon2(i, true); - } - return i; - } - } - return _skipColon2(i, true); // true -> skipped colon - } - if (i == INT_SPACE || i == INT_TAB) { - i = _inputData.readUnsignedByte(); - } - if (i == INT_COLON) { - i = _inputData.readUnsignedByte(); - if (i > INT_SPACE) { - if (i == INT_SLASH || i == INT_HASH) { - return _skipColon2(i, true); - } - return i; - } - if (i == INT_SPACE || i == INT_TAB) { - i = _inputData.readUnsignedByte(); - if (i > INT_SPACE) { - if (i == INT_SLASH || i == INT_HASH) { - return _skipColon2(i, true); - } - return i; - } - } - return _skipColon2(i, true); - } - return _skipColon2(i, false); - } - - private final int _skipColon2(int i, boolean gotColon) throws IOException - { - for (;; i = _inputData.readUnsignedByte()) { - if (i > INT_SPACE) { - if (i == INT_SLASH) { - _skipComment(); - continue; - } - if (i == INT_HASH) { - if (_skipYAMLComment()) { - continue; - } - } - if (gotColon) { - return i; - } - if (i != INT_COLON) { - _reportUnexpectedChar(i, "was expecting a colon to separate field name and value"); - } - gotColon = true; - } else { - // 06-May-2016, tatu: Could verify validity of WS, but for now why bother. - // ... but line number is useful thingy - if (i == INT_CR || i == INT_LF) { - ++_currInputRow; - } - } - } - } - - private final void _skipComment() throws IOException - { - if (!isEnabled(Feature.ALLOW_COMMENTS)) { - _reportUnexpectedChar('/', "maybe a (non-standard) comment? (not recognized as one since Feature 'ALLOW_COMMENTS' not enabled for parser)"); - } - int c = _inputData.readUnsignedByte(); - if (c == '/') { - _skipLine(); - } else if (c == '*') { - _skipCComment(); - } else { - _reportUnexpectedChar(c, "was expecting either '*' or '/' for a comment"); - } - } - - private final void _skipCComment() throws IOException - { - // Need to be UTF-8 aware here to decode content (for skipping) - final int[] codes = CharTypes.getInputCodeComment(); - int i = _inputData.readUnsignedByte(); - - // Ok: need the matching '*/' - main_loop: - while (true) { - int code = codes[i]; - if (code != 0) { - switch (code) { - case '*': - i = _inputData.readUnsignedByte(); - if (i == INT_SLASH) { - return; - } - continue main_loop; - case INT_LF: - case INT_CR: - ++_currInputRow; - break; - case 2: // 2-byte UTF - _skipUtf8_2(); - break; - case 3: // 3-byte UTF - _skipUtf8_3(); - break; - case 4: // 4-byte UTF - _skipUtf8_4(); - break; - default: // e.g. -1 - // Is this good enough error message? - _reportInvalidChar(i); - } - } - i = _inputData.readUnsignedByte(); - } - } - - private final boolean _skipYAMLComment() throws IOException - { - if (!isEnabled(Feature.ALLOW_YAML_COMMENTS)) { - return false; - } - _skipLine(); - return true; - } - - /** - * Method for skipping contents of an input line; usually for CPP - * and YAML style comments. - */ - private final void _skipLine() throws IOException - { - // Ok: need to find EOF or linefeed - final int[] codes = CharTypes.getInputCodeComment(); - while (true) { - int i = _inputData.readUnsignedByte(); - int code = codes[i]; - if (code != 0) { - switch (code) { - case INT_LF: - case INT_CR: - ++_currInputRow; - return; - case '*': // nop for these comments - break; - case 2: // 2-byte UTF - _skipUtf8_2(); - break; - case 3: // 3-byte UTF - _skipUtf8_3(); - break; - case 4: // 4-byte UTF - _skipUtf8_4(); - break; - default: // e.g. -1 - if (code < 0) { - // Is this good enough error message? - _reportInvalidChar(i); - } - } - } - } - } - - @Override - protected char _decodeEscaped() throws IOException - { - int c = _inputData.readUnsignedByte(); - - switch (c) { - // First, ones that are mapped - case 'b': - return '\b'; - case 't': - return '\t'; - case 'n': - return '\n'; - case 'f': - return '\f'; - case 'r': - return '\r'; - - // And these are to be returned as they are - case '"': - case '/': - case '\\': - return (char) c; - - case 'u': // and finally hex-escaped - break; - - default: - return _handleUnrecognizedCharacterEscape((char) _decodeCharForError(c)); - } - - // Ok, a hex escape. Need 4 characters - int value = 0; - for (int i = 0; i < 4; ++i) { - int ch = _inputData.readUnsignedByte(); - int digit = CharTypes.charToHex(ch); - if (digit < 0) { - _reportUnexpectedChar(ch, "expected a hex-digit for character escape sequence"); - } - value = (value << 4) | digit; - } - return (char) value; - } - - protected int _decodeCharForError(int firstByte) throws IOException - { - int c = firstByte & 0xFF; - if (c > 0x7F) { // if >= 0, is ascii and fine as is - int needed; - - // Ok; if we end here, we got multi-byte combination - if ((c & 0xE0) == 0xC0) { // 2 bytes (0x0080 - 0x07FF) - c &= 0x1F; - needed = 1; - } else if ((c & 0xF0) == 0xE0) { // 3 bytes (0x0800 - 0xFFFF) - c &= 0x0F; - needed = 2; - } else if ((c & 0xF8) == 0xF0) { - // 4 bytes; double-char with surrogates and all... - c &= 0x07; - needed = 3; - } else { - _reportInvalidInitial(c & 0xFF); - needed = 1; // never gets here - } - - int d = _inputData.readUnsignedByte(); - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF); - } - c = (c << 6) | (d & 0x3F); - - if (needed > 1) { // needed == 1 means 2 bytes total - d = _inputData.readUnsignedByte(); // 3rd byte - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF); - } - c = (c << 6) | (d & 0x3F); - if (needed > 2) { // 4 bytes? (need surrogates) - d = _inputData.readUnsignedByte(); - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF); - } - c = (c << 6) | (d & 0x3F); - } - } - } - return c; - } - - /* - /********************************************************** - /* Internal methods,UTF8 decoding - /********************************************************** - */ - - private final int _decodeUtf8_2(int c) throws IOException - { - int d = _inputData.readUnsignedByte(); - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF); - } - return ((c & 0x1F) << 6) | (d & 0x3F); - } - - private final int _decodeUtf8_3(int c1) throws IOException - { - c1 &= 0x0F; - int d = _inputData.readUnsignedByte(); - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF); - } - int c = (c1 << 6) | (d & 0x3F); - d = _inputData.readUnsignedByte(); - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF); - } - c = (c << 6) | (d & 0x3F); - return c; - } - - /** - * @return Character value minus 0x10000; this so that caller - * can readily expand it to actual surrogates - */ - private final int _decodeUtf8_4(int c) throws IOException - { - int d = _inputData.readUnsignedByte(); - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF); - } - c = ((c & 0x07) << 6) | (d & 0x3F); - d = _inputData.readUnsignedByte(); - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF); - } - c = (c << 6) | (d & 0x3F); - d = _inputData.readUnsignedByte(); - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF); - } - - /* note: won't change it to negative here, since caller - * already knows it'll need a surrogate - */ - return ((c << 6) | (d & 0x3F)) - 0x10000; - } - - private final void _skipUtf8_2() throws IOException - { - int c = _inputData.readUnsignedByte(); - if ((c & 0xC0) != 0x080) { - _reportInvalidOther(c & 0xFF); - } - } - - /* Alas, can't heavily optimize skipping, since we still have to - * do validity checks... - */ - private final void _skipUtf8_3() throws IOException - { - //c &= 0x0F; - int c = _inputData.readUnsignedByte(); - if ((c & 0xC0) != 0x080) { - _reportInvalidOther(c & 0xFF); - } - c = _inputData.readUnsignedByte(); - if ((c & 0xC0) != 0x080) { - _reportInvalidOther(c & 0xFF); - } - } - - private final void _skipUtf8_4() throws IOException - { - int d = _inputData.readUnsignedByte(); - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF); - } - d = _inputData.readUnsignedByte(); - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF); - } - d = _inputData.readUnsignedByte(); - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF); - } - } - - /* - /********************************************************** - /* Internal methods, error reporting - /********************************************************** - */ - - protected void _reportInvalidToken(int ch, String matchedPart) throws IOException - { - _reportInvalidToken(ch, matchedPart, "'null', 'true', 'false' or NaN"); - } - - protected void _reportInvalidToken(int ch, String matchedPart, String msg) - throws IOException - { - StringBuilder sb = new StringBuilder(matchedPart); - - /* Let's just try to find what appears to be the token, using - * regular Java identifier character rules. It's just a heuristic, - * nothing fancy here (nor fast). - */ - while (true) { - char c = (char) _decodeCharForError(ch); - if (!Character.isJavaIdentifierPart(c)) { - break; - } - sb.append(c); - ch = _inputData.readUnsignedByte(); - } - _reportError("Unrecognized token '"+sb.toString()+"': was expecting "+msg); - } - - protected void _reportInvalidChar(int c) - throws JsonParseException - { - // Either invalid WS or illegal UTF-8 start char - if (c < INT_SPACE) { - _throwInvalidSpace(c); - } - _reportInvalidInitial(c); - } - - protected void _reportInvalidInitial(int mask) - throws JsonParseException - { - _reportError("Invalid UTF-8 start byte 0x"+Integer.toHexString(mask)); - } - - private void _reportInvalidOther(int mask) - throws JsonParseException - { - _reportError("Invalid UTF-8 middle byte 0x"+Integer.toHexString(mask)); - } - - private static int[] _growArrayBy(int[] arr, int more) - { - if (arr == null) { - return new int[more]; - } - return Arrays.copyOf(arr, arr.length + more); - } - - /* - /********************************************************** - /* Internal methods, binary access - /********************************************************** - */ - - /** - * Efficient handling for incremental parsing of base64-encoded - * textual content. - */ - protected final byte[] _decodeBase64(Base64Variant b64variant) throws IOException - { - ByteArrayBuilder builder = _getByteArrayBuilder(); - - //main_loop: - while (true) { - // first, we'll skip preceding white space, if any - int ch; - do { - ch = _inputData.readUnsignedByte(); - } while (ch <= INT_SPACE); - int bits = b64variant.decodeBase64Char(ch); - if (bits < 0) { // reached the end, fair and square? - if (ch == INT_QUOTE) { - return builder.toByteArray(); - } - bits = _decodeBase64Escape(b64variant, ch, 0); - if (bits < 0) { // white space to skip - continue; - } - } - int decodedData = bits; - - // then second base64 char; can't get padding yet, nor ws - ch = _inputData.readUnsignedByte(); - bits = b64variant.decodeBase64Char(ch); - if (bits < 0) { - bits = _decodeBase64Escape(b64variant, ch, 1); - } - decodedData = (decodedData << 6) | bits; - // third base64 char; can be padding, but not ws - ch = _inputData.readUnsignedByte(); - bits = b64variant.decodeBase64Char(ch); - - // First branch: can get padding (-> 1 byte) - if (bits < 0) { - if (bits != Base64Variant.BASE64_VALUE_PADDING) { - // could also just be 'missing' padding - if (ch == '"' && !b64variant.usesPadding()) { - decodedData >>= 4; - builder.append(decodedData); - return builder.toByteArray(); - } - bits = _decodeBase64Escape(b64variant, ch, 2); - } - if (bits == Base64Variant.BASE64_VALUE_PADDING) { - ch = _inputData.readUnsignedByte(); - if (!b64variant.usesPaddingChar(ch)) { - throw reportInvalidBase64Char(b64variant, ch, 3, "expected padding character '"+b64variant.getPaddingChar()+"'"); - } - // Got 12 bits, only need 8, need to shift - decodedData >>= 4; - builder.append(decodedData); - continue; - } - } - // Nope, 2 or 3 bytes - decodedData = (decodedData << 6) | bits; - // fourth and last base64 char; can be padding, but not ws - ch = _inputData.readUnsignedByte(); - bits = b64variant.decodeBase64Char(ch); - if (bits < 0) { - if (bits != Base64Variant.BASE64_VALUE_PADDING) { - // could also just be 'missing' padding - if (ch == '"' && !b64variant.usesPadding()) { - decodedData >>= 2; - builder.appendTwoBytes(decodedData); - return builder.toByteArray(); - } - bits = _decodeBase64Escape(b64variant, ch, 3); - } - if (bits == Base64Variant.BASE64_VALUE_PADDING) { - /* With padding we only get 2 bytes; but we have - * to shift it a bit so it is identical to triplet - * case with partial output. - * 3 chars gives 3x6 == 18 bits, of which 2 are - * dummies, need to discard: - */ - decodedData >>= 2; - builder.appendTwoBytes(decodedData); - continue; - } - } - // otherwise, our triplet is now complete - decodedData = (decodedData << 6) | bits; - builder.appendThreeBytes(decodedData); - } - } - - /* - /********************************************************** - /* Improved location updating (refactored in 2.7) - /********************************************************** - */ - - @Override - public JsonLocation getTokenLocation() { - final Object src = _ioContext.getSourceReference(); - return new JsonLocation(src, - -1L, -1L, _tokenInputRow, -1); - } - - @Override - public JsonLocation getCurrentLocation() { - final Object src = _ioContext.getSourceReference(); - return new JsonLocation(src, - -1L, -1L, _currInputRow, -1); - } - - /* - /********************************************************** - /* Internal methods, other - /********************************************************** - */ - - private void _closeScope(int i) throws JsonParseException { - if (i == INT_RBRACKET) { - if (!_parsingContext.inArray()) { - _reportMismatchedEndMarker(i, '}'); - } - _parsingContext = _parsingContext.clearAndGetParent(); - _currToken = JsonToken.END_ARRAY; - } - if (i == INT_RCURLY) { - if (!_parsingContext.inObject()) { - _reportMismatchedEndMarker(i, ']'); - } - _parsingContext = _parsingContext.clearAndGetParent(); - _currToken = JsonToken.END_OBJECT; - } - } - - /** - * Helper method needed to fix [Issue#148], masking of 0x00 character - */ - private final static int pad(int q, int bytes) { - return (bytes == 4) ? q : (q | (-1 << (bytes << 3))); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/UTF8JsonGenerator.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/UTF8JsonGenerator.java deleted file mode 100644 index c7c92463..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/UTF8JsonGenerator.java +++ /dev/null @@ -1,2045 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.json; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.math.BigDecimal; -import java.math.BigInteger; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.Base64Variant; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonStreamContext; -import autosaveworld.zlibs.com.fasterxml.jackson.core.ObjectCodec; -import autosaveworld.zlibs.com.fasterxml.jackson.core.SerializableString; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.CharTypes; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.CharacterEscapes; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.IOContext; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.NumberOutput; - -public class UTF8JsonGenerator - extends JsonGeneratorImpl -{ - private final static byte BYTE_u = (byte) 'u'; - - private final static byte BYTE_0 = (byte) '0'; - - private final static byte BYTE_LBRACKET = (byte) '['; - private final static byte BYTE_RBRACKET = (byte) ']'; - private final static byte BYTE_LCURLY = (byte) '{'; - private final static byte BYTE_RCURLY = (byte) '}'; - - private final static byte BYTE_BACKSLASH = (byte) '\\'; - private final static byte BYTE_COMMA = (byte) ','; - private final static byte BYTE_COLON = (byte) ':'; - - // intermediate copies only made up to certain length... - private final static int MAX_BYTES_TO_BUFFER = 512; - - private final static byte[] HEX_CHARS = CharTypes.copyHexBytes(); - - private final static byte[] NULL_BYTES = { 'n', 'u', 'l', 'l' }; - private final static byte[] TRUE_BYTES = { 't', 'r', 'u', 'e' }; - private final static byte[] FALSE_BYTES = { 'f', 'a', 'l', 's', 'e' }; - - /* - /********************************************************** - /* Configuration - /********************************************************** - */ - - /** - * Underlying output stream used for writing JSON content. - */ - final protected OutputStream _outputStream; - - /** - * Character used for quoting JSON Object property names - * and String values. - * - * @since 2.8 - */ - protected byte _quoteChar = '"'; // TODO: make configurable - - /* - /********************************************************** - /* Output buffering - /********************************************************** - */ - - /** - * Intermediate buffer in which contents are buffered before - * being written using {@link #_outputStream}. - */ - protected byte[] _outputBuffer; - - /** - * Pointer to the position right beyond the last character to output - * (end marker; may be past the buffer) - */ - protected int _outputTail; - - /** - * End marker of the output buffer; one past the last valid position - * within the buffer. - */ - protected final int _outputEnd; - - /** - * Maximum number of chars that we know will always fit - * in the output buffer after escaping - */ - protected final int _outputMaxContiguous; - - /** - * Intermediate buffer in which characters of a String are copied - * before being encoded. - */ - protected char[] _charBuffer; - - /** - * Length of _charBuffer - */ - protected final int _charBufferLength; - - /** - * 6 character temporary buffer allocated if needed, for constructing - * escape sequences - */ - protected byte[] _entityBuffer; - - /** - * Flag that indicates whether the output buffer is recycable (and - * needs to be returned to recycler once we are done) or not. - */ - protected boolean _bufferRecyclable; - - /* - /********************************************************** - /* Life-cycle - /********************************************************** - */ - - public UTF8JsonGenerator(IOContext ctxt, int features, ObjectCodec codec, - OutputStream out) - { - super(ctxt, features, codec); - _outputStream = out; - _bufferRecyclable = true; - _outputBuffer = ctxt.allocWriteEncodingBuffer(); - _outputEnd = _outputBuffer.length; - - /* To be exact, each char can take up to 6 bytes when escaped (Unicode - * escape with backslash, 'u' and 4 hex digits); but to avoid fluctuation, - * we will actually round down to only do up to 1/8 number of chars - */ - _outputMaxContiguous = _outputEnd >> 3; - _charBuffer = ctxt.allocConcatBuffer(); - _charBufferLength = _charBuffer.length; - - // By default we use this feature to determine additional quoting - if (isEnabled(Feature.ESCAPE_NON_ASCII)) { - setHighestNonEscapedChar(127); - } - } - - public UTF8JsonGenerator(IOContext ctxt, int features, ObjectCodec codec, - OutputStream out, - byte[] outputBuffer, int outputOffset, boolean bufferRecyclable) - { - - super(ctxt, features, codec); - _outputStream = out; - _bufferRecyclable = bufferRecyclable; - _outputTail = outputOffset; - _outputBuffer = outputBuffer; - _outputEnd = _outputBuffer.length; - // up to 6 bytes per char (see above), rounded up to 1/8 - _outputMaxContiguous = (_outputEnd >> 3); - _charBuffer = ctxt.allocConcatBuffer(); - _charBufferLength = _charBuffer.length; - } - - /* - /********************************************************** - /* Overridden configuration methods - /********************************************************** - */ - - @Override - public Object getOutputTarget() { - return _outputStream; - } - - @Override - public int getOutputBuffered() { - // Assuming tail is always valid, set to 0 on close - return _outputTail; - } - - /* - /********************************************************** - /* Overridden methods - /********************************************************** - */ - - @Override - public void writeFieldName(String name) throws IOException - { - if (_cfgPrettyPrinter != null) { - _writePPFieldName(name); - return; - } - final int status = _writeContext.writeFieldName(name); - if (status == JsonWriteContext.STATUS_EXPECT_VALUE) { - _reportError("Can not write a field name, expecting a value"); - } - if (status == JsonWriteContext.STATUS_OK_AFTER_COMMA) { // need comma - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = BYTE_COMMA; - } - /* To support [JACKSON-46], we'll do this: - * (Question: should quoting of spaces (etc) still be enabled?) - */ - if (_cfgUnqNames) { - _writeStringSegments(name, false); - return; - } - final int len = name.length(); - // Does it fit in buffer? - if (len > _charBufferLength) { // no, offline - _writeStringSegments(name, true); - return; - } - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - // But as one segment, or multiple? - if (len <= _outputMaxContiguous) { - if ((_outputTail + len) > _outputEnd) { // caller must ensure enough space - _flushBuffer(); - } - _writeStringSegment(name, 0, len); - } else { - _writeStringSegments(name, 0, len); - } - // and closing quotes; need room for one more char: - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } - - @Override - public void writeFieldName(SerializableString name) throws IOException - { - if (_cfgPrettyPrinter != null) { - _writePPFieldName(name); - return; - } - final int status = _writeContext.writeFieldName(name.getValue()); - if (status == JsonWriteContext.STATUS_EXPECT_VALUE) { - _reportError("Can not write a field name, expecting a value"); - } - if (status == JsonWriteContext.STATUS_OK_AFTER_COMMA) { - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = BYTE_COMMA; - } - if (_cfgUnqNames) { - _writeUnq(name); - return; - } - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - int len = name.appendQuotedUTF8(_outputBuffer, _outputTail); - if (len < 0) { // couldn't append, bit longer processing - _writeBytes(name.asQuotedUTF8()); - } else { - _outputTail += len; - } - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } - - private final void _writeUnq(SerializableString name) throws IOException { - int len = name.appendQuotedUTF8(_outputBuffer, _outputTail); - if (len < 0) { - _writeBytes(name.asQuotedUTF8()); - } else { - _outputTail += len; - } - } - - /* - /********************************************************** - /* Output method implementations, structural - /********************************************************** - */ - - @Override - public final void writeStartArray() throws IOException - { - _verifyValueWrite("start an array"); - _writeContext = _writeContext.createChildArrayContext(); - if (_cfgPrettyPrinter != null) { - _cfgPrettyPrinter.writeStartArray(this); - } else { - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = BYTE_LBRACKET; - } - } - - @Override - public final void writeEndArray() throws IOException - { - if (!_writeContext.inArray()) { - _reportError("Current context not Array but "+_writeContext.typeDesc()); - } - if (_cfgPrettyPrinter != null) { - _cfgPrettyPrinter.writeEndArray(this, _writeContext.getEntryCount()); - } else { - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = BYTE_RBRACKET; - } - _writeContext = _writeContext.clearAndGetParent(); - } - - @Override - public final void writeStartObject() throws IOException - { - _verifyValueWrite("start an object"); - _writeContext = _writeContext.createChildObjectContext(); - if (_cfgPrettyPrinter != null) { - _cfgPrettyPrinter.writeStartObject(this); - } else { - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = BYTE_LCURLY; - } - } - - @Override // since 2.8 - public void writeStartObject(Object forValue) throws IOException - { - _verifyValueWrite("start an object"); - JsonWriteContext ctxt = _writeContext.createChildObjectContext(); - _writeContext = ctxt; - if (forValue != null) { - ctxt.setCurrentValue(forValue); - } - if (_cfgPrettyPrinter != null) { - _cfgPrettyPrinter.writeStartObject(this); - } else { - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = '{'; - } - } - - @Override - public final void writeEndObject() throws IOException - { - if (!_writeContext.inObject()) { - _reportError("Current context not Object but "+_writeContext.typeDesc()); - } - if (_cfgPrettyPrinter != null) { - _cfgPrettyPrinter.writeEndObject(this, _writeContext.getEntryCount()); - } else { - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = BYTE_RCURLY; - } - _writeContext = _writeContext.clearAndGetParent(); - } - - /** - * Specialized version of _writeFieldName, off-lined - * to keep the "fast path" as simple (and hopefully fast) as possible. - */ - protected final void _writePPFieldName(String name) throws IOException - { - int status = _writeContext.writeFieldName(name); - if (status == JsonWriteContext.STATUS_EXPECT_VALUE) { - _reportError("Can not write a field name, expecting a value"); - } - if ((status == JsonWriteContext.STATUS_OK_AFTER_COMMA)) { - _cfgPrettyPrinter.writeObjectEntrySeparator(this); - } else { - _cfgPrettyPrinter.beforeObjectEntries(this); - } - if (_cfgUnqNames) { - _writeStringSegments(name, false); - return; - } - final int len = name.length(); - if (len > _charBufferLength) { - _writeStringSegments(name, true); - return; - } - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - name.getChars(0, len, _charBuffer, 0); - // But as one segment, or multiple? - if (len <= _outputMaxContiguous) { - if ((_outputTail + len) > _outputEnd) { // caller must ensure enough space - _flushBuffer(); - } - _writeStringSegment(_charBuffer, 0, len); - } else { - _writeStringSegments(_charBuffer, 0, len); - } - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } - - protected final void _writePPFieldName(SerializableString name) throws IOException - { - final int status = _writeContext.writeFieldName(name.getValue()); - if (status == JsonWriteContext.STATUS_EXPECT_VALUE) { - _reportError("Can not write a field name, expecting a value"); - } - if (status == JsonWriteContext.STATUS_OK_AFTER_COMMA) { - _cfgPrettyPrinter.writeObjectEntrySeparator(this); - } else { - _cfgPrettyPrinter.beforeObjectEntries(this); - } - - final boolean addQuotes = !_cfgUnqNames; // standard - if (addQuotes) { - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } - _writeBytes(name.asQuotedUTF8()); - if (addQuotes) { - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } - } - - /* - /********************************************************** - /* Output method implementations, textual - /********************************************************** - */ - - @Override - public void writeString(String text) throws IOException - { - _verifyValueWrite(WRITE_STRING); - if (text == null) { - _writeNull(); - return; - } - // First: if we can't guarantee it all fits, quoted, within output, offline - final int len = text.length(); - if (len > _outputMaxContiguous) { // nope: off-line handling - _writeStringSegments(text, true); - return; - } - if ((_outputTail + len) >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - _writeStringSegment(text, 0, len); // we checked space already above - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } - - @Override - public void writeString(char[] text, int offset, int len) throws IOException - { - _verifyValueWrite(WRITE_STRING); - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - // One or multiple segments? - if (len <= _outputMaxContiguous) { - if ((_outputTail + len) > _outputEnd) { // caller must ensure enough space - _flushBuffer(); - } - _writeStringSegment(text, offset, len); - } else { - _writeStringSegments(text, offset, len); - } - // And finally, closing quotes - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } - - @Override - public final void writeString(SerializableString text) throws IOException - { - _verifyValueWrite(WRITE_STRING); - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - int len = text.appendQuotedUTF8(_outputBuffer, _outputTail); - if (len < 0) { - _writeBytes(text.asQuotedUTF8()); - } else { - _outputTail += len; - } - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } - - @Override - public void writeRawUTF8String(byte[] text, int offset, int length) throws IOException - { - _verifyValueWrite(WRITE_STRING); - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - _writeBytes(text, offset, length); - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } - - @Override - public void writeUTF8String(byte[] text, int offset, int len) throws IOException - { - _verifyValueWrite(WRITE_STRING); - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - // One or multiple segments? - if (len <= _outputMaxContiguous) { - _writeUTF8Segment(text, offset, len); - } else { - _writeUTF8Segments(text, offset, len); - } - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } - - /* - /********************************************************** - /* Output method implementations, unprocessed ("raw") - /********************************************************** - */ - - @Override - public void writeRaw(String text) throws IOException { - final int len = text.length(); - final char[] buf = _charBuffer; - if (len <= buf.length) { - text.getChars(0, len, buf, 0); - writeRaw(buf, 0, len); - } else { - writeRaw(text, 0, len); - } - } - - @Override - public void writeRaw(String text, int offset, int len) throws IOException - { - final char[] buf = _charBuffer; - - // minor optimization: see if we can just get and copy - if (len <= buf.length) { - text.getChars(offset, offset+len, buf, 0); - writeRaw(buf, 0, len); - return; - } - - // If not, need segmented approach. For speed, let's also use input buffer - // size that is guaranteed to fit in output buffer; each char can expand to - // at most 3 bytes, so at most 1/3 of buffer size. - final int maxChunk = (_outputEnd >> 2) + (_outputEnd >> 4); // == (1/4 + 1/16) == 5/16 - final int maxBytes = maxChunk * 3; - - while (len > 0) { - int len2 = Math.min(maxChunk, len); - text.getChars(offset, offset+len2, buf, 0); - if ((_outputTail + maxBytes) > _outputEnd) { - _flushBuffer(); - } - // If this is NOT the last segment and if the last character looks like - // split surrogate second half, drop it - if (len > 0) { - char ch = buf[len2-1]; - if ((ch >= SURR1_FIRST) && (ch <= SURR1_LAST)) { - --len2; - } - } - _writeRawSegment(buf, 0, len2); - offset += len2; - len -= len2; - } - } - - @Override - public void writeRaw(SerializableString text) throws IOException - { - byte[] raw = text.asUnquotedUTF8(); - if (raw.length > 0) { - _writeBytes(raw); - } - } - - // since 2.5 - @Override - public void writeRawValue(SerializableString text) throws IOException { - _verifyValueWrite(WRITE_RAW); - byte[] raw = text.asUnquotedUTF8(); - if (raw.length > 0) { - _writeBytes(raw); - } - } - - // @TODO: rewrite for speed... - @Override - public final void writeRaw(char[] cbuf, int offset, int len) throws IOException - { - // First: if we have 3 x charCount spaces, we know it'll fit just fine - { - int len3 = len+len+len; - if ((_outputTail + len3) > _outputEnd) { - // maybe we could flush? - if (_outputEnd < len3) { // wouldn't be enough... - _writeSegmentedRaw(cbuf, offset, len); - return; - } - // yes, flushing brings enough space - _flushBuffer(); - } - } - len += offset; // now marks the end - - // Note: here we know there is enough room, hence no output boundary checks - main_loop: - while (offset < len) { - inner_loop: - while (true) { - int ch = (int) cbuf[offset]; - if (ch > 0x7F) { - break inner_loop; - } - _outputBuffer[_outputTail++] = (byte) ch; - if (++offset >= len) { - break main_loop; - } - } - char ch = cbuf[offset++]; - if (ch < 0x800) { // 2-byte? - _outputBuffer[_outputTail++] = (byte) (0xc0 | (ch >> 6)); - _outputBuffer[_outputTail++] = (byte) (0x80 | (ch & 0x3f)); - } else { - offset = _outputRawMultiByteChar(ch, cbuf, offset, len); - } - } - } - - @Override - public void writeRaw(char ch) throws IOException - { - if ((_outputTail + 3) >= _outputEnd) { - _flushBuffer(); - } - final byte[] bbuf = _outputBuffer; - if (ch <= 0x7F) { - bbuf[_outputTail++] = (byte) ch; - } else if (ch < 0x800) { // 2-byte? - bbuf[_outputTail++] = (byte) (0xc0 | (ch >> 6)); - bbuf[_outputTail++] = (byte) (0x80 | (ch & 0x3f)); - } else { - /*offset =*/ _outputRawMultiByteChar(ch, null, 0, 0); - } - } - - /** - * Helper method called when it is possible that output of raw section - * to output may cross buffer boundary - */ - private final void _writeSegmentedRaw(char[] cbuf, int offset, int len) throws IOException - { - final int end = _outputEnd; - final byte[] bbuf = _outputBuffer; - final int inputEnd = offset + len; - - main_loop: - while (offset < inputEnd) { - inner_loop: - while (true) { - int ch = (int) cbuf[offset]; - if (ch >= 0x80) { - break inner_loop; - } - // !!! TODO: fast(er) writes (roll input, output checks in one) - if (_outputTail >= end) { - _flushBuffer(); - } - bbuf[_outputTail++] = (byte) ch; - if (++offset >= inputEnd) { - break main_loop; - } - } - if ((_outputTail + 3) >= _outputEnd) { - _flushBuffer(); - } - char ch = cbuf[offset++]; - if (ch < 0x800) { // 2-byte? - bbuf[_outputTail++] = (byte) (0xc0 | (ch >> 6)); - bbuf[_outputTail++] = (byte) (0x80 | (ch & 0x3f)); - } else { - offset = _outputRawMultiByteChar(ch, cbuf, offset, inputEnd); - } - } - } - - /** - * Helper method that is called for segmented write of raw content - * when explicitly outputting a segment of longer thing. - * Caller has to take care of ensuring there's no split surrogate - * pair at the end (that is, last char can not be first part of a - * surrogate char pair). - * - * @since 2.8.2 - */ - private void _writeRawSegment(char[] cbuf, int offset, int end) throws IOException - { - main_loop: - while (offset < end) { - inner_loop: - while (true) { - int ch = (int) cbuf[offset]; - if (ch > 0x7F) { - break inner_loop; - } - _outputBuffer[_outputTail++] = (byte) ch; - if (++offset >= end) { - break main_loop; - } - } - char ch = cbuf[offset++]; - if (ch < 0x800) { // 2-byte? - _outputBuffer[_outputTail++] = (byte) (0xc0 | (ch >> 6)); - _outputBuffer[_outputTail++] = (byte) (0x80 | (ch & 0x3f)); - } else { - offset = _outputRawMultiByteChar(ch, cbuf, offset, end); - } - } - } - - /* - /********************************************************** - /* Output method implementations, base64-encoded binary - /********************************************************** - */ - - @Override - public void writeBinary(Base64Variant b64variant, - byte[] data, int offset, int len) - throws IOException, JsonGenerationException - { - _verifyValueWrite(WRITE_BINARY); - // Starting quotes - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - _writeBinary(b64variant, data, offset, offset+len); - // and closing quotes - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } - - @Override - public int writeBinary(Base64Variant b64variant, - InputStream data, int dataLength) - throws IOException, JsonGenerationException - { - _verifyValueWrite(WRITE_BINARY); - // Starting quotes - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - byte[] encodingBuffer = _ioContext.allocBase64Buffer(); - int bytes; - try { - if (dataLength < 0) { // length unknown - bytes = _writeBinary(b64variant, data, encodingBuffer); - } else { - int missing = _writeBinary(b64variant, data, encodingBuffer, dataLength); - if (missing > 0) { - _reportError("Too few bytes available: missing "+missing+" bytes (out of "+dataLength+")"); - } - bytes = dataLength; - } - } finally { - _ioContext.releaseBase64Buffer(encodingBuffer); - } - // and closing quotes - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - return bytes; - } - - /* - /********************************************************** - /* Output method implementations, primitive - /********************************************************** - */ - - @Override - public void writeNumber(short s) throws IOException - { - _verifyValueWrite(WRITE_NUMBER); - // up to 5 digits and possible minus sign - if ((_outputTail + 6) >= _outputEnd) { - _flushBuffer(); - } - if (_cfgNumbersAsStrings) { - _writeQuotedShort(s); - return; - } - _outputTail = NumberOutput.outputInt(s, _outputBuffer, _outputTail); - } - - private final void _writeQuotedShort(short s) throws IOException { - if ((_outputTail + 8) >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - _outputTail = NumberOutput.outputInt(s, _outputBuffer, _outputTail); - _outputBuffer[_outputTail++] = _quoteChar; - } - - @Override - public void writeNumber(int i) throws IOException - { - _verifyValueWrite(WRITE_NUMBER); - // up to 10 digits and possible minus sign - if ((_outputTail + 11) >= _outputEnd) { - _flushBuffer(); - } - if (_cfgNumbersAsStrings) { - _writeQuotedInt(i); - return; - } - _outputTail = NumberOutput.outputInt(i, _outputBuffer, _outputTail); - } - - private final void _writeQuotedInt(int i) throws IOException - { - if ((_outputTail + 13) >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - _outputTail = NumberOutput.outputInt(i, _outputBuffer, _outputTail); - _outputBuffer[_outputTail++] = _quoteChar; - } - - @Override - public void writeNumber(long l) throws IOException - { - _verifyValueWrite(WRITE_NUMBER); - if (_cfgNumbersAsStrings) { - _writeQuotedLong(l); - return; - } - if ((_outputTail + 21) >= _outputEnd) { - // up to 20 digits, minus sign - _flushBuffer(); - } - _outputTail = NumberOutput.outputLong(l, _outputBuffer, _outputTail); - } - - private final void _writeQuotedLong(long l) throws IOException - { - if ((_outputTail + 23) >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - _outputTail = NumberOutput.outputLong(l, _outputBuffer, _outputTail); - _outputBuffer[_outputTail++] = _quoteChar; - } - - @Override - public void writeNumber(BigInteger value) throws IOException - { - _verifyValueWrite(WRITE_NUMBER); - if (value == null) { - _writeNull(); - } else if (_cfgNumbersAsStrings) { - _writeQuotedRaw(value.toString()); - } else { - writeRaw(value.toString()); - } - } - - - @Override - public void writeNumber(double d) throws IOException - { - if (_cfgNumbersAsStrings || - (((Double.isNaN(d) || Double.isInfinite(d)) - && Feature.QUOTE_NON_NUMERIC_NUMBERS.enabledIn(_features)))) { - writeString(String.valueOf(d)); - return; - } - // What is the max length for doubles? 40 chars? - _verifyValueWrite(WRITE_NUMBER); - writeRaw(String.valueOf(d)); - } - - @Override - public void writeNumber(float f) throws IOException - { - if (_cfgNumbersAsStrings || - // [JACKSON-139] - (((Float.isNaN(f) || Float.isInfinite(f)) - && Feature.QUOTE_NON_NUMERIC_NUMBERS.enabledIn(_features)))) { - writeString(String.valueOf(f)); - return; - } - // What is the max length for floats? - _verifyValueWrite(WRITE_NUMBER); - writeRaw(String.valueOf(f)); - } - - @Override - public void writeNumber(BigDecimal value) throws IOException - { - // Don't really know max length for big decimal, no point checking - _verifyValueWrite(WRITE_NUMBER); - if (value == null) { - _writeNull(); - } else if (_cfgNumbersAsStrings) { - _writeQuotedRaw(_asString(value)); - } else { - writeRaw(_asString(value)); - } - } - - @Override - public void writeNumber(String encodedValue) throws IOException - { - _verifyValueWrite(WRITE_NUMBER); - if (_cfgNumbersAsStrings) { - _writeQuotedRaw(encodedValue); - } else { - writeRaw(encodedValue); - } - } - - private final void _writeQuotedRaw(String value) throws IOException - { - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - writeRaw(value); - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } - - @Override - public void writeBoolean(boolean state) throws IOException - { - _verifyValueWrite(WRITE_BOOLEAN); - if ((_outputTail + 5) >= _outputEnd) { - _flushBuffer(); - } - byte[] keyword = state ? TRUE_BYTES : FALSE_BYTES; - int len = keyword.length; - System.arraycopy(keyword, 0, _outputBuffer, _outputTail, len); - _outputTail += len; - } - - @Override - public void writeNull() throws IOException - { - _verifyValueWrite(WRITE_NULL); - _writeNull(); - } - - /* - /********************************************************** - /* Implementations for other methods - /********************************************************** - */ - - @Override - protected final void _verifyValueWrite(String typeMsg) throws IOException - { - final int status = _writeContext.writeValue(); - if (_cfgPrettyPrinter != null) { - // Otherwise, pretty printer knows what to do... - _verifyPrettyValueWrite(typeMsg, status); - return; - } - byte b; - switch (status) { - case JsonWriteContext.STATUS_OK_AS_IS: - default: - return; - case JsonWriteContext.STATUS_OK_AFTER_COMMA: - b = BYTE_COMMA; - break; - case JsonWriteContext.STATUS_OK_AFTER_COLON: - b = BYTE_COLON; - break; - case JsonWriteContext.STATUS_OK_AFTER_SPACE: // root-value separator - if (_rootValueSeparator != null) { - byte[] raw = _rootValueSeparator.asUnquotedUTF8(); - if (raw.length > 0) { - _writeBytes(raw); - } - } - return; - case JsonWriteContext.STATUS_EXPECT_NAME: - _reportCantWriteValueExpectName(typeMsg); - return; - } - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = b; - } - - /* - /********************************************************** - /* Low-level output handling - /********************************************************** - */ - - @Override - public void flush() throws IOException - { - _flushBuffer(); - if (_outputStream != null) { - if (isEnabled(Feature.FLUSH_PASSED_TO_STREAM)) { - _outputStream.flush(); - } - } - } - - @Override - public void close() throws IOException - { - super.close(); - - /* 05-Dec-2008, tatu: To add [JACKSON-27], need to close open - * scopes. - */ - // First: let's see that we still have buffers... - if ((_outputBuffer != null) - && isEnabled(Feature.AUTO_CLOSE_JSON_CONTENT)) { - while (true) { - JsonStreamContext ctxt = getOutputContext(); - if (ctxt.inArray()) { - writeEndArray(); - } else if (ctxt.inObject()) { - writeEndObject(); - } else { - break; - } - } - } - _flushBuffer(); - _outputTail = 0; // just to ensure we don't think there's anything buffered - - /* 25-Nov-2008, tatus: As per [JACKSON-16] we are not to call close() - * on the underlying Reader, unless we "own" it, or auto-closing - * feature is enabled. - * One downside: when using UTF8Writer, underlying buffer(s) - * may not be properly recycled if we don't close the writer. - */ - if (_outputStream != null) { - if (_ioContext.isResourceManaged() || isEnabled(Feature.AUTO_CLOSE_TARGET)) { - _outputStream.close(); - } else if (isEnabled(Feature.FLUSH_PASSED_TO_STREAM)) { - // If we can't close it, we should at least flush - _outputStream.flush(); - } - } - // Internal buffer(s) generator has can now be released as well - _releaseBuffers(); - } - - @Override - protected void _releaseBuffers() - { - byte[] buf = _outputBuffer; - if (buf != null && _bufferRecyclable) { - _outputBuffer = null; - _ioContext.releaseWriteEncodingBuffer(buf); - } - char[] cbuf = _charBuffer; - if (cbuf != null) { - _charBuffer = null; - _ioContext.releaseConcatBuffer(cbuf); - } - } - - /* - /********************************************************** - /* Internal methods, low-level writing, raw bytes - /********************************************************** - */ - - private final void _writeBytes(byte[] bytes) throws IOException - { - final int len = bytes.length; - if ((_outputTail + len) > _outputEnd) { - _flushBuffer(); - // still not enough? - if (len > MAX_BYTES_TO_BUFFER) { - _outputStream.write(bytes, 0, len); - return; - } - } - System.arraycopy(bytes, 0, _outputBuffer, _outputTail, len); - _outputTail += len; - } - - private final void _writeBytes(byte[] bytes, int offset, int len) throws IOException - { - if ((_outputTail + len) > _outputEnd) { - _flushBuffer(); - // still not enough? - if (len > MAX_BYTES_TO_BUFFER) { - _outputStream.write(bytes, offset, len); - return; - } - } - System.arraycopy(bytes, offset, _outputBuffer, _outputTail, len); - _outputTail += len; - } - - /* - /********************************************************** - /* Internal methods, mid-level writing, String segments - /********************************************************** - */ - - /** - * Method called when String to write is long enough not to fit - * completely in temporary copy buffer. If so, we will actually - * copy it in small enough chunks so it can be directly fed - * to single-segment writes (instead of maximum slices that - * would fit in copy buffer) - */ - private final void _writeStringSegments(String text, boolean addQuotes) throws IOException - { - if (addQuotes) { - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } - - int left = text.length(); - int offset = 0; - - while (left > 0) { - int len = Math.min(_outputMaxContiguous, left); - if ((_outputTail + len) > _outputEnd) { // caller must ensure enough space - _flushBuffer(); - } - _writeStringSegment(text, offset, len); - offset += len; - left -= len; - } - - if (addQuotes) { - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } - } - - /** - * Method called when character sequence to write is long enough that - * its maximum encoded and escaped form is not guaranteed to fit in - * the output buffer. If so, we will need to choose smaller output - * chunks to write at a time. - */ - private final void _writeStringSegments(char[] cbuf, int offset, int totalLen) throws IOException - { - do { - int len = Math.min(_outputMaxContiguous, totalLen); - if ((_outputTail + len) > _outputEnd) { // caller must ensure enough space - _flushBuffer(); - } - _writeStringSegment(cbuf, offset, len); - offset += len; - totalLen -= len; - } while (totalLen > 0); - } - - private final void _writeStringSegments(String text, int offset, int totalLen) throws IOException - { - do { - int len = Math.min(_outputMaxContiguous, totalLen); - if ((_outputTail + len) > _outputEnd) { // caller must ensure enough space - _flushBuffer(); - } - _writeStringSegment(text, offset, len); - offset += len; - totalLen -= len; - } while (totalLen > 0); - } - - /* - /********************************************************** - /* Internal methods, low-level writing, text segments - /********************************************************** - */ - - /** - * This method called when the string content is already in - * a char buffer, and its maximum total encoded and escaped length - * can not exceed size of the output buffer. - * Caller must ensure that there is enough space in output buffer, - * assuming case of all non-escaped ASCII characters, as well as - * potentially enough space for other cases (but not necessarily flushed) - */ - private final void _writeStringSegment(char[] cbuf, int offset, int len) - throws IOException - { - // note: caller MUST ensure (via flushing) there's room for ASCII only - - // Fast+tight loop for ASCII-only, no-escaping-needed output - len += offset; // becomes end marker, then - - int outputPtr = _outputTail; - final byte[] outputBuffer = _outputBuffer; - final int[] escCodes = _outputEscapes; - - while (offset < len) { - int ch = cbuf[offset]; - // note: here we know that (ch > 0x7F) will cover case of escaping non-ASCII too: - if (ch > 0x7F || escCodes[ch] != 0) { - break; - } - outputBuffer[outputPtr++] = (byte) ch; - ++offset; - } - _outputTail = outputPtr; - if (offset < len) { - // [JACKSON-106] - if (_characterEscapes != null) { - _writeCustomStringSegment2(cbuf, offset, len); - // [JACKSON-102] - } else if (_maximumNonEscapedChar == 0) { - _writeStringSegment2(cbuf, offset, len); - } else { - _writeStringSegmentASCII2(cbuf, offset, len); - } - - } - } - - private final void _writeStringSegment(String text, int offset, int len) throws IOException - { - // note: caller MUST ensure (via flushing) there's room for ASCII only - // Fast+tight loop for ASCII-only, no-escaping-needed output - len += offset; // becomes end marker, then - - int outputPtr = _outputTail; - final byte[] outputBuffer = _outputBuffer; - final int[] escCodes = _outputEscapes; - - while (offset < len) { - int ch = text.charAt(offset); - // note: here we know that (ch > 0x7F) will cover case of escaping non-ASCII too: - if (ch > 0x7F || escCodes[ch] != 0) { - break; - } - outputBuffer[outputPtr++] = (byte) ch; - ++offset; - } - _outputTail = outputPtr; - if (offset < len) { - if (_characterEscapes != null) { - _writeCustomStringSegment2(text, offset, len); - } else if (_maximumNonEscapedChar == 0) { - _writeStringSegment2(text, offset, len); - } else { - _writeStringSegmentASCII2(text, offset, len); - } - } - } - - /** - * Secondary method called when content contains characters to escape, - * and/or multi-byte UTF-8 characters. - */ - private final void _writeStringSegment2(final char[] cbuf, int offset, final int end) throws IOException - { - // Ok: caller guarantees buffer can have room; but that may require flushing: - if ((_outputTail + 6 * (end - offset)) > _outputEnd) { - _flushBuffer(); - } - - int outputPtr = _outputTail; - - final byte[] outputBuffer = _outputBuffer; - final int[] escCodes = _outputEscapes; - - while (offset < end) { - int ch = cbuf[offset++]; - if (ch <= 0x7F) { - if (escCodes[ch] == 0) { - outputBuffer[outputPtr++] = (byte) ch; - continue; - } - int escape = escCodes[ch]; - if (escape > 0) { // 2-char escape, fine - outputBuffer[outputPtr++] = BYTE_BACKSLASH; - outputBuffer[outputPtr++] = (byte) escape; - } else { - // ctrl-char, 6-byte escape... - outputPtr = _writeGenericEscape(ch, outputPtr); - } - continue; - } - if (ch <= 0x7FF) { // fine, just needs 2 byte output - outputBuffer[outputPtr++] = (byte) (0xc0 | (ch >> 6)); - outputBuffer[outputPtr++] = (byte) (0x80 | (ch & 0x3f)); - } else { - outputPtr = _outputMultiByteChar(ch, outputPtr); - } - } - _outputTail = outputPtr; - } - - private final void _writeStringSegment2(final String text, int offset, final int end) throws IOException - { - if ((_outputTail + 6 * (end - offset)) > _outputEnd) { - _flushBuffer(); - } - - int outputPtr = _outputTail; - - final byte[] outputBuffer = _outputBuffer; - final int[] escCodes = _outputEscapes; - - while (offset < end) { - int ch = text.charAt(offset++); - if (ch <= 0x7F) { - if (escCodes[ch] == 0) { - outputBuffer[outputPtr++] = (byte) ch; - continue; - } - int escape = escCodes[ch]; - if (escape > 0) { // 2-char escape, fine - outputBuffer[outputPtr++] = BYTE_BACKSLASH; - outputBuffer[outputPtr++] = (byte) escape; - } else { - // ctrl-char, 6-byte escape... - outputPtr = _writeGenericEscape(ch, outputPtr); - } - continue; - } - if (ch <= 0x7FF) { // fine, just needs 2 byte output - outputBuffer[outputPtr++] = (byte) (0xc0 | (ch >> 6)); - outputBuffer[outputPtr++] = (byte) (0x80 | (ch & 0x3f)); - } else { - outputPtr = _outputMultiByteChar(ch, outputPtr); - } - } - _outputTail = outputPtr; - } - - /* - /********************************************************** - /* Internal methods, low-level writing, text segment - /* with additional escaping (ASCII or such) - /********************************************************** - */ - - /** - * Same as _writeStringSegment2(char[], ...) _outputEnd) { - _flushBuffer(); - } - - int outputPtr = _outputTail; - - final byte[] outputBuffer = _outputBuffer; - final int[] escCodes = _outputEscapes; - final int maxUnescaped = _maximumNonEscapedChar; - - while (offset < end) { - int ch = cbuf[offset++]; - if (ch <= 0x7F) { - if (escCodes[ch] == 0) { - outputBuffer[outputPtr++] = (byte) ch; - continue; - } - int escape = escCodes[ch]; - if (escape > 0) { // 2-char escape, fine - outputBuffer[outputPtr++] = BYTE_BACKSLASH; - outputBuffer[outputPtr++] = (byte) escape; - } else { - // ctrl-char, 6-byte escape... - outputPtr = _writeGenericEscape(ch, outputPtr); - } - continue; - } - if (ch > maxUnescaped) { // [JACKSON-102] Allow forced escaping if non-ASCII (etc) chars: - outputPtr = _writeGenericEscape(ch, outputPtr); - continue; - } - if (ch <= 0x7FF) { // fine, just needs 2 byte output - outputBuffer[outputPtr++] = (byte) (0xc0 | (ch >> 6)); - outputBuffer[outputPtr++] = (byte) (0x80 | (ch & 0x3f)); - } else { - outputPtr = _outputMultiByteChar(ch, outputPtr); - } - } - _outputTail = outputPtr; - } - - private final void _writeStringSegmentASCII2(final String text, int offset, final int end) throws IOException - { - // Ok: caller guarantees buffer can have room; but that may require flushing: - if ((_outputTail + 6 * (end - offset)) > _outputEnd) { - _flushBuffer(); - } - - int outputPtr = _outputTail; - - final byte[] outputBuffer = _outputBuffer; - final int[] escCodes = _outputEscapes; - final int maxUnescaped = _maximumNonEscapedChar; - - while (offset < end) { - int ch = text.charAt(offset++); - if (ch <= 0x7F) { - if (escCodes[ch] == 0) { - outputBuffer[outputPtr++] = (byte) ch; - continue; - } - int escape = escCodes[ch]; - if (escape > 0) { // 2-char escape, fine - outputBuffer[outputPtr++] = BYTE_BACKSLASH; - outputBuffer[outputPtr++] = (byte) escape; - } else { - // ctrl-char, 6-byte escape... - outputPtr = _writeGenericEscape(ch, outputPtr); - } - continue; - } - if (ch > maxUnescaped) { // [JACKSON-102] Allow forced escaping if non-ASCII (etc) chars: - outputPtr = _writeGenericEscape(ch, outputPtr); - continue; - } - if (ch <= 0x7FF) { // fine, just needs 2 byte output - outputBuffer[outputPtr++] = (byte) (0xc0 | (ch >> 6)); - outputBuffer[outputPtr++] = (byte) (0x80 | (ch & 0x3f)); - } else { - outputPtr = _outputMultiByteChar(ch, outputPtr); - } - } - _outputTail = outputPtr; - } - - /* - /********************************************************** - /* Internal methods, low-level writing, text segment - /* with fully custom escaping (and possibly escaping of non-ASCII - /********************************************************** - */ - - /** - * Same as _writeStringSegmentASCII2(char[], ...) _outputEnd) { - _flushBuffer(); - } - int outputPtr = _outputTail; - - final byte[] outputBuffer = _outputBuffer; - final int[] escCodes = _outputEscapes; - // may or may not have this limit - final int maxUnescaped = (_maximumNonEscapedChar <= 0) ? 0xFFFF : _maximumNonEscapedChar; - final CharacterEscapes customEscapes = _characterEscapes; // non-null - - while (offset < end) { - int ch = cbuf[offset++]; - if (ch <= 0x7F) { - if (escCodes[ch] == 0) { - outputBuffer[outputPtr++] = (byte) ch; - continue; - } - int escape = escCodes[ch]; - if (escape > 0) { // 2-char escape, fine - outputBuffer[outputPtr++] = BYTE_BACKSLASH; - outputBuffer[outputPtr++] = (byte) escape; - } else if (escape == CharacterEscapes.ESCAPE_CUSTOM) { - SerializableString esc = customEscapes.getEscapeSequence(ch); - if (esc == null) { - _reportError("Invalid custom escape definitions; custom escape not found for character code 0x" - +Integer.toHexString(ch)+", although was supposed to have one"); - } - outputPtr = _writeCustomEscape(outputBuffer, outputPtr, esc, end-offset); - } else { - // ctrl-char, 6-byte escape... - outputPtr = _writeGenericEscape(ch, outputPtr); - } - continue; - } - if (ch > maxUnescaped) { // [JACKSON-102] Allow forced escaping if non-ASCII (etc) chars: - outputPtr = _writeGenericEscape(ch, outputPtr); - continue; - } - SerializableString esc = customEscapes.getEscapeSequence(ch); - if (esc != null) { - outputPtr = _writeCustomEscape(outputBuffer, outputPtr, esc, end-offset); - continue; - } - if (ch <= 0x7FF) { // fine, just needs 2 byte output - outputBuffer[outputPtr++] = (byte) (0xc0 | (ch >> 6)); - outputBuffer[outputPtr++] = (byte) (0x80 | (ch & 0x3f)); - } else { - outputPtr = _outputMultiByteChar(ch, outputPtr); - } - } - _outputTail = outputPtr; - } - - private final void _writeCustomStringSegment2(final String text, int offset, final int end) throws IOException - { - // Ok: caller guarantees buffer can have room; but that may require flushing: - if ((_outputTail + 6 * (end - offset)) > _outputEnd) { - _flushBuffer(); - } - int outputPtr = _outputTail; - - final byte[] outputBuffer = _outputBuffer; - final int[] escCodes = _outputEscapes; - // may or may not have this limit - final int maxUnescaped = (_maximumNonEscapedChar <= 0) ? 0xFFFF : _maximumNonEscapedChar; - final CharacterEscapes customEscapes = _characterEscapes; // non-null - - while (offset < end) { - int ch = text.charAt(offset++); - if (ch <= 0x7F) { - if (escCodes[ch] == 0) { - outputBuffer[outputPtr++] = (byte) ch; - continue; - } - int escape = escCodes[ch]; - if (escape > 0) { // 2-char escape, fine - outputBuffer[outputPtr++] = BYTE_BACKSLASH; - outputBuffer[outputPtr++] = (byte) escape; - } else if (escape == CharacterEscapes.ESCAPE_CUSTOM) { - SerializableString esc = customEscapes.getEscapeSequence(ch); - if (esc == null) { - _reportError("Invalid custom escape definitions; custom escape not found for character code 0x" - +Integer.toHexString(ch)+", although was supposed to have one"); - } - outputPtr = _writeCustomEscape(outputBuffer, outputPtr, esc, end-offset); - } else { - // ctrl-char, 6-byte escape... - outputPtr = _writeGenericEscape(ch, outputPtr); - } - continue; - } - if (ch > maxUnescaped) { // [JACKSON-102] Allow forced escaping if non-ASCII (etc) chars: - outputPtr = _writeGenericEscape(ch, outputPtr); - continue; - } - SerializableString esc = customEscapes.getEscapeSequence(ch); - if (esc != null) { - outputPtr = _writeCustomEscape(outputBuffer, outputPtr, esc, end-offset); - continue; - } - if (ch <= 0x7FF) { // fine, just needs 2 byte output - outputBuffer[outputPtr++] = (byte) (0xc0 | (ch >> 6)); - outputBuffer[outputPtr++] = (byte) (0x80 | (ch & 0x3f)); - } else { - outputPtr = _outputMultiByteChar(ch, outputPtr); - } - } - _outputTail = outputPtr; - } - - private final int _writeCustomEscape(byte[] outputBuffer, int outputPtr, SerializableString esc, int remainingChars) - throws IOException, JsonGenerationException - { - byte[] raw = esc.asUnquotedUTF8(); // must be escaped at this point, shouldn't double-quote - int len = raw.length; - if (len > 6) { // may violate constraints we have, do offline - return _handleLongCustomEscape(outputBuffer, outputPtr, _outputEnd, raw, remainingChars); - } - // otherwise will fit without issues, so: - System.arraycopy(raw, 0, outputBuffer, outputPtr, len); - return (outputPtr + len); - } - - private final int _handleLongCustomEscape(byte[] outputBuffer, int outputPtr, int outputEnd, byte[] raw, - int remainingChars) - throws IOException, JsonGenerationException - { - int len = raw.length; - if ((outputPtr + len) > outputEnd) { - _outputTail = outputPtr; - _flushBuffer(); - outputPtr = _outputTail; - if (len > outputBuffer.length) { // very unlikely, but possible... - _outputStream.write(raw, 0, len); - return outputPtr; - } - System.arraycopy(raw, 0, outputBuffer, outputPtr, len); - outputPtr += len; - } - // but is the invariant still obeyed? If not, flush once more - if ((outputPtr + 6 * remainingChars) > outputEnd) { - _flushBuffer(); - return _outputTail; - } - return outputPtr; - } - - /* - /********************************************************** - /* Internal methods, low-level writing, "raw UTF-8" segments - /********************************************************** - */ - - /** - * Method called when UTF-8 encoded (but NOT yet escaped!) content is not guaranteed - * to fit in the output buffer after escaping; as such, we just need to - * chunk writes. - */ - private final void _writeUTF8Segments(byte[] utf8, int offset, int totalLen) - throws IOException, JsonGenerationException - { - do { - int len = Math.min(_outputMaxContiguous, totalLen); - _writeUTF8Segment(utf8, offset, len); - offset += len; - totalLen -= len; - } while (totalLen > 0); - } - - private final void _writeUTF8Segment(byte[] utf8, final int offset, final int len) - throws IOException, JsonGenerationException - { - // fast loop to see if escaping is needed; don't copy, just look - final int[] escCodes = _outputEscapes; - - for (int ptr = offset, end = offset + len; ptr < end; ) { - // 28-Feb-2011, tatu: escape codes just cover 7-bit range, so: - int ch = utf8[ptr++]; - if ((ch >= 0) && escCodes[ch] != 0) { - _writeUTF8Segment2(utf8, offset, len); - return; - } - } - - // yes, fine, just copy the sucker - if ((_outputTail + len) > _outputEnd) { // enough room or need to flush? - _flushBuffer(); // but yes once we flush (caller guarantees length restriction) - } - System.arraycopy(utf8, offset, _outputBuffer, _outputTail, len); - _outputTail += len; - } - - private final void _writeUTF8Segment2(final byte[] utf8, int offset, int len) - throws IOException, JsonGenerationException - { - int outputPtr = _outputTail; - - // Ok: caller guarantees buffer can have room; but that may require flushing: - if ((outputPtr + (len * 6)) > _outputEnd) { - _flushBuffer(); - outputPtr = _outputTail; - } - - final byte[] outputBuffer = _outputBuffer; - final int[] escCodes = _outputEscapes; - len += offset; // so 'len' becomes 'end' - - while (offset < len) { - byte b = utf8[offset++]; - int ch = b; - if (ch < 0 || escCodes[ch] == 0) { - outputBuffer[outputPtr++] = b; - continue; - } - int escape = escCodes[ch]; - if (escape > 0) { // 2-char escape, fine - outputBuffer[outputPtr++] = BYTE_BACKSLASH; - outputBuffer[outputPtr++] = (byte) escape; - } else { - // ctrl-char, 6-byte escape... - outputPtr = _writeGenericEscape(ch, outputPtr); - } - } - _outputTail = outputPtr; - } - - /* - /********************************************************** - /* Internal methods, low-level writing, base64 encoded - /********************************************************** - */ - - protected final void _writeBinary(Base64Variant b64variant, - byte[] input, int inputPtr, final int inputEnd) - throws IOException, JsonGenerationException - { - // Encoding is by chunks of 3 input, 4 output chars, so: - int safeInputEnd = inputEnd - 3; - // Let's also reserve room for possible (and quoted) lf char each round - int safeOutputEnd = _outputEnd - 6; - int chunksBeforeLF = b64variant.getMaxLineLength() >> 2; - - // Ok, first we loop through all full triplets of data: - while (inputPtr <= safeInputEnd) { - if (_outputTail > safeOutputEnd) { // need to flush - _flushBuffer(); - } - // First, mash 3 bytes into lsb of 32-bit int - int b24 = ((int) input[inputPtr++]) << 8; - b24 |= ((int) input[inputPtr++]) & 0xFF; - b24 = (b24 << 8) | (((int) input[inputPtr++]) & 0xFF); - _outputTail = b64variant.encodeBase64Chunk(b24, _outputBuffer, _outputTail); - if (--chunksBeforeLF <= 0) { - // note: must quote in JSON value - _outputBuffer[_outputTail++] = '\\'; - _outputBuffer[_outputTail++] = 'n'; - chunksBeforeLF = b64variant.getMaxLineLength() >> 2; - } - } - - // And then we may have 1 or 2 leftover bytes to encode - int inputLeft = inputEnd - inputPtr; // 0, 1 or 2 - if (inputLeft > 0) { // yes, but do we have room for output? - if (_outputTail > safeOutputEnd) { // don't really need 6 bytes but... - _flushBuffer(); - } - int b24 = ((int) input[inputPtr++]) << 16; - if (inputLeft == 2) { - b24 |= (((int) input[inputPtr++]) & 0xFF) << 8; - } - _outputTail = b64variant.encodeBase64Partial(b24, inputLeft, _outputBuffer, _outputTail); - } - } - - // write-method called when length is definitely known - protected final int _writeBinary(Base64Variant b64variant, - InputStream data, byte[] readBuffer, int bytesLeft) - throws IOException, JsonGenerationException - { - int inputPtr = 0; - int inputEnd = 0; - int lastFullOffset = -3; - - // Let's also reserve room for possible (and quoted) LF char each round - int safeOutputEnd = _outputEnd - 6; - int chunksBeforeLF = b64variant.getMaxLineLength() >> 2; - - while (bytesLeft > 2) { // main loop for full triplets - if (inputPtr > lastFullOffset) { - inputEnd = _readMore(data, readBuffer, inputPtr, inputEnd, bytesLeft); - inputPtr = 0; - if (inputEnd < 3) { // required to try to read to have at least 3 bytes - break; - } - lastFullOffset = inputEnd-3; - } - if (_outputTail > safeOutputEnd) { // need to flush - _flushBuffer(); - } - int b24 = ((int) readBuffer[inputPtr++]) << 8; - b24 |= ((int) readBuffer[inputPtr++]) & 0xFF; - b24 = (b24 << 8) | (((int) readBuffer[inputPtr++]) & 0xFF); - bytesLeft -= 3; - _outputTail = b64variant.encodeBase64Chunk(b24, _outputBuffer, _outputTail); - if (--chunksBeforeLF <= 0) { - _outputBuffer[_outputTail++] = '\\'; - _outputBuffer[_outputTail++] = 'n'; - chunksBeforeLF = b64variant.getMaxLineLength() >> 2; - } - } - - // And then we may have 1 or 2 leftover bytes to encode - if (bytesLeft > 0) { - inputEnd = _readMore(data, readBuffer, inputPtr, inputEnd, bytesLeft); - inputPtr = 0; - if (inputEnd > 0) { // yes, but do we have room for output? - if (_outputTail > safeOutputEnd) { // don't really need 6 bytes but... - _flushBuffer(); - } - int b24 = ((int) readBuffer[inputPtr++]) << 16; - int amount; - if (inputPtr < inputEnd) { - b24 |= (((int) readBuffer[inputPtr]) & 0xFF) << 8; - amount = 2; - } else { - amount = 1; - } - _outputTail = b64variant.encodeBase64Partial(b24, amount, _outputBuffer, _outputTail); - bytesLeft -= amount; - } - } - return bytesLeft; - } - - // write method when length is unknown - protected final int _writeBinary(Base64Variant b64variant, - InputStream data, byte[] readBuffer) - throws IOException, JsonGenerationException - { - int inputPtr = 0; - int inputEnd = 0; - int lastFullOffset = -3; - int bytesDone = 0; - - // Let's also reserve room for possible (and quoted) LF char each round - int safeOutputEnd = _outputEnd - 6; - int chunksBeforeLF = b64variant.getMaxLineLength() >> 2; - - // Ok, first we loop through all full triplets of data: - while (true) { - if (inputPtr > lastFullOffset) { // need to load more - inputEnd = _readMore(data, readBuffer, inputPtr, inputEnd, readBuffer.length); - inputPtr = 0; - if (inputEnd < 3) { // required to try to read to have at least 3 bytes - break; - } - lastFullOffset = inputEnd-3; - } - if (_outputTail > safeOutputEnd) { // need to flush - _flushBuffer(); - } - // First, mash 3 bytes into lsb of 32-bit int - int b24 = ((int) readBuffer[inputPtr++]) << 8; - b24 |= ((int) readBuffer[inputPtr++]) & 0xFF; - b24 = (b24 << 8) | (((int) readBuffer[inputPtr++]) & 0xFF); - bytesDone += 3; - _outputTail = b64variant.encodeBase64Chunk(b24, _outputBuffer, _outputTail); - if (--chunksBeforeLF <= 0) { - _outputBuffer[_outputTail++] = '\\'; - _outputBuffer[_outputTail++] = 'n'; - chunksBeforeLF = b64variant.getMaxLineLength() >> 2; - } - } - - // And then we may have 1 or 2 leftover bytes to encode - if (inputPtr < inputEnd) { // yes, but do we have room for output? - if (_outputTail > safeOutputEnd) { // don't really need 6 bytes but... - _flushBuffer(); - } - int b24 = ((int) readBuffer[inputPtr++]) << 16; - int amount = 1; - if (inputPtr < inputEnd) { - b24 |= (((int) readBuffer[inputPtr]) & 0xFF) << 8; - amount = 2; - } - bytesDone += amount; - _outputTail = b64variant.encodeBase64Partial(b24, amount, _outputBuffer, _outputTail); - } - return bytesDone; - } - - private final int _readMore(InputStream in, - byte[] readBuffer, int inputPtr, int inputEnd, - int maxRead) throws IOException - { - // anything to shift to front? - int i = 0; - while (inputPtr < inputEnd) { - readBuffer[i++] = readBuffer[inputPtr++]; - } - inputPtr = 0; - inputEnd = i; - maxRead = Math.min(maxRead, readBuffer.length); - - do { - int length = maxRead - inputEnd; - if (length == 0) { - break; - } - int count = in.read(readBuffer, inputEnd, length); - if (count < 0) { - return inputEnd; - } - inputEnd += count; - } while (inputEnd < 3); - return inputEnd; - } - - /* - /********************************************************** - /* Internal methods, character escapes/encoding - /********************************************************** - */ - - /** - * Method called to output a character that is beyond range of - * 1- and 2-byte UTF-8 encodings, when outputting "raw" - * text (meaning it is not to be escaped or quoted) - */ - private final int _outputRawMultiByteChar(int ch, char[] cbuf, int inputOffset, int inputEnd) - throws IOException - { - // Let's handle surrogates gracefully (as 4 byte output): - if (ch >= SURR1_FIRST) { - if (ch <= SURR2_LAST) { // yes, outside of BMP - // Do we have second part? - if (inputOffset >= inputEnd || cbuf == null) { // nope... have to note down - _reportError(String.format( -"Split surrogate on writeRaw() input (last character): first character 0x%4x", ch)); - } - _outputSurrogates(ch, cbuf[inputOffset]); - return inputOffset+1; - } - } - final byte[] bbuf = _outputBuffer; - bbuf[_outputTail++] = (byte) (0xe0 | (ch >> 12)); - bbuf[_outputTail++] = (byte) (0x80 | ((ch >> 6) & 0x3f)); - bbuf[_outputTail++] = (byte) (0x80 | (ch & 0x3f)); - return inputOffset; - } - - protected final void _outputSurrogates(int surr1, int surr2) throws IOException - { - int c = _decodeSurrogate(surr1, surr2); - if ((_outputTail + 4) > _outputEnd) { - _flushBuffer(); - } - final byte[] bbuf = _outputBuffer; - bbuf[_outputTail++] = (byte) (0xf0 | (c >> 18)); - bbuf[_outputTail++] = (byte) (0x80 | ((c >> 12) & 0x3f)); - bbuf[_outputTail++] = (byte) (0x80 | ((c >> 6) & 0x3f)); - bbuf[_outputTail++] = (byte) (0x80 | (c & 0x3f)); - } - - /** - * - * @param ch - * @param outputPtr Position within output buffer to append multi-byte in - * - * @return New output position after appending - * - * @throws IOException - */ - private final int _outputMultiByteChar(int ch, int outputPtr) throws IOException - { - byte[] bbuf = _outputBuffer; - if (ch >= SURR1_FIRST && ch <= SURR2_LAST) { // yes, outside of BMP; add an escape - // 23-Nov-2015, tatu: As per [core#223], may or may not want escapes; - // it would be added here... but as things are, we do not have proper - // access yet... -// if (Feature.ESCAPE_UTF8_SURROGATES.enabledIn(_features)) { - bbuf[outputPtr++] = BYTE_BACKSLASH; - bbuf[outputPtr++] = BYTE_u; - - bbuf[outputPtr++] = HEX_CHARS[(ch >> 12) & 0xF]; - bbuf[outputPtr++] = HEX_CHARS[(ch >> 8) & 0xF]; - bbuf[outputPtr++] = HEX_CHARS[(ch >> 4) & 0xF]; - bbuf[outputPtr++] = HEX_CHARS[ch & 0xF]; -// } else { ... } - } else { - bbuf[outputPtr++] = (byte) (0xe0 | (ch >> 12)); - bbuf[outputPtr++] = (byte) (0x80 | ((ch >> 6) & 0x3f)); - bbuf[outputPtr++] = (byte) (0x80 | (ch & 0x3f)); - } - return outputPtr; - } - - private final void _writeNull() throws IOException - { - if ((_outputTail + 4) >= _outputEnd) { - _flushBuffer(); - } - System.arraycopy(NULL_BYTES, 0, _outputBuffer, _outputTail, 4); - _outputTail += 4; - } - - /** - * Method called to write a generic Unicode escape for given character. - * - * @param charToEscape Character to escape using escape sequence (\\uXXXX) - */ - private int _writeGenericEscape(int charToEscape, int outputPtr) throws IOException - { - final byte[] bbuf = _outputBuffer; - bbuf[outputPtr++] = BYTE_BACKSLASH; - bbuf[outputPtr++] = BYTE_u; - if (charToEscape > 0xFF) { - int hi = (charToEscape >> 8) & 0xFF; - bbuf[outputPtr++] = HEX_CHARS[hi >> 4]; - bbuf[outputPtr++] = HEX_CHARS[hi & 0xF]; - charToEscape &= 0xFF; - } else { - bbuf[outputPtr++] = BYTE_0; - bbuf[outputPtr++] = BYTE_0; - } - // We know it's a control char, so only the last 2 chars are non-0 - bbuf[outputPtr++] = HEX_CHARS[charToEscape >> 4]; - bbuf[outputPtr++] = HEX_CHARS[charToEscape & 0xF]; - return outputPtr; - } - - protected final void _flushBuffer() throws IOException - { - int len = _outputTail; - if (len > 0) { - _outputTail = 0; - _outputStream.write(_outputBuffer, 0, len); - } - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/UTF8StreamJsonParser.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/UTF8StreamJsonParser.java deleted file mode 100644 index 7214af36..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/UTF8StreamJsonParser.java +++ /dev/null @@ -1,3772 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.json; - -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_FIELD_NAME; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_NUMBER_FLOAT; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_NUMBER_INT; -import static autosaveworld.zlibs.com.fasterxml.jackson.core.JsonTokenId.ID_STRING; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Writer; -import java.util.Arrays; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.Base64Variant; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonLocation; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; -import autosaveworld.zlibs.com.fasterxml.jackson.core.ObjectCodec; -import autosaveworld.zlibs.com.fasterxml.jackson.core.SerializableString; -import autosaveworld.zlibs.com.fasterxml.jackson.core.base.ParserBase; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.CharTypes; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.IOContext; -import autosaveworld.zlibs.com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.ByteArrayBuilder; - -/** - * This is a concrete implementation of {@link JsonParser}, which is - * based on a {@link java.io.InputStream} as the input source. - */ -public class UTF8StreamJsonParser - extends ParserBase -{ - final static byte BYTE_LF = (byte) '\n'; - - // This is the main input-code lookup table, fetched eagerly - private final static int[] _icUTF8 = CharTypes.getInputCodeUtf8(); - - // Latin1 encoding is not supported, but we do use 8-bit subset for - // pre-processing task, to simplify first pass, keep it fast. - protected final static int[] _icLatin1 = CharTypes.getInputCodeLatin1(); - - protected final static int FEAT_MASK_TRAILING_COMMA = Feature.ALLOW_TRAILING_COMMA.getMask(); - - /* - /********************************************************** - /* Configuration - /********************************************************** - */ - - /** - * Codec used for data binding when (if) requested; typically full - * ObjectMapper, but that abstract is not part of core - * package. - */ - protected ObjectCodec _objectCodec; - - /** - * Symbol table that contains field names encountered so far - */ - final protected ByteQuadsCanonicalizer _symbols; - - /* - /********************************************************** - /* Parsing state - /********************************************************** - */ - - /** - * Temporary buffer used for name parsing. - */ - protected int[] _quadBuffer = new int[16]; - - /** - * Flag that indicates that the current token has not yet - * been fully processed, and needs to be finished for - * some access (or skipped to obtain the next token) - */ - protected boolean _tokenIncomplete; - - /** - * Temporary storage for partially parsed name bytes. - */ - private int _quad1; - - /** - * Value of {@link #_inputPtr} at the time when the first character of - * name token was read. Used for calculating token location when requested; - * combined with {@link #_currInputProcessed}, may be updated appropriately - * as needed. - * - * @since 2.7 - */ - protected int _nameStartOffset; - - /** - * @since 2.7 - */ - protected int _nameStartRow; - - /** - * @since 2.7 - */ - protected int _nameStartCol; - - /* - /********************************************************** - /* Input buffering (from former 'StreamBasedParserBase') - /********************************************************** - */ - - protected InputStream _inputStream; - - /* - /********************************************************** - /* Current input data - /********************************************************** - */ - - /** - * Current buffer from which data is read; generally data is read into - * buffer from input source, but in some cases pre-loaded buffer - * is handed to the parser. - */ - protected byte[] _inputBuffer; - - /** - * Flag that indicates whether the input buffer is recycable (and - * needs to be returned to recycler once we are done) or not. - *

- * If it is not, it also means that parser can NOT modify underlying - * buffer. - */ - protected boolean _bufferRecyclable; - - /* - /********************************************************** - /* Life-cycle - /********************************************************** - */ - - public UTF8StreamJsonParser(IOContext ctxt, int features, InputStream in, - ObjectCodec codec, ByteQuadsCanonicalizer sym, - byte[] inputBuffer, int start, int end, - boolean bufferRecyclable) - { - super(ctxt, features); - _inputStream = in; - _objectCodec = codec; - _symbols = sym; - _inputBuffer = inputBuffer; - _inputPtr = start; - _inputEnd = end; - _currInputRowStart = start; - // If we have offset, need to omit that from byte offset, so: - _currInputProcessed = -start; - _bufferRecyclable = bufferRecyclable; - } - - @Override - public ObjectCodec getCodec() { - return _objectCodec; - } - - @Override - public void setCodec(ObjectCodec c) { - _objectCodec = c; - } - - /* - /********************************************************** - /* Overrides for life-cycle - /********************************************************** - */ - - @Override - public int releaseBuffered(OutputStream out) throws IOException - { - int count = _inputEnd - _inputPtr; - if (count < 1) { - return 0; - } - // let's just advance ptr to end - int origPtr = _inputPtr; - out.write(_inputBuffer, origPtr, count); - return count; - } - - @Override - public Object getInputSource() { - return _inputStream; - } - - /* - /********************************************************** - /* Overrides, low-level reading - /********************************************************** - */ - - protected final boolean _loadMore() throws IOException - { - final int bufSize = _inputEnd; - - _currInputProcessed += _inputEnd; - _currInputRowStart -= _inputEnd; - - // 26-Nov-2015, tatu: Since name-offset requires it too, must offset - // this increase to avoid "moving" name-offset, resulting most likely - // in negative value, which is fine as combine value remains unchanged. - _nameStartOffset -= bufSize; - - if (_inputStream != null) { - int space = _inputBuffer.length; - if (space == 0) { // only occurs when we've been closed - return false; - } - - int count = _inputStream.read(_inputBuffer, 0, space); - if (count > 0) { - _inputPtr = 0; - _inputEnd = count; - return true; - } - // End of input - _closeInput(); - // Should never return 0, so let's fail - if (count == 0) { - throw new IOException("InputStream.read() returned 0 characters when trying to read "+_inputBuffer.length+" bytes"); - } - } - return false; - } - - /** - * Helper method that will try to load at least specified number bytes in - * input buffer, possible moving existing data around if necessary - */ - protected final boolean _loadToHaveAtLeast(int minAvailable) throws IOException - { - // No input stream, no leading (either we are closed, or have non-stream input source) - if (_inputStream == null) { - return false; - } - // Need to move remaining data in front? - int amount = _inputEnd - _inputPtr; - if (amount > 0 && _inputPtr > 0) { - final int ptr = _inputPtr; - - _currInputProcessed += ptr; - _currInputRowStart -= ptr; - // 26-Nov-2015, tatu: Since name-offset requires it too, must offset - // (note: probably has little effect here but just in case) - _nameStartOffset -= ptr; - - System.arraycopy(_inputBuffer, ptr, _inputBuffer, 0, amount); - _inputEnd = amount; - } else { - _inputEnd = 0; - } - _inputPtr = 0; - while (_inputEnd < minAvailable) { - int count = _inputStream.read(_inputBuffer, _inputEnd, _inputBuffer.length - _inputEnd); - if (count < 1) { - // End of input - _closeInput(); - // Should never return 0, so let's fail - if (count == 0) { - throw new IOException("InputStream.read() returned 0 characters when trying to read "+amount+" bytes"); - } - return false; - } - _inputEnd += count; - } - return true; - } - - @Override - protected void _closeInput() throws IOException - { - // We are not to call close() on the underlying InputStream - // unless we "own" it, or auto-closing feature is enabled. - if (_inputStream != null) { - if (_ioContext.isResourceManaged() || isEnabled(Feature.AUTO_CLOSE_SOURCE)) { - _inputStream.close(); - } - _inputStream = null; - } - } - - /** - * Method called to release internal buffers owned by the base - * reader. This may be called along with {@link #_closeInput} (for - * example, when explicitly closing this reader instance), or - * separately (if need be). - */ - @Override - protected void _releaseBuffers() throws IOException - { - super._releaseBuffers(); - // Merge found symbols, if any: - _symbols.release(); - if (_bufferRecyclable) { - byte[] buf = _inputBuffer; - if (buf != null) { - /* 21-Nov-2014, tatu: Let's not set it to null; this way should - * get slightly more meaningful error messages in case someone - * closes parser indirectly, without realizing. - */ - _inputBuffer = ByteArrayBuilder.NO_BYTES; - _ioContext.releaseReadIOBuffer(buf); - } - } - } - - /* - /********************************************************** - /* Public API, data access - /********************************************************** - */ - - @Override - public String getText() throws IOException - { - if (_currToken == JsonToken.VALUE_STRING) { - if (_tokenIncomplete) { - _tokenIncomplete = false; - return _finishAndReturnString(); // only strings can be incomplete - } - return _textBuffer.contentsAsString(); - } - return _getText2(_currToken); - } - - @Override // since 2.8 - public int getText(Writer writer) throws IOException - { - JsonToken t = _currToken; - if (t == JsonToken.VALUE_STRING) { - if (_tokenIncomplete) { - _tokenIncomplete = false; - _finishString(); // only strings can be incomplete - } - return _textBuffer.contentsToWriter(writer); - } - if (t == JsonToken.FIELD_NAME) { - String n = _parsingContext.getCurrentName(); - writer.write(n); - return n.length(); - } - if (t != null) { - if (t.isNumeric()) { - return _textBuffer.contentsToWriter(writer); - } - char[] ch = t.asCharArray(); - writer.write(ch); - return ch.length; - } - return 0; - } - - // // // Let's override default impls for improved performance - - // @since 2.1 - @Override - public String getValueAsString() throws IOException - { - if (_currToken == JsonToken.VALUE_STRING) { - if (_tokenIncomplete) { - _tokenIncomplete = false; - return _finishAndReturnString(); // only strings can be incomplete - } - return _textBuffer.contentsAsString(); - } - if (_currToken == JsonToken.FIELD_NAME) { - return getCurrentName(); - } - return super.getValueAsString(null); - } - - // @since 2.1 - @Override - public String getValueAsString(String defValue) throws IOException - { - if (_currToken == JsonToken.VALUE_STRING) { - if (_tokenIncomplete) { - _tokenIncomplete = false; - return _finishAndReturnString(); // only strings can be incomplete - } - return _textBuffer.contentsAsString(); - } - if (_currToken == JsonToken.FIELD_NAME) { - return getCurrentName(); - } - return super.getValueAsString(defValue); - } - - // since 2.6 - @Override - public int getValueAsInt() throws IOException - { - JsonToken t = _currToken; - if ((t == JsonToken.VALUE_NUMBER_INT) || (t == JsonToken.VALUE_NUMBER_FLOAT)) { - // inlined 'getIntValue()' - if ((_numTypesValid & NR_INT) == 0) { - if (_numTypesValid == NR_UNKNOWN) { - return _parseIntValue(); - } - if ((_numTypesValid & NR_INT) == 0) { - convertNumberToInt(); - } - } - return _numberInt; - } - return super.getValueAsInt(0); - } - - // since 2.6 - @Override - public int getValueAsInt(int defValue) throws IOException - { - JsonToken t = _currToken; - if ((t == JsonToken.VALUE_NUMBER_INT) || (t == JsonToken.VALUE_NUMBER_FLOAT)) { - // inlined 'getIntValue()' - if ((_numTypesValid & NR_INT) == 0) { - if (_numTypesValid == NR_UNKNOWN) { - return _parseIntValue(); - } - if ((_numTypesValid & NR_INT) == 0) { - convertNumberToInt(); - } - } - return _numberInt; - } - return super.getValueAsInt(defValue); - } - - protected final String _getText2(JsonToken t) - { - if (t == null) { - return null; - } - switch (t.id()) { - case ID_FIELD_NAME: - return _parsingContext.getCurrentName(); - - case ID_STRING: - // fall through - case ID_NUMBER_INT: - case ID_NUMBER_FLOAT: - return _textBuffer.contentsAsString(); - default: - return t.asString(); - } - } - - @Override - public char[] getTextCharacters() throws IOException - { - if (_currToken != null) { // null only before/after document - switch (_currToken.id()) { - - case ID_FIELD_NAME: - if (!_nameCopied) { - String name = _parsingContext.getCurrentName(); - int nameLen = name.length(); - if (_nameCopyBuffer == null) { - _nameCopyBuffer = _ioContext.allocNameCopyBuffer(nameLen); - } else if (_nameCopyBuffer.length < nameLen) { - _nameCopyBuffer = new char[nameLen]; - } - name.getChars(0, nameLen, _nameCopyBuffer, 0); - _nameCopied = true; - } - return _nameCopyBuffer; - - case ID_STRING: - if (_tokenIncomplete) { - _tokenIncomplete = false; - _finishString(); // only strings can be incomplete - } - // fall through - case ID_NUMBER_INT: - case ID_NUMBER_FLOAT: - return _textBuffer.getTextBuffer(); - - default: - return _currToken.asCharArray(); - } - } - return null; - } - - @Override - public int getTextLength() throws IOException - { - if (_currToken != null) { // null only before/after document - switch (_currToken.id()) { - - case ID_FIELD_NAME: - return _parsingContext.getCurrentName().length(); - case ID_STRING: - if (_tokenIncomplete) { - _tokenIncomplete = false; - _finishString(); // only strings can be incomplete - } - // fall through - case ID_NUMBER_INT: - case ID_NUMBER_FLOAT: - return _textBuffer.size(); - - default: - return _currToken.asCharArray().length; - } - } - return 0; - } - - @Override - public int getTextOffset() throws IOException - { - // Most have offset of 0, only some may have other values: - if (_currToken != null) { - switch (_currToken.id()) { - case ID_FIELD_NAME: - return 0; - case ID_STRING: - if (_tokenIncomplete) { - _tokenIncomplete = false; - _finishString(); // only strings can be incomplete - } - // fall through - case ID_NUMBER_INT: - case ID_NUMBER_FLOAT: - return _textBuffer.getTextOffset(); - default: - } - } - return 0; - } - - @Override - public byte[] getBinaryValue(Base64Variant b64variant) throws IOException - { - if (_currToken != JsonToken.VALUE_STRING && - (_currToken != JsonToken.VALUE_EMBEDDED_OBJECT || _binaryValue == null)) { - _reportError("Current token ("+_currToken+") not VALUE_STRING or VALUE_EMBEDDED_OBJECT, can not access as binary"); - } - /* To ensure that we won't see inconsistent data, better clear up - * state... - */ - if (_tokenIncomplete) { - try { - _binaryValue = _decodeBase64(b64variant); - } catch (IllegalArgumentException iae) { - throw _constructError("Failed to decode VALUE_STRING as base64 ("+b64variant+"): "+iae.getMessage()); - } - /* let's clear incomplete only now; allows for accessing other - * textual content in error cases - */ - _tokenIncomplete = false; - } else { // may actually require conversion... - if (_binaryValue == null) { - ByteArrayBuilder builder = _getByteArrayBuilder(); - _decodeBase64(getText(), builder, b64variant); - _binaryValue = builder.toByteArray(); - } - } - return _binaryValue; - } - - @Override - public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws IOException - { - // if we have already read the token, just use whatever we may have - if (!_tokenIncomplete || _currToken != JsonToken.VALUE_STRING) { - byte[] b = getBinaryValue(b64variant); - out.write(b); - return b.length; - } - // otherwise do "real" incremental parsing... - byte[] buf = _ioContext.allocBase64Buffer(); - try { - return _readBinary(b64variant, out, buf); - } finally { - _ioContext.releaseBase64Buffer(buf); - } - } - - protected int _readBinary(Base64Variant b64variant, OutputStream out, - byte[] buffer) throws IOException - { - int outputPtr = 0; - final int outputEnd = buffer.length - 3; - int outputCount = 0; - - while (true) { - // first, we'll skip preceding white space, if any - int ch; - do { - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - ch = (int) _inputBuffer[_inputPtr++] & 0xFF; - } while (ch <= INT_SPACE); - int bits = b64variant.decodeBase64Char(ch); - if (bits < 0) { // reached the end, fair and square? - if (ch == INT_QUOTE) { - break; - } - bits = _decodeBase64Escape(b64variant, ch, 0); - if (bits < 0) { // white space to skip - continue; - } - } - - // enough room? If not, flush - if (outputPtr > outputEnd) { - outputCount += outputPtr; - out.write(buffer, 0, outputPtr); - outputPtr = 0; - } - - int decodedData = bits; - - // then second base64 char; can't get padding yet, nor ws - - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - ch = _inputBuffer[_inputPtr++] & 0xFF; - bits = b64variant.decodeBase64Char(ch); - if (bits < 0) { - bits = _decodeBase64Escape(b64variant, ch, 1); - } - decodedData = (decodedData << 6) | bits; - - // third base64 char; can be padding, but not ws - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - ch = _inputBuffer[_inputPtr++] & 0xFF; - bits = b64variant.decodeBase64Char(ch); - - // First branch: can get padding (-> 1 byte) - if (bits < 0) { - if (bits != Base64Variant.BASE64_VALUE_PADDING) { - // as per [JACKSON-631], could also just be 'missing' padding - if (ch == '"' && !b64variant.usesPadding()) { - decodedData >>= 4; - buffer[outputPtr++] = (byte) decodedData; - break; - } - bits = _decodeBase64Escape(b64variant, ch, 2); - } - if (bits == Base64Variant.BASE64_VALUE_PADDING) { - // Ok, must get padding - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - ch = _inputBuffer[_inputPtr++] & 0xFF; - if (!b64variant.usesPaddingChar(ch)) { - throw reportInvalidBase64Char(b64variant, ch, 3, "expected padding character '"+b64variant.getPaddingChar()+"'"); - } - // Got 12 bits, only need 8, need to shift - decodedData >>= 4; - buffer[outputPtr++] = (byte) decodedData; - continue; - } - } - // Nope, 2 or 3 bytes - decodedData = (decodedData << 6) | bits; - // fourth and last base64 char; can be padding, but not ws - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - ch = _inputBuffer[_inputPtr++] & 0xFF; - bits = b64variant.decodeBase64Char(ch); - if (bits < 0) { - if (bits != Base64Variant.BASE64_VALUE_PADDING) { - // as per [JACKSON-631], could also just be 'missing' padding - if (ch == '"' && !b64variant.usesPadding()) { - decodedData >>= 2; - buffer[outputPtr++] = (byte) (decodedData >> 8); - buffer[outputPtr++] = (byte) decodedData; - break; - } - bits = _decodeBase64Escape(b64variant, ch, 3); - } - if (bits == Base64Variant.BASE64_VALUE_PADDING) { - /* With padding we only get 2 bytes; but we have - * to shift it a bit so it is identical to triplet - * case with partial output. - * 3 chars gives 3x6 == 18 bits, of which 2 are - * dummies, need to discard: - */ - decodedData >>= 2; - buffer[outputPtr++] = (byte) (decodedData >> 8); - buffer[outputPtr++] = (byte) decodedData; - continue; - } - } - // otherwise, our triplet is now complete - decodedData = (decodedData << 6) | bits; - buffer[outputPtr++] = (byte) (decodedData >> 16); - buffer[outputPtr++] = (byte) (decodedData >> 8); - buffer[outputPtr++] = (byte) decodedData; - } - _tokenIncomplete = false; - if (outputPtr > 0) { - outputCount += outputPtr; - out.write(buffer, 0, outputPtr); - } - return outputCount; - } - - /* - /********************************************************** - /* Public API, traversal, basic - /********************************************************** - */ - - /** - * @return Next token from the stream, if any found, or null - * to indicate end-of-input - */ - @Override - public JsonToken nextToken() throws IOException - { - /* First: field names are special -- we will always tokenize - * (part of) value along with field name to simplify - * state handling. If so, can and need to use secondary token: - */ - if (_currToken == JsonToken.FIELD_NAME) { - return _nextAfterName(); - } - // But if we didn't already have a name, and (partially?) decode number, - // need to ensure no numeric information is leaked - _numTypesValid = NR_UNKNOWN; - if (_tokenIncomplete) { - _skipString(); // only strings can be partial - } - int i = _skipWSOrEnd(); - if (i < 0) { // end-of-input - // Close/release things like input source, symbol table and recyclable buffers - close(); - return (_currToken = null); - } - // clear any data retained so far - _binaryValue = null; - - // Closing scope? - if (i == INT_RBRACKET) { - _closeArrayScope(); - return (_currToken = JsonToken.END_ARRAY); - } - if (i == INT_RCURLY) { - _closeObjectScope(); - return (_currToken = JsonToken.END_OBJECT); - } - - // Nope: do we then expect a comma? - if (_parsingContext.expectComma()) { - if (i != INT_COMMA) { - _reportUnexpectedChar(i, "was expecting comma to separate "+_parsingContext.typeDesc()+" entries"); - } - i = _skipWS(); - // Was that a trailing comma? - if ((_features & FEAT_MASK_TRAILING_COMMA) != 0) { - if ((i == INT_RBRACKET) || (i == INT_RCURLY)) { - return _closeScope(i); - } - } - } - - /* And should we now have a name? Always true for Object contexts - * since the intermediate 'expect-value' state is never retained. - */ - if (!_parsingContext.inObject()) { - _updateLocation(); - return _nextTokenNotInObject(i); - } - // So first parse the field name itself: - _updateNameLocation(); - String n = _parseName(i); - _parsingContext.setCurrentName(n); - _currToken = JsonToken.FIELD_NAME; - - i = _skipColon(); - _updateLocation(); - - // Ok: we must have a value... what is it? Strings are very common, check first: - if (i == INT_QUOTE) { - _tokenIncomplete = true; - _nextToken = JsonToken.VALUE_STRING; - return _currToken; - } - JsonToken t; - - switch (i) { - case '-': - t = _parseNegNumber(); - break; - - /* Should we have separate handling for plus? Although - * it is not allowed per se, it may be erroneously used, - * and could be indicate by a more specific error message. - */ - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - t = _parsePosNumber(i); - break; - case 'f': - _matchToken("false", 1); - t = JsonToken.VALUE_FALSE; - break; - case 'n': - _matchToken("null", 1); - t = JsonToken.VALUE_NULL; - break; - case 't': - _matchToken("true", 1); - t = JsonToken.VALUE_TRUE; - break; - case '[': - t = JsonToken.START_ARRAY; - break; - case '{': - t = JsonToken.START_OBJECT; - break; - - default: - t = _handleUnexpectedValue(i); - } - _nextToken = t; - return _currToken; - } - - private final JsonToken _nextTokenNotInObject(int i) throws IOException - { - if (i == INT_QUOTE) { - _tokenIncomplete = true; - return (_currToken = JsonToken.VALUE_STRING); - } - switch (i) { - case '[': - _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); - return (_currToken = JsonToken.START_ARRAY); - case '{': - _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); - return (_currToken = JsonToken.START_OBJECT); - case 't': - _matchToken("true", 1); - return (_currToken = JsonToken.VALUE_TRUE); - case 'f': - _matchToken("false", 1); - return (_currToken = JsonToken.VALUE_FALSE); - case 'n': - _matchToken("null", 1); - return (_currToken = JsonToken.VALUE_NULL); - case '-': - return (_currToken = _parseNegNumber()); - /* Should we have separate handling for plus? Although - * it is not allowed per se, it may be erroneously used, - * and could be indicated by a more specific error message. - */ - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - return (_currToken = _parsePosNumber(i)); - } - return (_currToken = _handleUnexpectedValue(i)); - } - - private final JsonToken _nextAfterName() - { - _nameCopied = false; // need to invalidate if it was copied - JsonToken t = _nextToken; - _nextToken = null; - - // !!! 16-Nov-2015, tatu: TODO: fix [databind#37], copy next location to current here - - // Also: may need to start new context? - if (t == JsonToken.START_ARRAY) { - _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); - } else if (t == JsonToken.START_OBJECT) { - _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); - } - return (_currToken = t); - } - - @Override - public void finishToken() throws IOException { - if (_tokenIncomplete) { - _tokenIncomplete = false; - _finishString(); // only strings can be incomplete - } - } - - /* - /********************************************************** - /* Public API, traversal, nextXxxValue/nextFieldName - /********************************************************** - */ - - @Override - public boolean nextFieldName(SerializableString str) throws IOException - { - // // // Note: most of code below is copied from nextToken() - _numTypesValid = NR_UNKNOWN; - if (_currToken == JsonToken.FIELD_NAME) { // can't have name right after name - _nextAfterName(); - return false; - } - if (_tokenIncomplete) { - _skipString(); - } - int i = _skipWSOrEnd(); - if (i < 0) { // end-of-input - close(); - _currToken = null; - return false; - } - _binaryValue = null; - - // Closing scope? - if (i == INT_RBRACKET) { - _closeArrayScope(); - _currToken = JsonToken.END_ARRAY; - return false; - } - if (i == INT_RCURLY) { - _closeObjectScope(); - _currToken = JsonToken.END_OBJECT; - return false; - } - - // Nope: do we then expect a comma? - if (_parsingContext.expectComma()) { - if (i != INT_COMMA) { - _reportUnexpectedChar(i, "was expecting comma to separate "+_parsingContext.typeDesc()+" entries"); - } - i = _skipWS(); - - // Was that a trailing comma? - if ((_features & FEAT_MASK_TRAILING_COMMA) != 0) { - if ((i == INT_RBRACKET) || (i == INT_RCURLY)) { - _closeScope(i); - return false; - } - } - } - if (!_parsingContext.inObject()) { - _updateLocation(); - _nextTokenNotInObject(i); - return false; - } - - // // // This part differs, name parsing - _updateNameLocation(); - if (i == INT_QUOTE) { - // when doing literal match, must consider escaping: - byte[] nameBytes = str.asQuotedUTF8(); - final int len = nameBytes.length; - // 22-May-2014, tatu: Actually, let's require 4 more bytes for faster skipping - // of colon that follows name - if ((_inputPtr + len + 4) < _inputEnd) { // maybe... - // first check length match by - final int end = _inputPtr+len; - if (_inputBuffer[end] == INT_QUOTE) { - int offset = 0; - int ptr = _inputPtr; - while (true) { - if (ptr == end) { // yes, match! - _parsingContext.setCurrentName(str.getValue()); - i = _skipColonFast(ptr+1); - _isNextTokenNameYes(i); - return true; - } - if (nameBytes[offset] != _inputBuffer[ptr]) { - break; - } - ++offset; - ++ptr; - } - } - } - } - return _isNextTokenNameMaybe(i, str); - } - - @Override - public String nextFieldName() throws IOException - { - // // // Note: this is almost a verbatim copy of nextToken() - - _numTypesValid = NR_UNKNOWN; - if (_currToken == JsonToken.FIELD_NAME) { - _nextAfterName(); - return null; - } - if (_tokenIncomplete) { - _skipString(); - } - int i = _skipWSOrEnd(); - if (i < 0) { - close(); - _currToken = null; - return null; - } - _binaryValue = null; - - if (i == INT_RBRACKET) { - _closeArrayScope(); - _currToken = JsonToken.END_ARRAY; - return null; - } - if (i == INT_RCURLY) { - _closeObjectScope(); - _currToken = JsonToken.END_OBJECT; - return null; - } - - // Nope: do we then expect a comma? - if (_parsingContext.expectComma()) { - if (i != INT_COMMA) { - _reportUnexpectedChar(i, "was expecting comma to separate "+_parsingContext.typeDesc()+" entries"); - } - i = _skipWS(); - // Was that a trailing comma? - if ((_features & FEAT_MASK_TRAILING_COMMA) != 0) { - if ((i == INT_RBRACKET) || (i == INT_RCURLY)) { - _closeScope(i); - return null; - } - } - } - - if (!_parsingContext.inObject()) { - _updateLocation(); - _nextTokenNotInObject(i); - return null; - } - - _updateNameLocation(); - final String nameStr = _parseName(i); - _parsingContext.setCurrentName(nameStr); - _currToken = JsonToken.FIELD_NAME; - - i = _skipColon(); - _updateLocation(); - if (i == INT_QUOTE) { - _tokenIncomplete = true; - _nextToken = JsonToken.VALUE_STRING; - return nameStr; - } - JsonToken t; - switch (i) { - case '-': - t = _parseNegNumber(); - break; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - t = _parsePosNumber(i); - break; - case 'f': - _matchToken("false", 1); - t = JsonToken.VALUE_FALSE; - break; - case 'n': - _matchToken("null", 1); - t = JsonToken.VALUE_NULL; - break; - case 't': - _matchToken("true", 1); - t = JsonToken.VALUE_TRUE; - break; - case '[': - t = JsonToken.START_ARRAY; - break; - case '{': - t = JsonToken.START_OBJECT; - break; - - default: - t = _handleUnexpectedValue(i); - } - _nextToken = t; - return nameStr; - } - - // Variant called when we know there's at least 4 more bytes available - private final int _skipColonFast(int ptr) throws IOException - { - int i = _inputBuffer[ptr++]; - if (i == INT_COLON) { // common case, no leading space - i = _inputBuffer[ptr++]; - if (i > INT_SPACE) { // nor trailing - if (i != INT_SLASH && i != INT_HASH) { - _inputPtr = ptr; - return i; - } - } else if (i == INT_SPACE || i == INT_TAB) { - i = (int) _inputBuffer[ptr++]; - if (i > INT_SPACE) { - if (i != INT_SLASH && i != INT_HASH) { - _inputPtr = ptr; - return i; - } - } - } - _inputPtr = ptr-1; - return _skipColon2(true); // true -> skipped colon - } - if (i == INT_SPACE || i == INT_TAB) { - i = _inputBuffer[ptr++]; - } - if (i == INT_COLON) { - i = _inputBuffer[ptr++]; - if (i > INT_SPACE) { - if (i != INT_SLASH && i != INT_HASH) { - _inputPtr = ptr; - return i; - } - } else if (i == INT_SPACE || i == INT_TAB) { - i = (int) _inputBuffer[ptr++]; - if (i > INT_SPACE) { - if (i != INT_SLASH && i != INT_HASH) { - _inputPtr = ptr; - return i; - } - } - } - _inputPtr = ptr-1; - return _skipColon2(true); - } - _inputPtr = ptr-1; - return _skipColon2(false); - } - - private final void _isNextTokenNameYes(int i) throws IOException - { - _currToken = JsonToken.FIELD_NAME; - _updateLocation(); - - switch (i) { - case '"': - _tokenIncomplete = true; - _nextToken = JsonToken.VALUE_STRING; - return; - case '[': - _nextToken = JsonToken.START_ARRAY; - return; - case '{': - _nextToken = JsonToken.START_OBJECT; - return; - case 't': - _matchToken("true", 1); - _nextToken = JsonToken.VALUE_TRUE; - return; - case 'f': - _matchToken("false", 1); - _nextToken = JsonToken.VALUE_FALSE; - return; - case 'n': - _matchToken("null", 1); - _nextToken = JsonToken.VALUE_NULL; - return; - case '-': - _nextToken = _parseNegNumber(); - return; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - _nextToken = _parsePosNumber(i); - return; - } - _nextToken = _handleUnexpectedValue(i); - } - - private final boolean _isNextTokenNameMaybe(int i, SerializableString str) throws IOException - { - // // // and this is back to standard nextToken() - - String n = _parseName(i); - _parsingContext.setCurrentName(n); - final boolean match = n.equals(str.getValue()); - _currToken = JsonToken.FIELD_NAME; - i = _skipColon(); - _updateLocation(); - - // Ok: we must have a value... what is it? Strings are very common, check first: - if (i == INT_QUOTE) { - _tokenIncomplete = true; - _nextToken = JsonToken.VALUE_STRING; - return match; - } - JsonToken t; - - switch (i) { - case '[': - t = JsonToken.START_ARRAY; - break; - case '{': - t = JsonToken.START_OBJECT; - break; - case 't': - _matchToken("true", 1); - t = JsonToken.VALUE_TRUE; - break; - case 'f': - _matchToken("false", 1); - t = JsonToken.VALUE_FALSE; - break; - case 'n': - _matchToken("null", 1); - t = JsonToken.VALUE_NULL; - break; - case '-': - t = _parseNegNumber(); - break; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - t = _parsePosNumber(i); - break; - default: - t = _handleUnexpectedValue(i); - } - _nextToken = t; - return match; - } - - @Override - public String nextTextValue() throws IOException - { - // two distinct cases; either got name and we know next type, or 'other' - if (_currToken == JsonToken.FIELD_NAME) { // mostly copied from '_nextAfterName' - _nameCopied = false; - JsonToken t = _nextToken; - _nextToken = null; - _currToken = t; - if (t == JsonToken.VALUE_STRING) { - if (_tokenIncomplete) { - _tokenIncomplete = false; - return _finishAndReturnString(); - } - return _textBuffer.contentsAsString(); - } - if (t == JsonToken.START_ARRAY) { - _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); - } else if (t == JsonToken.START_OBJECT) { - _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); - } - return null; - } - // !!! TODO: optimize this case as well - return (nextToken() == JsonToken.VALUE_STRING) ? getText() : null; - } - - @Override - public int nextIntValue(int defaultValue) throws IOException - { - // two distinct cases; either got name and we know next type, or 'other' - if (_currToken == JsonToken.FIELD_NAME) { // mostly copied from '_nextAfterName' - _nameCopied = false; - JsonToken t = _nextToken; - _nextToken = null; - _currToken = t; - if (t == JsonToken.VALUE_NUMBER_INT) { - return getIntValue(); - } - if (t == JsonToken.START_ARRAY) { - _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); - } else if (t == JsonToken.START_OBJECT) { - _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); - } - return defaultValue; - } - // !!! TODO: optimize this case as well - return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getIntValue() : defaultValue; - } - - @Override - public long nextLongValue(long defaultValue) throws IOException - { - // two distinct cases; either got name and we know next type, or 'other' - if (_currToken == JsonToken.FIELD_NAME) { // mostly copied from '_nextAfterName' - _nameCopied = false; - JsonToken t = _nextToken; - _nextToken = null; - _currToken = t; - if (t == JsonToken.VALUE_NUMBER_INT) { - return getLongValue(); - } - if (t == JsonToken.START_ARRAY) { - _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); - } else if (t == JsonToken.START_OBJECT) { - _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); - } - return defaultValue; - } - // !!! TODO: optimize this case as well - return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getLongValue() : defaultValue; - } - - @Override - public Boolean nextBooleanValue() throws IOException - { - // two distinct cases; either got name and we know next type, or 'other' - if (_currToken == JsonToken.FIELD_NAME) { // mostly copied from '_nextAfterName' - _nameCopied = false; - JsonToken t = _nextToken; - _nextToken = null; - _currToken = t; - if (t == JsonToken.VALUE_TRUE) { - return Boolean.TRUE; - } - if (t == JsonToken.VALUE_FALSE) { - return Boolean.FALSE; - } - if (t == JsonToken.START_ARRAY) { - _parsingContext = _parsingContext.createChildArrayContext(_tokenInputRow, _tokenInputCol); - } else if (t == JsonToken.START_OBJECT) { - _parsingContext = _parsingContext.createChildObjectContext(_tokenInputRow, _tokenInputCol); - } - return null; - } - - JsonToken t = nextToken(); - if (t == JsonToken.VALUE_TRUE) { - return Boolean.TRUE; - } - if (t == JsonToken.VALUE_FALSE) { - return Boolean.FALSE; - } - return null; - } - - /* - /********************************************************** - /* Internal methods, number parsing - /********************************************************** - */ - - /** - * Initial parsing method for number values. It needs to be able - * to parse enough input to be able to determine whether the - * value is to be considered a simple integer value, or a more - * generic decimal value: latter of which needs to be expressed - * as a floating point number. The basic rule is that if the number - * has no fractional or exponential part, it is an integer; otherwise - * a floating point number. - *

- * Because much of input has to be processed in any case, no partial - * parsing is done: all input text will be stored for further - * processing. However, actual numeric value conversion will be - * deferred, since it is usually the most complicated and costliest - * part of processing. - */ - protected JsonToken _parsePosNumber(int c) throws IOException - { - char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); - // One special case: if first char is 0, must not be followed by a digit - if (c == INT_0) { - c = _verifyNoLeadingZeroes(); - } - // Ok: we can first just add digit we saw first: - outBuf[0] = (char) c; - int intLen = 1; - int outPtr = 1; - // And then figure out how far we can read without further checks - // for either input or output - int end = _inputPtr + outBuf.length - 1; // 1 == outPtr - if (end > _inputEnd) { - end = _inputEnd; - } - // With this, we have a nice and tight loop: - while (true) { - if (_inputPtr >= end) { // split across boundary, offline - return _parseNumber2(outBuf, outPtr, false, intLen); - } - c = (int) _inputBuffer[_inputPtr++] & 0xFF; - if (c < INT_0 || c > INT_9) { - break; - } - ++intLen; - outBuf[outPtr++] = (char) c; - } - if (c == '.' || c == 'e' || c == 'E') { - return _parseFloat(outBuf, outPtr, c, false, intLen); - } - --_inputPtr; // to push back trailing char (comma etc) - _textBuffer.setCurrentLength(outPtr); - // As per #105, need separating space between root values; check here - if (_parsingContext.inRoot()) { - _verifyRootSpace(c); - } - // And there we have it! - return resetInt(false, intLen); - } - - protected JsonToken _parseNegNumber() throws IOException - { - char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); - int outPtr = 0; - - // Need to prepend sign? - outBuf[outPtr++] = '-'; - // Must have something after sign too - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - int c = (int) _inputBuffer[_inputPtr++] & 0xFF; - // Note: must be followed by a digit - if (c < INT_0 || c > INT_9) { - return _handleInvalidNumberStart(c, true); - } - - // One special case: if first char is 0, must not be followed by a digit - if (c == INT_0) { - c = _verifyNoLeadingZeroes(); - } - - // Ok: we can first just add digit we saw first: - outBuf[outPtr++] = (char) c; - int intLen = 1; - - // And then figure out how far we can read without further checks - // for either input or output - int end = _inputPtr + outBuf.length - outPtr; - if (end > _inputEnd) { - end = _inputEnd; - } - - // With this, we have a nice and tight loop: - while (true) { - if (_inputPtr >= end) { - // Long enough to be split across boundary, so: - return _parseNumber2(outBuf, outPtr, true, intLen); - } - c = (int) _inputBuffer[_inputPtr++] & 0xFF; - if (c < INT_0 || c > INT_9) { - break; - } - ++intLen; - outBuf[outPtr++] = (char) c; - } - if (c == '.' || c == 'e' || c == 'E') { - return _parseFloat(outBuf, outPtr, c, true, intLen); - } - - --_inputPtr; // to push back trailing char (comma etc) - _textBuffer.setCurrentLength(outPtr); - // As per #105, need separating space between root values; check here - if (_parsingContext.inRoot()) { - _verifyRootSpace(c); - } - - // And there we have it! - return resetInt(true, intLen); - } - - /** - * Method called to handle parsing when input is split across buffer boundary - * (or output is longer than segment used to store it) - */ - private final JsonToken _parseNumber2(char[] outBuf, int outPtr, boolean negative, - int intPartLength) throws IOException - { - // Ok, parse the rest - while (true) { - if (_inputPtr >= _inputEnd && !_loadMore()) { - _textBuffer.setCurrentLength(outPtr); - return resetInt(negative, intPartLength); - } - int c = (int) _inputBuffer[_inputPtr++] & 0xFF; - if (c > INT_9 || c < INT_0) { - if (c == INT_PERIOD || c == INT_e || c == INT_E) { - return _parseFloat(outBuf, outPtr, c, negative, intPartLength); - } - break; - } - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - outBuf[outPtr++] = (char) c; - ++intPartLength; - } - --_inputPtr; // to push back trailing char (comma etc) - _textBuffer.setCurrentLength(outPtr); - // As per #105, need separating space between root values; check here - if (_parsingContext.inRoot()) { - _verifyRootSpace(_inputBuffer[_inputPtr++] & 0xFF); - } - - // And there we have it! - return resetInt(negative, intPartLength); - - } - - /** - * Method called when we have seen one zero, and want to ensure - * it is not followed by another - */ - private final int _verifyNoLeadingZeroes() throws IOException - { - // Ok to have plain "0" - if (_inputPtr >= _inputEnd && !_loadMore()) { - return INT_0; - } - int ch = _inputBuffer[_inputPtr] & 0xFF; - // if not followed by a number (probably '.'); return zero as is, to be included - if (ch < INT_0 || ch > INT_9) { - return INT_0; - } - // [JACKSON-358]: we may want to allow them, after all... - if (!isEnabled(Feature.ALLOW_NUMERIC_LEADING_ZEROS)) { - reportInvalidNumber("Leading zeroes not allowed"); - } - // if so, just need to skip either all zeroes (if followed by number); or all but one (if non-number) - ++_inputPtr; // Leading zero to be skipped - if (ch == INT_0) { - while (_inputPtr < _inputEnd || _loadMore()) { - ch = _inputBuffer[_inputPtr] & 0xFF; - if (ch < INT_0 || ch > INT_9) { // followed by non-number; retain one zero - return INT_0; - } - ++_inputPtr; // skip previous zeroes - if (ch != INT_0) { // followed by other number; return - break; - } - } - } - return ch; - } - - private final JsonToken _parseFloat(char[] outBuf, int outPtr, int c, - boolean negative, int integerPartLength) throws IOException - { - int fractLen = 0; - boolean eof = false; - - // And then see if we get other parts - if (c == INT_PERIOD) { // yes, fraction - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - outBuf[outPtr++] = (char) c; - - fract_loop: - while (true) { - if (_inputPtr >= _inputEnd && !_loadMore()) { - eof = true; - break fract_loop; - } - c = (int) _inputBuffer[_inputPtr++] & 0xFF; - if (c < INT_0 || c > INT_9) { - break fract_loop; - } - ++fractLen; - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - outBuf[outPtr++] = (char) c; - } - // must be followed by sequence of ints, one minimum - if (fractLen == 0) { - reportUnexpectedNumberChar(c, "Decimal point not followed by a digit"); - } - } - - int expLen = 0; - if (c == INT_e || c == INT_E) { // exponent? - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - outBuf[outPtr++] = (char) c; - // Not optional, can require that we get one more char - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - c = (int) _inputBuffer[_inputPtr++] & 0xFF; - // Sign indicator? - if (c == '-' || c == '+') { - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - outBuf[outPtr++] = (char) c; - // Likewise, non optional: - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - c = (int) _inputBuffer[_inputPtr++] & 0xFF; - } - - exp_loop: - while (c <= INT_9 && c >= INT_0) { - ++expLen; - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - outBuf[outPtr++] = (char) c; - if (_inputPtr >= _inputEnd && !_loadMore()) { - eof = true; - break exp_loop; - } - c = (int) _inputBuffer[_inputPtr++] & 0xFF; - } - // must be followed by sequence of ints, one minimum - if (expLen == 0) { - reportUnexpectedNumberChar(c, "Exponent indicator not followed by a digit"); - } - } - - // Ok; unless we hit end-of-input, need to push last char read back - if (!eof) { - --_inputPtr; - // As per [core#105], need separating space between root values; check here - if (_parsingContext.inRoot()) { - _verifyRootSpace(c); - } - } - _textBuffer.setCurrentLength(outPtr); - - // And there we have it! - return resetFloat(negative, integerPartLength, fractLen, expLen); - } - - /** - * Method called to ensure that a root-value is followed by a space - * token. - *

- * NOTE: caller MUST ensure there is at least one character available; - * and that input pointer is AT given char (not past) - */ - private final void _verifyRootSpace(int ch) throws IOException - { - // caller had pushed it back, before calling; reset - ++_inputPtr; - // TODO? Handle UTF-8 char decoding for error reporting - switch (ch) { - case ' ': - case '\t': - return; - case '\r': - _skipCR(); - return; - case '\n': - ++_currInputRow; - _currInputRowStart = _inputPtr; - return; - } - _reportMissingRootWS(ch); - } - - /* - /********************************************************** - /* Internal methods, secondary parsing - /********************************************************** - */ - - protected final String _parseName(int i) throws IOException - { - if (i != INT_QUOTE) { - return _handleOddName(i); - } - // First: can we optimize out bounds checks? - if ((_inputPtr + 13) > _inputEnd) { // Need up to 12 chars, plus one trailing (quote) - return slowParseName(); - } - - // If so, can also unroll loops nicely - /* 25-Nov-2008, tatu: This may seem weird, but here we do - * NOT want to worry about UTF-8 decoding. Rather, we'll - * assume that part is ok (if not it will get caught - * later on), and just handle quotes and backslashes here. - */ - final byte[] input = _inputBuffer; - final int[] codes = _icLatin1; - - int q = input[_inputPtr++] & 0xFF; - - if (codes[q] == 0) { - i = input[_inputPtr++] & 0xFF; - if (codes[i] == 0) { - q = (q << 8) | i; - i = input[_inputPtr++] & 0xFF; - if (codes[i] == 0) { - q = (q << 8) | i; - i = input[_inputPtr++] & 0xFF; - if (codes[i] == 0) { - q = (q << 8) | i; - i = input[_inputPtr++] & 0xFF; - if (codes[i] == 0) { - _quad1 = q; - return parseMediumName(i); - } - if (i == INT_QUOTE) { // 4 byte/char case or broken - return findName(q, 4); - } - return parseName(q, i, 4); - } - if (i == INT_QUOTE) { // 3 byte/char case or broken - return findName(q, 3); - } - return parseName(q, i, 3); - } - if (i == INT_QUOTE) { // 2 byte/char case or broken - return findName(q, 2); - } - return parseName(q, i, 2); - } - if (i == INT_QUOTE) { // one byte/char case or broken - return findName(q, 1); - } - return parseName(q, i, 1); - } - if (q == INT_QUOTE) { // special case, "" - return ""; - } - return parseName(0, q, 0); // quoting or invalid char - } - - protected final String parseMediumName(int q2) throws IOException - { - final byte[] input = _inputBuffer; - final int[] codes = _icLatin1; - - // Ok, got 5 name bytes so far - int i = input[_inputPtr++] & 0xFF; - if (codes[i] != 0) { - if (i == INT_QUOTE) { // 5 bytes - return findName(_quad1, q2, 1); - } - return parseName(_quad1, q2, i, 1); // quoting or invalid char - } - q2 = (q2 << 8) | i; - i = input[_inputPtr++] & 0xFF; - if (codes[i] != 0) { - if (i == INT_QUOTE) { // 6 bytes - return findName(_quad1, q2, 2); - } - return parseName(_quad1, q2, i, 2); - } - q2 = (q2 << 8) | i; - i = input[_inputPtr++] & 0xFF; - if (codes[i] != 0) { - if (i == INT_QUOTE) { // 7 bytes - return findName(_quad1, q2, 3); - } - return parseName(_quad1, q2, i, 3); - } - q2 = (q2 << 8) | i; - i = input[_inputPtr++] & 0xFF; - if (codes[i] != 0) { - if (i == INT_QUOTE) { // 8 bytes - return findName(_quad1, q2, 4); - } - return parseName(_quad1, q2, i, 4); - } - return parseMediumName2(i, q2); - } - - /** - * @since 2.6 - */ - protected final String parseMediumName2(int q3, final int q2) throws IOException - { - final byte[] input = _inputBuffer; - final int[] codes = _icLatin1; - - // Got 9 name bytes so far - int i = input[_inputPtr++] & 0xFF; - if (codes[i] != 0) { - if (i == INT_QUOTE) { // 9 bytes - return findName(_quad1, q2, q3, 1); - } - return parseName(_quad1, q2, q3, i, 1); - } - q3 = (q3 << 8) | i; - i = input[_inputPtr++] & 0xFF; - if (codes[i] != 0) { - if (i == INT_QUOTE) { // 10 bytes - return findName(_quad1, q2, q3, 2); - } - return parseName(_quad1, q2, q3, i, 2); - } - q3 = (q3 << 8) | i; - i = input[_inputPtr++] & 0xFF; - if (codes[i] != 0) { - if (i == INT_QUOTE) { // 11 bytes - return findName(_quad1, q2, q3, 3); - } - return parseName(_quad1, q2, q3, i, 3); - } - q3 = (q3 << 8) | i; - i = input[_inputPtr++] & 0xFF; - if (codes[i] != 0) { - if (i == INT_QUOTE) { // 12 bytes - return findName(_quad1, q2, q3, 4); - } - return parseName(_quad1, q2, q3, i, 4); - } - return parseLongName(i, q2, q3); - } - - protected final String parseLongName(int q, final int q2, int q3) throws IOException - { - _quadBuffer[0] = _quad1; - _quadBuffer[1] = q2; - _quadBuffer[2] = q3; - - // As explained above, will ignore UTF-8 encoding at this point - final byte[] input = _inputBuffer; - final int[] codes = _icLatin1; - int qlen = 3; - - while ((_inputPtr + 4) <= _inputEnd) { - int i = input[_inputPtr++] & 0xFF; - if (codes[i] != 0) { - if (i == INT_QUOTE) { - return findName(_quadBuffer, qlen, q, 1); - } - return parseEscapedName(_quadBuffer, qlen, q, i, 1); - } - - q = (q << 8) | i; - i = input[_inputPtr++] & 0xFF; - if (codes[i] != 0) { - if (i == INT_QUOTE) { - return findName(_quadBuffer, qlen, q, 2); - } - return parseEscapedName(_quadBuffer, qlen, q, i, 2); - } - - q = (q << 8) | i; - i = input[_inputPtr++] & 0xFF; - if (codes[i] != 0) { - if (i == INT_QUOTE) { - return findName(_quadBuffer, qlen, q, 3); - } - return parseEscapedName(_quadBuffer, qlen, q, i, 3); - } - - q = (q << 8) | i; - i = input[_inputPtr++] & 0xFF; - if (codes[i] != 0) { - if (i == INT_QUOTE) { - return findName(_quadBuffer, qlen, q, 4); - } - return parseEscapedName(_quadBuffer, qlen, q, i, 4); - } - - // Nope, no end in sight. Need to grow quad array etc - if (qlen >= _quadBuffer.length) { - _quadBuffer = growArrayBy(_quadBuffer, qlen); - } - _quadBuffer[qlen++] = q; - q = i; - } - - /* Let's offline if we hit buffer boundary (otherwise would - * need to [try to] align input, which is bit complicated - * and may not always be possible) - */ - return parseEscapedName(_quadBuffer, qlen, 0, q, 0); - } - - /** - * Method called when not even first 8 bytes are guaranteed - * to come consecutively. Happens rarely, so this is offlined; - * plus we'll also do full checks for escaping etc. - */ - protected String slowParseName() throws IOException - { - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { - _reportInvalidEOF(": was expecting closing '\"' for name", JsonToken.FIELD_NAME); - } - } - int i = _inputBuffer[_inputPtr++] & 0xFF; - if (i == INT_QUOTE) { // special case, "" - return ""; - } - return parseEscapedName(_quadBuffer, 0, 0, i, 0); - } - - private final String parseName(int q1, int ch, int lastQuadBytes) throws IOException { - return parseEscapedName(_quadBuffer, 0, q1, ch, lastQuadBytes); - } - - private final String parseName(int q1, int q2, int ch, int lastQuadBytes) throws IOException { - _quadBuffer[0] = q1; - return parseEscapedName(_quadBuffer, 1, q2, ch, lastQuadBytes); - } - - private final String parseName(int q1, int q2, int q3, int ch, int lastQuadBytes) throws IOException { - _quadBuffer[0] = q1; - _quadBuffer[1] = q2; - return parseEscapedName(_quadBuffer, 2, q3, ch, lastQuadBytes); - } - - /** - * Slower parsing method which is generally branched to when - * an escape sequence is detected (or alternatively for long - * names, one crossing input buffer boundary). - * Needs to be able to handle more exceptional cases, gets slower, - * and hence is offlined to a separate method. - */ - protected final String parseEscapedName(int[] quads, int qlen, int currQuad, int ch, - int currQuadBytes) throws IOException - { - /* 25-Nov-2008, tatu: This may seem weird, but here we do not want to worry about - * UTF-8 decoding yet. Rather, we'll assume that part is ok (if not it will get - * caught later on), and just handle quotes and backslashes here. - */ - final int[] codes = _icLatin1; - - while (true) { - if (codes[ch] != 0) { - if (ch == INT_QUOTE) { // we are done - break; - } - // Unquoted white space? - if (ch != INT_BACKSLASH) { - // As per [JACKSON-208], call can now return: - _throwUnquotedSpace(ch, "name"); - } else { - // Nope, escape sequence - ch = _decodeEscaped(); - } - /* Oh crap. May need to UTF-8 (re-)encode it, if it's - * beyond 7-bit ASCII. Gets pretty messy. - * If this happens often, may want to use different name - * canonicalization to avoid these hits. - */ - if (ch > 127) { - // Ok, we'll need room for first byte right away - if (currQuadBytes >= 4) { - if (qlen >= quads.length) { - _quadBuffer = quads = growArrayBy(quads, quads.length); - } - quads[qlen++] = currQuad; - currQuad = 0; - currQuadBytes = 0; - } - if (ch < 0x800) { // 2-byte - currQuad = (currQuad << 8) | (0xc0 | (ch >> 6)); - ++currQuadBytes; - // Second byte gets output below: - } else { // 3 bytes; no need to worry about surrogates here - currQuad = (currQuad << 8) | (0xe0 | (ch >> 12)); - ++currQuadBytes; - // need room for middle byte? - if (currQuadBytes >= 4) { - if (qlen >= quads.length) { - _quadBuffer = quads = growArrayBy(quads, quads.length); - } - quads[qlen++] = currQuad; - currQuad = 0; - currQuadBytes = 0; - } - currQuad = (currQuad << 8) | (0x80 | ((ch >> 6) & 0x3f)); - ++currQuadBytes; - } - // And same last byte in both cases, gets output below: - ch = 0x80 | (ch & 0x3f); - } - } - // Ok, we have one more byte to add at any rate: - if (currQuadBytes < 4) { - ++currQuadBytes; - currQuad = (currQuad << 8) | ch; - } else { - if (qlen >= quads.length) { - _quadBuffer = quads = growArrayBy(quads, quads.length); - } - quads[qlen++] = currQuad; - currQuad = ch; - currQuadBytes = 1; - } - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { - _reportInvalidEOF(" in field name", JsonToken.FIELD_NAME); - } - } - ch = _inputBuffer[_inputPtr++] & 0xFF; - } - - if (currQuadBytes > 0) { - if (qlen >= quads.length) { - _quadBuffer = quads = growArrayBy(quads, quads.length); - } - quads[qlen++] = pad(currQuad, currQuadBytes); - } - String name = _symbols.findName(quads, qlen); - if (name == null) { - name = addName(quads, qlen, currQuadBytes); - } - return name; - } - - /** - * Method called when we see non-white space character other - * than double quote, when expecting a field name. - * In standard mode will just throw an exception; but - * in non-standard modes may be able to parse name. - */ - protected String _handleOddName(int ch) throws IOException - { - // [JACKSON-173]: allow single quotes - if (ch == '\'' && isEnabled(Feature.ALLOW_SINGLE_QUOTES)) { - return _parseAposName(); - } - // [JACKSON-69]: allow unquoted names if feature enabled: - if (!isEnabled(Feature.ALLOW_UNQUOTED_FIELD_NAMES)) { - char c = (char) _decodeCharForError(ch); - _reportUnexpectedChar(c, "was expecting double-quote to start field name"); - } - /* Also: note that although we use a different table here, - * it does NOT handle UTF-8 decoding. It'll just pass those - * high-bit codes as acceptable for later decoding. - */ - final int[] codes = CharTypes.getInputCodeUtf8JsNames(); - // Also: must start with a valid character... - if (codes[ch] != 0) { - _reportUnexpectedChar(ch, "was expecting either valid name character (for unquoted name) or double-quote (for quoted) to start field name"); - } - - /* Ok, now; instead of ultra-optimizing parsing here (as with - * regular JSON names), let's just use the generic "slow" - * variant. Can measure its impact later on if need be - */ - int[] quads = _quadBuffer; - int qlen = 0; - int currQuad = 0; - int currQuadBytes = 0; - - while (true) { - // Ok, we have one more byte to add at any rate: - if (currQuadBytes < 4) { - ++currQuadBytes; - currQuad = (currQuad << 8) | ch; - } else { - if (qlen >= quads.length) { - _quadBuffer = quads = growArrayBy(quads, quads.length); - } - quads[qlen++] = currQuad; - currQuad = ch; - currQuadBytes = 1; - } - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { - _reportInvalidEOF(" in field name", JsonToken.FIELD_NAME); - } - } - ch = _inputBuffer[_inputPtr] & 0xFF; - if (codes[ch] != 0) { - break; - } - ++_inputPtr; - } - - if (currQuadBytes > 0) { - if (qlen >= quads.length) { - _quadBuffer = quads = growArrayBy(quads, quads.length); - } - quads[qlen++] = currQuad; - } - String name = _symbols.findName(quads, qlen); - if (name == null) { - name = addName(quads, qlen, currQuadBytes); - } - return name; - } - - /* Parsing to support [JACKSON-173]. Plenty of duplicated code; - * main reason being to try to avoid slowing down fast path - * for valid JSON -- more alternatives, more code, generally - * bit slower execution. - */ - protected String _parseAposName() throws IOException - { - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { - _reportInvalidEOF(": was expecting closing '\'' for field name", JsonToken.FIELD_NAME); - } - } - int ch = _inputBuffer[_inputPtr++] & 0xFF; - if (ch == '\'') { // special case, '' - return ""; - } - int[] quads = _quadBuffer; - int qlen = 0; - int currQuad = 0; - int currQuadBytes = 0; - - // Copied from parseEscapedFieldName, with minor mods: - - final int[] codes = _icLatin1; - - while (true) { - if (ch == '\'') { - break; - } - // additional check to skip handling of double-quotes - if (ch != '"' && codes[ch] != 0) { - if (ch != '\\') { - // Unquoted white space? - // As per [JACKSON-208], call can now return: - _throwUnquotedSpace(ch, "name"); - } else { - // Nope, escape sequence - ch = _decodeEscaped(); - } - /* Oh crap. May need to UTF-8 (re-)encode it, if it's - * beyond 7-bit ascii. Gets pretty messy. - * If this happens often, may want to use different name - * canonicalization to avoid these hits. - */ - if (ch > 127) { - // Ok, we'll need room for first byte right away - if (currQuadBytes >= 4) { - if (qlen >= quads.length) { - _quadBuffer = quads = growArrayBy(quads, quads.length); - } - quads[qlen++] = currQuad; - currQuad = 0; - currQuadBytes = 0; - } - if (ch < 0x800) { // 2-byte - currQuad = (currQuad << 8) | (0xc0 | (ch >> 6)); - ++currQuadBytes; - // Second byte gets output below: - } else { // 3 bytes; no need to worry about surrogates here - currQuad = (currQuad << 8) | (0xe0 | (ch >> 12)); - ++currQuadBytes; - // need room for middle byte? - if (currQuadBytes >= 4) { - if (qlen >= quads.length) { - _quadBuffer = quads = growArrayBy(quads, quads.length); - } - quads[qlen++] = currQuad; - currQuad = 0; - currQuadBytes = 0; - } - currQuad = (currQuad << 8) | (0x80 | ((ch >> 6) & 0x3f)); - ++currQuadBytes; - } - // And same last byte in both cases, gets output below: - ch = 0x80 | (ch & 0x3f); - } - } - // Ok, we have one more byte to add at any rate: - if (currQuadBytes < 4) { - ++currQuadBytes; - currQuad = (currQuad << 8) | ch; - } else { - if (qlen >= quads.length) { - _quadBuffer = quads = growArrayBy(quads, quads.length); - } - quads[qlen++] = currQuad; - currQuad = ch; - currQuadBytes = 1; - } - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { - _reportInvalidEOF(" in field name", JsonToken.FIELD_NAME); - } - } - ch = _inputBuffer[_inputPtr++] & 0xFF; - } - - if (currQuadBytes > 0) { - if (qlen >= quads.length) { - _quadBuffer = quads = growArrayBy(quads, quads.length); - } - quads[qlen++] = pad(currQuad, currQuadBytes); - } - String name = _symbols.findName(quads, qlen); - if (name == null) { - name = addName(quads, qlen, currQuadBytes); - } - return name; - } - - /* - /********************************************************** - /* Internal methods, symbol (name) handling - /********************************************************** - */ - - private final String findName(int q1, int lastQuadBytes) throws JsonParseException - { - q1 = pad(q1, lastQuadBytes); - // Usually we'll find it from the canonical symbol table already - String name = _symbols.findName(q1); - if (name != null) { - return name; - } - // If not, more work. We'll need add stuff to buffer - _quadBuffer[0] = q1; - return addName(_quadBuffer, 1, lastQuadBytes); - } - - private final String findName(int q1, int q2, int lastQuadBytes) throws JsonParseException - { - q2 = pad(q2, lastQuadBytes); - // Usually we'll find it from the canonical symbol table already - String name = _symbols.findName(q1, q2); - if (name != null) { - return name; - } - // If not, more work. We'll need add stuff to buffer - _quadBuffer[0] = q1; - _quadBuffer[1] = q2; - return addName(_quadBuffer, 2, lastQuadBytes); - } - - private final String findName(int q1, int q2, int q3, int lastQuadBytes) throws JsonParseException - { - q3 = pad(q3, lastQuadBytes); - String name = _symbols.findName(q1, q2, q3); - if (name != null) { - return name; - } - int[] quads = _quadBuffer; - quads[0] = q1; - quads[1] = q2; - quads[2] = pad(q3, lastQuadBytes); - return addName(quads, 3, lastQuadBytes); - } - - private final String findName(int[] quads, int qlen, int lastQuad, int lastQuadBytes) throws JsonParseException - { - if (qlen >= quads.length) { - _quadBuffer = quads = growArrayBy(quads, quads.length); - } - quads[qlen++] = pad(lastQuad, lastQuadBytes); - String name = _symbols.findName(quads, qlen); - if (name == null) { - return addName(quads, qlen, lastQuadBytes); - } - return name; - } - - /** - * This is the main workhorse method used when we take a symbol - * table miss. It needs to demultiplex individual bytes, decode - * multi-byte chars (if any), and then construct Name instance - * and add it to the symbol table. - */ - private final String addName(int[] quads, int qlen, int lastQuadBytes) throws JsonParseException - { - /* Ok: must decode UTF-8 chars. No other validation is - * needed, since unescaping has been done earlier as necessary - * (as well as error reporting for unescaped control chars) - */ - // 4 bytes per quad, except last one maybe less - int byteLen = (qlen << 2) - 4 + lastQuadBytes; - - /* And last one is not correctly aligned (leading zero bytes instead - * need to shift a bit, instead of trailing). Only need to shift it - * for UTF-8 decoding; need revert for storage (since key will not - * be aligned, to optimize lookup speed) - */ - int lastQuad; - - if (lastQuadBytes < 4) { - lastQuad = quads[qlen-1]; - // 8/16/24 bit left shift - quads[qlen-1] = (lastQuad << ((4 - lastQuadBytes) << 3)); - } else { - lastQuad = 0; - } - - // Need some working space, TextBuffer works well: - char[] cbuf = _textBuffer.emptyAndGetCurrentSegment(); - int cix = 0; - - for (int ix = 0; ix < byteLen; ) { - int ch = quads[ix >> 2]; // current quad, need to shift+mask - int byteIx = (ix & 3); - ch = (ch >> ((3 - byteIx) << 3)) & 0xFF; - ++ix; - - if (ch > 127) { // multi-byte - int needed; - if ((ch & 0xE0) == 0xC0) { // 2 bytes (0x0080 - 0x07FF) - ch &= 0x1F; - needed = 1; - } else if ((ch & 0xF0) == 0xE0) { // 3 bytes (0x0800 - 0xFFFF) - ch &= 0x0F; - needed = 2; - } else if ((ch & 0xF8) == 0xF0) { // 4 bytes; double-char with surrogates and all... - ch &= 0x07; - needed = 3; - } else { // 5- and 6-byte chars not valid xml chars - _reportInvalidInitial(ch); - needed = ch = 1; // never really gets this far - } - if ((ix + needed) > byteLen) { - _reportInvalidEOF(" in field name", JsonToken.FIELD_NAME); - } - - // Ok, always need at least one more: - int ch2 = quads[ix >> 2]; // current quad, need to shift+mask - byteIx = (ix & 3); - ch2 = (ch2 >> ((3 - byteIx) << 3)); - ++ix; - - if ((ch2 & 0xC0) != 0x080) { - _reportInvalidOther(ch2); - } - ch = (ch << 6) | (ch2 & 0x3F); - if (needed > 1) { - ch2 = quads[ix >> 2]; - byteIx = (ix & 3); - ch2 = (ch2 >> ((3 - byteIx) << 3)); - ++ix; - - if ((ch2 & 0xC0) != 0x080) { - _reportInvalidOther(ch2); - } - ch = (ch << 6) | (ch2 & 0x3F); - if (needed > 2) { // 4 bytes? (need surrogates on output) - ch2 = quads[ix >> 2]; - byteIx = (ix & 3); - ch2 = (ch2 >> ((3 - byteIx) << 3)); - ++ix; - if ((ch2 & 0xC0) != 0x080) { - _reportInvalidOther(ch2 & 0xFF); - } - ch = (ch << 6) | (ch2 & 0x3F); - } - } - if (needed > 2) { // surrogate pair? once again, let's output one here, one later on - ch -= 0x10000; // to normalize it starting with 0x0 - if (cix >= cbuf.length) { - cbuf = _textBuffer.expandCurrentSegment(); - } - cbuf[cix++] = (char) (0xD800 + (ch >> 10)); - ch = 0xDC00 | (ch & 0x03FF); - } - } - if (cix >= cbuf.length) { - cbuf = _textBuffer.expandCurrentSegment(); - } - cbuf[cix++] = (char) ch; - } - - // Ok. Now we have the character array, and can construct the String - String baseName = new String(cbuf, 0, cix); - // And finally, un-align if necessary - if (lastQuadBytes < 4) { - quads[qlen-1] = lastQuad; - } - return _symbols.addName(baseName, quads, qlen); - } - - /* - /********************************************************** - /* Internal methods, String value parsing - /********************************************************** - */ - - protected void _loadMoreGuaranteed() throws IOException { - if (!_loadMore()) { _reportInvalidEOF(); } - } - - @Override - protected void _finishString() throws IOException - { - // First, single tight loop for ASCII content, not split across input buffer boundary: - int ptr = _inputPtr; - if (ptr >= _inputEnd) { - _loadMoreGuaranteed(); - ptr = _inputPtr; - } - int outPtr = 0; - char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); - final int[] codes = _icUTF8; - - final int max = Math.min(_inputEnd, (ptr + outBuf.length)); - final byte[] inputBuffer = _inputBuffer; - while (ptr < max) { - int c = (int) inputBuffer[ptr] & 0xFF; - if (codes[c] != 0) { - if (c == INT_QUOTE) { - _inputPtr = ptr+1; - _textBuffer.setCurrentLength(outPtr); - return; - } - break; - } - ++ptr; - outBuf[outPtr++] = (char) c; - } - _inputPtr = ptr; - _finishString2(outBuf, outPtr); - } - - /** - * @since 2.6 - */ - protected String _finishAndReturnString() throws IOException - { - // First, single tight loop for ASCII content, not split across input buffer boundary: - int ptr = _inputPtr; - if (ptr >= _inputEnd) { - _loadMoreGuaranteed(); - ptr = _inputPtr; - } - int outPtr = 0; - char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); - final int[] codes = _icUTF8; - - final int max = Math.min(_inputEnd, (ptr + outBuf.length)); - final byte[] inputBuffer = _inputBuffer; - while (ptr < max) { - int c = (int) inputBuffer[ptr] & 0xFF; - if (codes[c] != 0) { - if (c == INT_QUOTE) { - _inputPtr = ptr+1; - return _textBuffer.setCurrentAndReturn(outPtr); - } - break; - } - ++ptr; - outBuf[outPtr++] = (char) c; - } - _inputPtr = ptr; - _finishString2(outBuf, outPtr); - return _textBuffer.contentsAsString(); - } - - private final void _finishString2(char[] outBuf, int outPtr) - throws IOException - { - int c; - - // Here we do want to do full decoding, hence: - final int[] codes = _icUTF8; - final byte[] inputBuffer = _inputBuffer; - - main_loop: - while (true) { - // Then the tight ASCII non-funny-char loop: - ascii_loop: - while (true) { - int ptr = _inputPtr; - if (ptr >= _inputEnd) { - _loadMoreGuaranteed(); - ptr = _inputPtr; - } - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - final int max = Math.min(_inputEnd, (ptr + (outBuf.length - outPtr))); - while (ptr < max) { - c = (int) inputBuffer[ptr++] & 0xFF; - if (codes[c] != 0) { - _inputPtr = ptr; - break ascii_loop; - } - outBuf[outPtr++] = (char) c; - } - _inputPtr = ptr; - } - // Ok: end marker, escape or multi-byte? - if (c == INT_QUOTE) { - break main_loop; - } - - switch (codes[c]) { - case 1: // backslash - c = _decodeEscaped(); - break; - case 2: // 2-byte UTF - c = _decodeUtf8_2(c); - break; - case 3: // 3-byte UTF - if ((_inputEnd - _inputPtr) >= 2) { - c = _decodeUtf8_3fast(c); - } else { - c = _decodeUtf8_3(c); - } - break; - case 4: // 4-byte UTF - c = _decodeUtf8_4(c); - // Let's add first part right away: - outBuf[outPtr++] = (char) (0xD800 | (c >> 10)); - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - c = 0xDC00 | (c & 0x3FF); - // And let the other char output down below - break; - default: - if (c < INT_SPACE) { - // As per [JACKSON-208], call can now return: - _throwUnquotedSpace(c, "string value"); - } else { - // Is this good enough error message? - _reportInvalidChar(c); - } - } - // Need more room? - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - // Ok, let's add char to output: - outBuf[outPtr++] = (char) c; - } - _textBuffer.setCurrentLength(outPtr); - } - - /** - * Method called to skim through rest of unparsed String value, - * if it is not needed. This can be done bit faster if contents - * need not be stored for future access. - */ - protected void _skipString() throws IOException - { - _tokenIncomplete = false; - - // Need to be fully UTF-8 aware here: - final int[] codes = _icUTF8; - final byte[] inputBuffer = _inputBuffer; - - main_loop: - while (true) { - int c; - - ascii_loop: - while (true) { - int ptr = _inputPtr; - int max = _inputEnd; - if (ptr >= max) { - _loadMoreGuaranteed(); - ptr = _inputPtr; - max = _inputEnd; - } - while (ptr < max) { - c = (int) inputBuffer[ptr++] & 0xFF; - if (codes[c] != 0) { - _inputPtr = ptr; - break ascii_loop; - } - } - _inputPtr = ptr; - } - // Ok: end marker, escape or multi-byte? - if (c == INT_QUOTE) { - break main_loop; - } - - switch (codes[c]) { - case 1: // backslash - _decodeEscaped(); - break; - case 2: // 2-byte UTF - _skipUtf8_2(); - break; - case 3: // 3-byte UTF - _skipUtf8_3(); - break; - case 4: // 4-byte UTF - _skipUtf8_4(c); - break; - default: - if (c < INT_SPACE) { - _throwUnquotedSpace(c, "string value"); - } else { - // Is this good enough error message? - _reportInvalidChar(c); - } - } - } - } - - /** - * Method for handling cases where first non-space character - * of an expected value token is not legal for standard JSON content. - */ - protected JsonToken _handleUnexpectedValue(int c) - throws IOException - { - // Most likely an error, unless we are to allow single-quote-strings - switch (c) { - /* - * This check proceeds only if the Feature.ALLOW_MISSING_VALUES is enabled - * The Check is for missing values. Incase of missing values in an array, the next token will be either ',' or ']'. - * This case, decrements the already incremented _inputPtr in the buffer in case of comma(,) - * so that the existing flow goes back to checking the next token which will be comma again and - * it continues the parsing. - * Also the case returns NULL as current token in case of ',' or ']'. - */ - case ']': - if (!_parsingContext.inArray()) { - break; - } - // fall through - case ',': - /* 28-Mar-2016: [core#116]: If Feature.ALLOW_MISSING_VALUES is enabled - * we may allow "missing values", that is, encountering a trailing - * comma or closing marker where value would be expected - */ - if (isEnabled(Feature.ALLOW_MISSING_VALUES)) { - _inputPtr--; - return JsonToken.VALUE_NULL; - } - // fall through - case '}': - // Error: neither is valid at this point; valid closers have - // been handled earlier - _reportUnexpectedChar(c, "expected a value"); - case '\'': - if (isEnabled(Feature.ALLOW_SINGLE_QUOTES)) { - return _handleApos(); - } - break; - case 'N': - _matchToken("NaN", 1); - if (isEnabled(Feature.ALLOW_NON_NUMERIC_NUMBERS)) { - return resetAsNaN("NaN", Double.NaN); - } - _reportError("Non-standard token 'NaN': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow"); - break; - case 'I': - _matchToken("Infinity", 1); - if (isEnabled(Feature.ALLOW_NON_NUMERIC_NUMBERS)) { - return resetAsNaN("Infinity", Double.POSITIVE_INFINITY); - } - _reportError("Non-standard token 'Infinity': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow"); - break; - case '+': // note: '-' is taken as number - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { - _reportInvalidEOFInValue(JsonToken.VALUE_NUMBER_INT); - } - } - return _handleInvalidNumberStart(_inputBuffer[_inputPtr++] & 0xFF, false); - } - // [core#77] Try to decode most likely token - if (Character.isJavaIdentifierStart(c)) { - _reportInvalidToken(""+((char) c), "('true', 'false' or 'null')"); - } - // but if it doesn't look like a token: - _reportUnexpectedChar(c, "expected a valid value (number, String, array, object, 'true', 'false' or 'null')"); - return null; - } - - protected JsonToken _handleApos() - throws IOException - { - int c = 0; - // Otherwise almost verbatim copy of _finishString() - int outPtr = 0; - char[] outBuf = _textBuffer.emptyAndGetCurrentSegment(); - - // Here we do want to do full decoding, hence: - final int[] codes = _icUTF8; - final byte[] inputBuffer = _inputBuffer; - - main_loop: - while (true) { - // Then the tight ascii non-funny-char loop: - ascii_loop: - while (true) { - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - int max = _inputEnd; - { - int max2 = _inputPtr + (outBuf.length - outPtr); - if (max2 < max) { - max = max2; - } - } - while (_inputPtr < max) { - c = (int) inputBuffer[_inputPtr++] & 0xFF; - if (c == '\'' || codes[c] != 0) { - break ascii_loop; - } - outBuf[outPtr++] = (char) c; - } - } - - // Ok: end marker, escape or multi-byte? - if (c == '\'') { - break main_loop; - } - - switch (codes[c]) { - case 1: // backslash - c = _decodeEscaped(); - break; - case 2: // 2-byte UTF - c = _decodeUtf8_2(c); - break; - case 3: // 3-byte UTF - if ((_inputEnd - _inputPtr) >= 2) { - c = _decodeUtf8_3fast(c); - } else { - c = _decodeUtf8_3(c); - } - break; - case 4: // 4-byte UTF - c = _decodeUtf8_4(c); - // Let's add first part right away: - outBuf[outPtr++] = (char) (0xD800 | (c >> 10)); - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - c = 0xDC00 | (c & 0x3FF); - // And let the other char output down below - break; - default: - if (c < INT_SPACE) { - _throwUnquotedSpace(c, "string value"); - } - // Is this good enough error message? - _reportInvalidChar(c); - } - // Need more room? - if (outPtr >= outBuf.length) { - outBuf = _textBuffer.finishCurrentSegment(); - outPtr = 0; - } - // Ok, let's add char to output: - outBuf[outPtr++] = (char) c; - } - _textBuffer.setCurrentLength(outPtr); - - return JsonToken.VALUE_STRING; - } - - /** - * Method called if expected numeric value (due to leading sign) does not - * look like a number - */ - protected JsonToken _handleInvalidNumberStart(int ch, boolean neg) - throws IOException - { - while (ch == 'I') { - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { - _reportInvalidEOFInValue(JsonToken.VALUE_NUMBER_FLOAT); // possibly? - } - } - ch = _inputBuffer[_inputPtr++]; - String match; - if (ch == 'N') { - match = neg ? "-INF" :"+INF"; - } else if (ch == 'n') { - match = neg ? "-Infinity" :"+Infinity"; - } else { - break; - } - _matchToken(match, 3); - if (isEnabled(Feature.ALLOW_NON_NUMERIC_NUMBERS)) { - return resetAsNaN(match, neg ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY); - } - _reportError("Non-standard token '"+match+"': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow"); - } - reportUnexpectedNumberChar(ch, "expected digit (0-9) to follow minus sign, for valid numeric value"); - return null; - } - - protected final void _matchToken(String matchStr, int i) throws IOException - { - final int len = matchStr.length(); - if ((_inputPtr + len) >= _inputEnd) { - _matchToken2(matchStr, i); - return; - } - do { - if (_inputBuffer[_inputPtr] != matchStr.charAt(i)) { - _reportInvalidToken(matchStr.substring(0, i)); - } - ++_inputPtr; - } while (++i < len); - - int ch = _inputBuffer[_inputPtr] & 0xFF; - if (ch >= '0' && ch != ']' && ch != '}') { // expected/allowed chars - _checkMatchEnd(matchStr, i, ch); - } - } - - private final void _matchToken2(String matchStr, int i) throws IOException - { - final int len = matchStr.length(); - do { - if (((_inputPtr >= _inputEnd) && !_loadMore()) - || (_inputBuffer[_inputPtr] != matchStr.charAt(i))) { - _reportInvalidToken(matchStr.substring(0, i)); - } - ++_inputPtr; - } while (++i < len); - - // but let's also ensure we either get EOF, or non-alphanum char... - if (_inputPtr >= _inputEnd && !_loadMore()) { - return; - } - int ch = _inputBuffer[_inputPtr] & 0xFF; - if (ch >= '0' && ch != ']' && ch != '}') { // expected/allowed chars - _checkMatchEnd(matchStr, i, ch); - } - } - - private final void _checkMatchEnd(String matchStr, int i, int ch) throws IOException { - // but actually only alphanums are problematic - char c = (char) _decodeCharForError(ch); - if (Character.isJavaIdentifierPart(c)) { - _reportInvalidToken(matchStr.substring(0, i)); - } - } - - /* - /********************************************************** - /* Internal methods, ws skipping, escape/unescape - /********************************************************** - */ - - private final int _skipWS() throws IOException - { - while (_inputPtr < _inputEnd) { - int i = _inputBuffer[_inputPtr++] & 0xFF; - if (i > INT_SPACE) { - if (i == INT_SLASH || i == INT_HASH) { - --_inputPtr; - return _skipWS2(); - } - return i; - } - if (i != INT_SPACE) { - if (i == INT_LF) { - ++_currInputRow; - _currInputRowStart = _inputPtr; - } else if (i == INT_CR) { - _skipCR(); - } else if (i != INT_TAB) { - _throwInvalidSpace(i); - } - } - } - return _skipWS2(); - } - - private final int _skipWS2() throws IOException - { - while (_inputPtr < _inputEnd || _loadMore()) { - int i = _inputBuffer[_inputPtr++] & 0xFF; - if (i > INT_SPACE) { - if (i == INT_SLASH) { - _skipComment(); - continue; - } - if (i == INT_HASH) { - if (_skipYAMLComment()) { - continue; - } - } - return i; - } - if (i != INT_SPACE) { - if (i == INT_LF) { - ++_currInputRow; - _currInputRowStart = _inputPtr; - } else if (i == INT_CR) { - _skipCR(); - } else if (i != INT_TAB) { - _throwInvalidSpace(i); - } - } - } - throw _constructError("Unexpected end-of-input within/between "+_parsingContext.typeDesc()+" entries"); - } - - private final int _skipWSOrEnd() throws IOException - { - // Let's handle first character separately since it is likely that - // it is either non-whitespace; or we have longer run of white space - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { - return _eofAsNextChar(); - } - } - int i = _inputBuffer[_inputPtr++] & 0xFF; - if (i > INT_SPACE) { - if (i == INT_SLASH || i == INT_HASH) { - --_inputPtr; - return _skipWSOrEnd2(); - } - return i; - } - if (i != INT_SPACE) { - if (i == INT_LF) { - ++_currInputRow; - _currInputRowStart = _inputPtr; - } else if (i == INT_CR) { - _skipCR(); - } else if (i != INT_TAB) { - _throwInvalidSpace(i); - } - } - - while (_inputPtr < _inputEnd) { - i = _inputBuffer[_inputPtr++] & 0xFF; - if (i > INT_SPACE) { - if (i == INT_SLASH || i == INT_HASH) { - --_inputPtr; - return _skipWSOrEnd2(); - } - return i; - } - if (i != INT_SPACE) { - if (i == INT_LF) { - ++_currInputRow; - _currInputRowStart = _inputPtr; - } else if (i == INT_CR) { - _skipCR(); - } else if (i != INT_TAB) { - _throwInvalidSpace(i); - } - } - } - return _skipWSOrEnd2(); - } - - private final int _skipWSOrEnd2() throws IOException - { - while ((_inputPtr < _inputEnd) || _loadMore()) { - int i = _inputBuffer[_inputPtr++] & 0xFF; - if (i > INT_SPACE) { - if (i == INT_SLASH) { - _skipComment(); - continue; - } - if (i == INT_HASH) { - if (_skipYAMLComment()) { - continue; - } - } - return i; - } else if (i != INT_SPACE) { - if (i == INT_LF) { - ++_currInputRow; - _currInputRowStart = _inputPtr; - } else if (i == INT_CR) { - _skipCR(); - } else if (i != INT_TAB) { - _throwInvalidSpace(i); - } - } - } - // We ran out of input... - return _eofAsNextChar(); - } - - private final int _skipColon() throws IOException - { - if ((_inputPtr + 4) >= _inputEnd) { - return _skipColon2(false); - } - // Fast path: colon with optional single-space/tab before and/or after: - int i = _inputBuffer[_inputPtr]; - if (i == INT_COLON) { // common case, no leading space - i = _inputBuffer[++_inputPtr]; - if (i > INT_SPACE) { // nor trailing - if (i == INT_SLASH || i == INT_HASH) { - return _skipColon2(true); - } - ++_inputPtr; - return i; - } - if (i == INT_SPACE || i == INT_TAB) { - i = (int) _inputBuffer[++_inputPtr]; - if (i > INT_SPACE) { - if (i == INT_SLASH || i == INT_HASH) { - return _skipColon2(true); - } - ++_inputPtr; - return i; - } - } - return _skipColon2(true); // true -> skipped colon - } - if (i == INT_SPACE || i == INT_TAB) { - i = _inputBuffer[++_inputPtr]; - } - if (i == INT_COLON) { - i = _inputBuffer[++_inputPtr]; - if (i > INT_SPACE) { - if (i == INT_SLASH || i == INT_HASH) { - return _skipColon2(true); - } - ++_inputPtr; - return i; - } - if (i == INT_SPACE || i == INT_TAB) { - i = (int) _inputBuffer[++_inputPtr]; - if (i > INT_SPACE) { - if (i == INT_SLASH || i == INT_HASH) { - return _skipColon2(true); - } - ++_inputPtr; - return i; - } - } - return _skipColon2(true); - } - return _skipColon2(false); - } - - private final int _skipColon2(boolean gotColon) throws IOException - { - while (_inputPtr < _inputEnd || _loadMore()) { - int i = _inputBuffer[_inputPtr++] & 0xFF; - - if (i > INT_SPACE) { - if (i == INT_SLASH) { - _skipComment(); - continue; - } - if (i == INT_HASH) { - if (_skipYAMLComment()) { - continue; - } - } - if (gotColon) { - return i; - } - if (i != INT_COLON) { - _reportUnexpectedChar(i, "was expecting a colon to separate field name and value"); - } - gotColon = true; - } else if (i != INT_SPACE) { - if (i == INT_LF) { - ++_currInputRow; - _currInputRowStart = _inputPtr; - } else if (i == INT_CR) { - _skipCR(); - } else if (i != INT_TAB) { - _throwInvalidSpace(i); - } - } - } - _reportInvalidEOF(" within/between "+_parsingContext.typeDesc()+" entries", - null); - return -1; - } - - private final void _skipComment() throws IOException - { - if (!isEnabled(Feature.ALLOW_COMMENTS)) { - _reportUnexpectedChar('/', "maybe a (non-standard) comment? (not recognized as one since Feature 'ALLOW_COMMENTS' not enabled for parser)"); - } - // First: check which comment (if either) it is: - if (_inputPtr >= _inputEnd && !_loadMore()) { - _reportInvalidEOF(" in a comment", null); - } - int c = _inputBuffer[_inputPtr++] & 0xFF; - if (c == '/') { - _skipLine(); - } else if (c == '*') { - _skipCComment(); - } else { - _reportUnexpectedChar(c, "was expecting either '*' or '/' for a comment"); - } - } - - private final void _skipCComment() throws IOException - { - // Need to be UTF-8 aware here to decode content (for skipping) - final int[] codes = CharTypes.getInputCodeComment(); - - // Ok: need the matching '*/' - main_loop: - while ((_inputPtr < _inputEnd) || _loadMore()) { - int i = (int) _inputBuffer[_inputPtr++] & 0xFF; - int code = codes[i]; - if (code != 0) { - switch (code) { - case '*': - if (_inputPtr >= _inputEnd && !_loadMore()) { - break main_loop; - } - if (_inputBuffer[_inputPtr] == INT_SLASH) { - ++_inputPtr; - return; - } - break; - case INT_LF: - ++_currInputRow; - _currInputRowStart = _inputPtr; - break; - case INT_CR: - _skipCR(); - break; - case 2: // 2-byte UTF - _skipUtf8_2(); - break; - case 3: // 3-byte UTF - _skipUtf8_3(); - break; - case 4: // 4-byte UTF - _skipUtf8_4(i); - break; - default: // e.g. -1 - // Is this good enough error message? - _reportInvalidChar(i); - } - } - } - _reportInvalidEOF(" in a comment", null); - } - - private final boolean _skipYAMLComment() throws IOException - { - if (!isEnabled(Feature.ALLOW_YAML_COMMENTS)) { - return false; - } - _skipLine(); - return true; - } - - /** - * Method for skipping contents of an input line; usually for CPP - * and YAML style comments. - */ - private final void _skipLine() throws IOException - { - // Ok: need to find EOF or linefeed - final int[] codes = CharTypes.getInputCodeComment(); - while ((_inputPtr < _inputEnd) || _loadMore()) { - int i = (int) _inputBuffer[_inputPtr++] & 0xFF; - int code = codes[i]; - if (code != 0) { - switch (code) { - case INT_LF: - ++_currInputRow; - _currInputRowStart = _inputPtr; - return; - case INT_CR: - _skipCR(); - return; - case '*': // nop for these comments - break; - case 2: // 2-byte UTF - _skipUtf8_2(); - break; - case 3: // 3-byte UTF - _skipUtf8_3(); - break; - case 4: // 4-byte UTF - _skipUtf8_4(i); - break; - default: // e.g. -1 - if (code < 0) { - // Is this good enough error message? - _reportInvalidChar(i); - } - } - } - } - } - - @Override - protected char _decodeEscaped() throws IOException - { - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { - _reportInvalidEOF(" in character escape sequence", JsonToken.VALUE_STRING); - } - } - int c = (int) _inputBuffer[_inputPtr++]; - - switch (c) { - // First, ones that are mapped - case 'b': - return '\b'; - case 't': - return '\t'; - case 'n': - return '\n'; - case 'f': - return '\f'; - case 'r': - return '\r'; - - // And these are to be returned as they are - case '"': - case '/': - case '\\': - return (char) c; - - case 'u': // and finally hex-escaped - break; - - default: - return _handleUnrecognizedCharacterEscape((char) _decodeCharForError(c)); - } - - // Ok, a hex escape. Need 4 characters - int value = 0; - for (int i = 0; i < 4; ++i) { - if (_inputPtr >= _inputEnd) { - if (!_loadMore()) { - _reportInvalidEOF(" in character escape sequence", JsonToken.VALUE_STRING); - } - } - int ch = (int) _inputBuffer[_inputPtr++]; - int digit = CharTypes.charToHex(ch); - if (digit < 0) { - _reportUnexpectedChar(ch, "expected a hex-digit for character escape sequence"); - } - value = (value << 4) | digit; - } - return (char) value; - } - - protected int _decodeCharForError(int firstByte) throws IOException - { - int c = firstByte & 0xFF; - if (c > 0x7F) { // if >= 0, is ascii and fine as is - int needed; - - // Ok; if we end here, we got multi-byte combination - if ((c & 0xE0) == 0xC0) { // 2 bytes (0x0080 - 0x07FF) - c &= 0x1F; - needed = 1; - } else if ((c & 0xF0) == 0xE0) { // 3 bytes (0x0800 - 0xFFFF) - c &= 0x0F; - needed = 2; - } else if ((c & 0xF8) == 0xF0) { - // 4 bytes; double-char with surrogates and all... - c &= 0x07; - needed = 3; - } else { - _reportInvalidInitial(c & 0xFF); - needed = 1; // never gets here - } - - int d = nextByte(); - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF); - } - c = (c << 6) | (d & 0x3F); - - if (needed > 1) { // needed == 1 means 2 bytes total - d = nextByte(); // 3rd byte - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF); - } - c = (c << 6) | (d & 0x3F); - if (needed > 2) { // 4 bytes? (need surrogates) - d = nextByte(); - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF); - } - c = (c << 6) | (d & 0x3F); - } - } - } - return c; - } - - /* - /********************************************************** - /* Internal methods,UTF8 decoding - /********************************************************** - */ - - private final int _decodeUtf8_2(int c) throws IOException - { - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - int d = (int) _inputBuffer[_inputPtr++]; - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF, _inputPtr); - } - return ((c & 0x1F) << 6) | (d & 0x3F); - } - - private final int _decodeUtf8_3(int c1) throws IOException - { - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - c1 &= 0x0F; - int d = (int) _inputBuffer[_inputPtr++]; - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF, _inputPtr); - } - int c = (c1 << 6) | (d & 0x3F); - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - d = (int) _inputBuffer[_inputPtr++]; - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF, _inputPtr); - } - c = (c << 6) | (d & 0x3F); - return c; - } - - private final int _decodeUtf8_3fast(int c1) throws IOException - { - c1 &= 0x0F; - int d = (int) _inputBuffer[_inputPtr++]; - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF, _inputPtr); - } - int c = (c1 << 6) | (d & 0x3F); - d = (int) _inputBuffer[_inputPtr++]; - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF, _inputPtr); - } - c = (c << 6) | (d & 0x3F); - return c; - } - - /** - * @return Character value minus 0x10000; this so that caller - * can readily expand it to actual surrogates - */ - private final int _decodeUtf8_4(int c) throws IOException - { - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - int d = (int) _inputBuffer[_inputPtr++]; - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF, _inputPtr); - } - c = ((c & 0x07) << 6) | (d & 0x3F); - - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - d = (int) _inputBuffer[_inputPtr++]; - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF, _inputPtr); - } - c = (c << 6) | (d & 0x3F); - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - d = (int) _inputBuffer[_inputPtr++]; - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF, _inputPtr); - } - - /* note: won't change it to negative here, since caller - * already knows it'll need a surrogate - */ - return ((c << 6) | (d & 0x3F)) - 0x10000; - } - - private final void _skipUtf8_2() throws IOException - { - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - int c = (int) _inputBuffer[_inputPtr++]; - if ((c & 0xC0) != 0x080) { - _reportInvalidOther(c & 0xFF, _inputPtr); - } - } - - /* Alas, can't heavily optimize skipping, since we still have to - * do validity checks... - */ - private final void _skipUtf8_3() throws IOException - { - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - //c &= 0x0F; - int c = (int) _inputBuffer[_inputPtr++]; - if ((c & 0xC0) != 0x080) { - _reportInvalidOther(c & 0xFF, _inputPtr); - } - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - c = (int) _inputBuffer[_inputPtr++]; - if ((c & 0xC0) != 0x080) { - _reportInvalidOther(c & 0xFF, _inputPtr); - } - } - - private final void _skipUtf8_4(int c) throws IOException - { - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - int d = (int) _inputBuffer[_inputPtr++]; - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF, _inputPtr); - } - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - d = (int) _inputBuffer[_inputPtr++]; - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF, _inputPtr); - } - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - d = (int) _inputBuffer[_inputPtr++]; - if ((d & 0xC0) != 0x080) { - _reportInvalidOther(d & 0xFF, _inputPtr); - } - } - - /* - /********************************************************** - /* Internal methods, input loading - /********************************************************** - */ - - /** - * We actually need to check the character value here - * (to see if we have \n following \r). - */ - protected final void _skipCR() throws IOException - { - if (_inputPtr < _inputEnd || _loadMore()) { - if (_inputBuffer[_inputPtr] == BYTE_LF) { - ++_inputPtr; - } - } - ++_currInputRow; - _currInputRowStart = _inputPtr; - } - - private int nextByte() throws IOException - { - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - return _inputBuffer[_inputPtr++] & 0xFF; - } - - /* - /********************************************************** - /* Internal methods, error reporting - /********************************************************** - */ - - protected void _reportInvalidToken(String matchedPart) throws IOException { - _reportInvalidToken(matchedPart, "'null', 'true', 'false' or NaN"); - } - - protected void _reportInvalidToken(String matchedPart, String msg) throws IOException - { - StringBuilder sb = new StringBuilder(matchedPart); - - /* Let's just try to find what appears to be the token, using - * regular Java identifier character rules. It's just a heuristic, - * nothing fancy here (nor fast). - */ - while (true) { - if (_inputPtr >= _inputEnd && !_loadMore()) { - break; - } - int i = (int) _inputBuffer[_inputPtr++]; - char c = (char) _decodeCharForError(i); - if (!Character.isJavaIdentifierPart(c)) { - break; - } - sb.append(c); - } - _reportError("Unrecognized token '"+sb.toString()+"': was expecting "+msg); - } - - protected void _reportInvalidChar(int c) - throws JsonParseException - { - // Either invalid WS or illegal UTF-8 start char - if (c < INT_SPACE) { - _throwInvalidSpace(c); - } - _reportInvalidInitial(c); - } - - protected void _reportInvalidInitial(int mask) - throws JsonParseException - { - _reportError("Invalid UTF-8 start byte 0x"+Integer.toHexString(mask)); - } - - protected void _reportInvalidOther(int mask) - throws JsonParseException - { - _reportError("Invalid UTF-8 middle byte 0x"+Integer.toHexString(mask)); - } - - protected void _reportInvalidOther(int mask, int ptr) - throws JsonParseException - { - _inputPtr = ptr; - _reportInvalidOther(mask); - } - - public static int[] growArrayBy(int[] arr, int more) - { - if (arr == null) { - return new int[more]; - } - return Arrays.copyOf(arr, arr.length + more); - } - - /* - /********************************************************** - /* Internal methods, binary access - /********************************************************** - */ - - /** - * Efficient handling for incremental parsing of base64-encoded - * textual content. - */ - protected final byte[] _decodeBase64(Base64Variant b64variant) throws IOException - { - ByteArrayBuilder builder = _getByteArrayBuilder(); - - //main_loop: - while (true) { - // first, we'll skip preceding white space, if any - int ch; - do { - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - ch = (int) _inputBuffer[_inputPtr++] & 0xFF; - } while (ch <= INT_SPACE); - int bits = b64variant.decodeBase64Char(ch); - if (bits < 0) { // reached the end, fair and square? - if (ch == INT_QUOTE) { - return builder.toByteArray(); - } - bits = _decodeBase64Escape(b64variant, ch, 0); - if (bits < 0) { // white space to skip - continue; - } - } - int decodedData = bits; - - // then second base64 char; can't get padding yet, nor ws - - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - ch = _inputBuffer[_inputPtr++] & 0xFF; - bits = b64variant.decodeBase64Char(ch); - if (bits < 0) { - bits = _decodeBase64Escape(b64variant, ch, 1); - } - decodedData = (decodedData << 6) | bits; - - // third base64 char; can be padding, but not ws - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - ch = _inputBuffer[_inputPtr++] & 0xFF; - bits = b64variant.decodeBase64Char(ch); - - // First branch: can get padding (-> 1 byte) - if (bits < 0) { - if (bits != Base64Variant.BASE64_VALUE_PADDING) { - // as per [JACKSON-631], could also just be 'missing' padding - if (ch == '"' && !b64variant.usesPadding()) { - decodedData >>= 4; - builder.append(decodedData); - return builder.toByteArray(); - } - bits = _decodeBase64Escape(b64variant, ch, 2); - } - if (bits == Base64Variant.BASE64_VALUE_PADDING) { - // Ok, must get padding - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - ch = _inputBuffer[_inputPtr++] & 0xFF; - if (!b64variant.usesPaddingChar(ch)) { - throw reportInvalidBase64Char(b64variant, ch, 3, "expected padding character '"+b64variant.getPaddingChar()+"'"); - } - // Got 12 bits, only need 8, need to shift - decodedData >>= 4; - builder.append(decodedData); - continue; - } - } - // Nope, 2 or 3 bytes - decodedData = (decodedData << 6) | bits; - // fourth and last base64 char; can be padding, but not ws - if (_inputPtr >= _inputEnd) { - _loadMoreGuaranteed(); - } - ch = _inputBuffer[_inputPtr++] & 0xFF; - bits = b64variant.decodeBase64Char(ch); - if (bits < 0) { - if (bits != Base64Variant.BASE64_VALUE_PADDING) { - // as per [JACKSON-631], could also just be 'missing' padding - if (ch == '"' && !b64variant.usesPadding()) { - decodedData >>= 2; - builder.appendTwoBytes(decodedData); - return builder.toByteArray(); - } - bits = _decodeBase64Escape(b64variant, ch, 3); - } - if (bits == Base64Variant.BASE64_VALUE_PADDING) { - /* With padding we only get 2 bytes; but we have - * to shift it a bit so it is identical to triplet - * case with partial output. - * 3 chars gives 3x6 == 18 bits, of which 2 are - * dummies, need to discard: - */ - decodedData >>= 2; - builder.appendTwoBytes(decodedData); - continue; - } - } - // otherwise, our triplet is now complete - decodedData = (decodedData << 6) | bits; - builder.appendThreeBytes(decodedData); - } - } - - /* - /********************************************************** - /* Improved location updating (refactored in 2.7) - /********************************************************** - */ - - // As per [core#108], must ensure we call the right method - @Override - public JsonLocation getTokenLocation() - { - final Object src = _ioContext.getSourceReference(); - if (_currToken == JsonToken.FIELD_NAME) { - long total = _currInputProcessed + (_nameStartOffset-1); - return new JsonLocation(src, - total, -1L, _nameStartRow, _nameStartCol); - } - return new JsonLocation(src, - _tokenInputTotal-1, -1L, _tokenInputRow, _tokenInputCol); - } - - // As per [core#108], must ensure we call the right method - @Override - public JsonLocation getCurrentLocation() - { - int col = _inputPtr - _currInputRowStart + 1; // 1-based - return new JsonLocation(_ioContext.getSourceReference(), - _currInputProcessed + _inputPtr, -1L, // bytes, chars - _currInputRow, col); - } - - // @since 2.7 - private final void _updateLocation() - { - _tokenInputRow = _currInputRow; - final int ptr = _inputPtr; - _tokenInputTotal = _currInputProcessed + ptr; - _tokenInputCol = ptr - _currInputRowStart; - } - - // @since 2.7 - private final void _updateNameLocation() - { - _nameStartRow = _currInputRow; - final int ptr = _inputPtr; - _nameStartOffset = ptr; - _nameStartCol = ptr - _currInputRowStart; - } - - /* - /********************************************************** - /* Internal methods, other - /********************************************************** - */ - - private final JsonToken _closeScope(int i) throws JsonParseException { - if (i == INT_RCURLY) { - _closeObjectScope(); - return (_currToken = JsonToken.END_OBJECT); - } - _closeArrayScope(); - return (_currToken = JsonToken.END_ARRAY); - } - - private final void _closeArrayScope() throws JsonParseException { - _updateLocation(); - if (!_parsingContext.inArray()) { - _reportMismatchedEndMarker(']', '}'); - } - _parsingContext = _parsingContext.clearAndGetParent(); - } - - private final void _closeObjectScope() throws JsonParseException { - _updateLocation(); - if (!_parsingContext.inObject()) { - _reportMismatchedEndMarker('}', ']'); - } - _parsingContext = _parsingContext.clearAndGetParent(); - } - - /** - * Helper method needed to fix [Issue#148], masking of 0x00 character - */ - private final static int pad(int q, int bytes) { - return (bytes == 4) ? q : (q | (-1 << (bytes << 3))); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/WriterBasedJsonGenerator.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/WriterBasedJsonGenerator.java deleted file mode 100644 index 6461d8b1..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/json/WriterBasedJsonGenerator.java +++ /dev/null @@ -1,1893 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.json; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Writer; -import java.math.BigDecimal; -import java.math.BigInteger; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.Base64Variant; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonStreamContext; -import autosaveworld.zlibs.com.fasterxml.jackson.core.ObjectCodec; -import autosaveworld.zlibs.com.fasterxml.jackson.core.SerializableString; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.CharTypes; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.CharacterEscapes; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.IOContext; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.NumberOutput; - -/** - * {@link JsonGenerator} that outputs JSON content using a {@link java.io.Writer} - * which handles character encoding. - */ -public final class WriterBasedJsonGenerator - extends JsonGeneratorImpl -{ - final protected static int SHORT_WRITE = 32; - - final protected static char[] HEX_CHARS = CharTypes.copyHexChars(); - - /* - /********************************************************** - /* Configuration - /********************************************************** - */ - - final protected Writer _writer; - - /** - * Character used for quoting JSON Object property names - * and String values. - * - * @since 2.8 - */ - protected char _quoteChar = '"'; // TODO: make configurable - - /* - /********************************************************** - /* Output buffering - /********************************************************** - */ - - /** - * Intermediate buffer in which contents are buffered before - * being written using {@link #_writer}. - */ - protected char[] _outputBuffer; - - /** - * Pointer to the first buffered character to output - */ - protected int _outputHead; - - /** - * Pointer to the position right beyond the last character to output - * (end marker; may point to position right beyond the end of the buffer) - */ - protected int _outputTail; - - /** - * End marker of the output buffer; one past the last valid position - * within the buffer. - */ - protected int _outputEnd; - - /** - * Short (14 char) temporary buffer allocated if needed, for constructing - * escape sequences - */ - protected char[] _entityBuffer; - - /** - * When custom escapes are used, this member variable is used - * internally to hold a reference to currently used escape - */ - protected SerializableString _currentEscape; - - /* - /********************************************************** - /* Life-cycle - /********************************************************** - */ - - public WriterBasedJsonGenerator(IOContext ctxt, int features, - ObjectCodec codec, Writer w) - { - super(ctxt, features, codec); - _writer = w; - _outputBuffer = ctxt.allocConcatBuffer(); - _outputEnd = _outputBuffer.length; - } - - /* - /********************************************************** - /* Overridden configuration, introspection methods - /********************************************************** - */ - - @Override - public Object getOutputTarget() { - return _writer; - } - - @Override - public int getOutputBuffered() { - // Assuming tail and head are kept but... trust and verify: - int len = _outputTail - _outputHead; - return Math.max(0, len); - } - - // json does allow this so - @Override - public boolean canWriteFormattedNumbers() { return true; } - - /* - /********************************************************** - /* Overridden methods - /********************************************************** - */ - - @Override - public void writeFieldName(String name) throws IOException - { - int status = _writeContext.writeFieldName(name); - if (status == JsonWriteContext.STATUS_EXPECT_VALUE) { - _reportError("Can not write a field name, expecting a value"); - } - _writeFieldName(name, (status == JsonWriteContext.STATUS_OK_AFTER_COMMA)); - } - - @Override - public void writeFieldName(SerializableString name) throws IOException - { - // Object is a value, need to verify it's allowed - int status = _writeContext.writeFieldName(name.getValue()); - if (status == JsonWriteContext.STATUS_EXPECT_VALUE) { - _reportError("Can not write a field name, expecting a value"); - } - _writeFieldName(name, (status == JsonWriteContext.STATUS_OK_AFTER_COMMA)); - } - - protected void _writeFieldName(String name, boolean commaBefore) throws IOException - { - if (_cfgPrettyPrinter != null) { - _writePPFieldName(name, commaBefore); - return; - } - // for fast+std case, need to output up to 2 chars, comma, dquote - if ((_outputTail + 1) >= _outputEnd) { - _flushBuffer(); - } - if (commaBefore) { - _outputBuffer[_outputTail++] = ','; - } - // Alternate mode, in which quoting of field names disabled? - if (_cfgUnqNames) { - _writeString(name); - return; - } - // we know there's room for at least one more char - _outputBuffer[_outputTail++] = _quoteChar; - // The beef: - _writeString(name); - // and closing quotes; need room for one more char: - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } - - protected void _writeFieldName(SerializableString name, boolean commaBefore) throws IOException - { - if (_cfgPrettyPrinter != null) { - _writePPFieldName(name, commaBefore); - return; - } - // for fast+std case, need to output up to 2 chars, comma, dquote - if ((_outputTail + 1) >= _outputEnd) { - _flushBuffer(); - } - if (commaBefore) { - _outputBuffer[_outputTail++] = ','; - } - // Alternate mode, in which quoting of field names disabled? - final char[] quoted = name.asQuotedChars(); - if (_cfgUnqNames) { - writeRaw(quoted, 0, quoted.length); - return; - } - // we know there's room for at least one more char - _outputBuffer[_outputTail++] = _quoteChar; - // The beef: - final int qlen = quoted.length; - if ((_outputTail + qlen + 1) >= _outputEnd) { - writeRaw(quoted, 0, qlen); - // and closing quotes; need room for one more char: - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } else { - System.arraycopy(quoted, 0, _outputBuffer, _outputTail, qlen); - _outputTail += qlen; - _outputBuffer[_outputTail++] = _quoteChar; - } - } - - /* - /********************************************************** - /* Output method implementations, structural - /********************************************************** - */ - - @Override - public void writeStartArray() throws IOException - { - _verifyValueWrite("start an array"); - _writeContext = _writeContext.createChildArrayContext(); - if (_cfgPrettyPrinter != null) { - _cfgPrettyPrinter.writeStartArray(this); - } else { - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = '['; - } - } - - @Override - public void writeEndArray() throws IOException - { - if (!_writeContext.inArray()) { - _reportError("Current context not Array but "+_writeContext.typeDesc()); - } - if (_cfgPrettyPrinter != null) { - _cfgPrettyPrinter.writeEndArray(this, _writeContext.getEntryCount()); - } else { - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = ']'; - } - _writeContext = _writeContext.clearAndGetParent(); - } - - @Override // since 2.8 - public void writeStartObject(Object forValue) throws IOException - { - _verifyValueWrite("start an object"); - JsonWriteContext ctxt = _writeContext.createChildObjectContext(); - _writeContext = ctxt; - if (forValue != null) { - ctxt.setCurrentValue(forValue); - } - if (_cfgPrettyPrinter != null) { - _cfgPrettyPrinter.writeStartObject(this); - } else { - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = '{'; - } - } - - @Override - public void writeStartObject() throws IOException - { - _verifyValueWrite("start an object"); - _writeContext = _writeContext.createChildObjectContext(); - if (_cfgPrettyPrinter != null) { - _cfgPrettyPrinter.writeStartObject(this); - } else { - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = '{'; - } - } - - @Override - public void writeEndObject() throws IOException - { - if (!_writeContext.inObject()) { - _reportError("Current context not Object but "+_writeContext.typeDesc()); - } - if (_cfgPrettyPrinter != null) { - _cfgPrettyPrinter.writeEndObject(this, _writeContext.getEntryCount()); - } else { - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = '}'; - } - _writeContext = _writeContext.clearAndGetParent(); - } - - /** - * Specialized version of _writeFieldName, off-lined - * to keep the "fast path" as simple (and hopefully fast) as possible. - */ - protected void _writePPFieldName(String name, boolean commaBefore) throws IOException - { - if (commaBefore) { - _cfgPrettyPrinter.writeObjectEntrySeparator(this); - } else { - _cfgPrettyPrinter.beforeObjectEntries(this); - } - - if (_cfgUnqNames) {// non-standard, omit quotes - _writeString(name); - } else { - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - _writeString(name); - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } - } - - protected void _writePPFieldName(SerializableString name, boolean commaBefore) throws IOException - { - if (commaBefore) { - _cfgPrettyPrinter.writeObjectEntrySeparator(this); - } else { - _cfgPrettyPrinter.beforeObjectEntries(this); - } - - final char[] quoted = name.asQuotedChars(); - if (_cfgUnqNames) {// non-standard, omit quotes - writeRaw(quoted, 0, quoted.length); - } else { - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - writeRaw(quoted, 0, quoted.length); - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } - } - - /* - /********************************************************** - /* Output method implementations, textual - /********************************************************** - */ - - @Override - public void writeString(String text) throws IOException - { - _verifyValueWrite(WRITE_STRING); - if (text == null) { - _writeNull(); - return; - } - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - _writeString(text); - // And finally, closing quotes - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } - - @Override - public void writeString(char[] text, int offset, int len) throws IOException - { - _verifyValueWrite(WRITE_STRING); - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - _writeString(text, offset, len); - // And finally, closing quotes - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } - - @Override - public void writeString(SerializableString sstr) throws IOException - { - _verifyValueWrite(WRITE_STRING); - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - // Note: copied from writeRaw: - char[] text = sstr.asQuotedChars(); - final int len = text.length; - // Only worth buffering if it's a short write? - if (len < SHORT_WRITE) { - int room = _outputEnd - _outputTail; - if (len > room) { - _flushBuffer(); - } - System.arraycopy(text, 0, _outputBuffer, _outputTail, len); - _outputTail += len; - } else { - // Otherwise, better just pass through: - _flushBuffer(); - _writer.write(text, 0, len); - } - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } - - @Override - public void writeRawUTF8String(byte[] text, int offset, int length) throws IOException { - // could add support for buffering if we really want it... - _reportUnsupportedOperation(); - } - - @Override - public void writeUTF8String(byte[] text, int offset, int length) throws IOException { - // could add support for buffering if we really want it... - _reportUnsupportedOperation(); - } - - /* - /********************************************************** - /* Output method implementations, unprocessed ("raw") - /********************************************************** - */ - - @Override - public void writeRaw(String text) throws IOException - { - // Nothing to check, can just output as is - int len = text.length(); - int room = _outputEnd - _outputTail; - - if (room == 0) { - _flushBuffer(); - room = _outputEnd - _outputTail; - } - // But would it nicely fit in? If yes, it's easy - if (room >= len) { - text.getChars(0, len, _outputBuffer, _outputTail); - _outputTail += len; - } else { - writeRawLong(text); - } - } - - @Override - public void writeRaw(String text, int start, int len) throws IOException - { - // Nothing to check, can just output as is - int room = _outputEnd - _outputTail; - - if (room < len) { - _flushBuffer(); - room = _outputEnd - _outputTail; - } - // But would it nicely fit in? If yes, it's easy - if (room >= len) { - text.getChars(start, start+len, _outputBuffer, _outputTail); - _outputTail += len; - } else { - writeRawLong(text.substring(start, start+len)); - } - } - - // @since 2.1 - @Override - public void writeRaw(SerializableString text) throws IOException { - writeRaw(text.getValue()); - } - - @Override - public void writeRaw(char[] text, int offset, int len) throws IOException - { - // Only worth buffering if it's a short write? - if (len < SHORT_WRITE) { - int room = _outputEnd - _outputTail; - if (len > room) { - _flushBuffer(); - } - System.arraycopy(text, offset, _outputBuffer, _outputTail, len); - _outputTail += len; - return; - } - // Otherwise, better just pass through: - _flushBuffer(); - _writer.write(text, offset, len); - } - - @Override - public void writeRaw(char c) throws IOException - { - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = c; - } - - private void writeRawLong(String text) throws IOException - { - int room = _outputEnd - _outputTail; - // If not, need to do it by looping - text.getChars(0, room, _outputBuffer, _outputTail); - _outputTail += room; - _flushBuffer(); - int offset = room; - int len = text.length() - room; - - while (len > _outputEnd) { - int amount = _outputEnd; - text.getChars(offset, offset+amount, _outputBuffer, 0); - _outputHead = 0; - _outputTail = amount; - _flushBuffer(); - offset += amount; - len -= amount; - } - // And last piece (at most length of buffer) - text.getChars(offset, offset+len, _outputBuffer, 0); - _outputHead = 0; - _outputTail = len; - } - - /* - /********************************************************** - /* Output method implementations, base64-encoded binary - /********************************************************** - */ - - @Override - public void writeBinary(Base64Variant b64variant, byte[] data, int offset, int len) - throws IOException, JsonGenerationException - { - _verifyValueWrite(WRITE_BINARY); - // Starting quotes - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - _writeBinary(b64variant, data, offset, offset+len); - // and closing quotes - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } - - @Override - public int writeBinary(Base64Variant b64variant, - InputStream data, int dataLength) - throws IOException, JsonGenerationException - { - _verifyValueWrite(WRITE_BINARY); - // Starting quotes - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - byte[] encodingBuffer = _ioContext.allocBase64Buffer(); - int bytes; - try { - if (dataLength < 0) { // length unknown - bytes = _writeBinary(b64variant, data, encodingBuffer); - } else { - int missing = _writeBinary(b64variant, data, encodingBuffer, dataLength); - if (missing > 0) { - _reportError("Too few bytes available: missing "+missing+" bytes (out of "+dataLength+")"); - } - bytes = dataLength; - } - } finally { - _ioContext.releaseBase64Buffer(encodingBuffer); - } - // and closing quotes - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - return bytes; - } - - /* - /********************************************************** - /* Output method implementations, primitive - /********************************************************** - */ - - @Override - public void writeNumber(short s) throws IOException - { - _verifyValueWrite(WRITE_NUMBER); - if (_cfgNumbersAsStrings) { - _writeQuotedShort(s); - return; - } - // up to 5 digits and possible minus sign - if ((_outputTail + 6) >= _outputEnd) { - _flushBuffer(); - } - _outputTail = NumberOutput.outputInt(s, _outputBuffer, _outputTail); - } - - private void _writeQuotedShort(short s) throws IOException { - if ((_outputTail + 8) >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - _outputTail = NumberOutput.outputInt(s, _outputBuffer, _outputTail); - _outputBuffer[_outputTail++] = _quoteChar; - } - - @Override - public void writeNumber(int i) throws IOException - { - _verifyValueWrite(WRITE_NUMBER); - if (_cfgNumbersAsStrings) { - _writeQuotedInt(i); - return; - } - // up to 10 digits and possible minus sign - if ((_outputTail + 11) >= _outputEnd) { - _flushBuffer(); - } - _outputTail = NumberOutput.outputInt(i, _outputBuffer, _outputTail); - } - - private void _writeQuotedInt(int i) throws IOException { - if ((_outputTail + 13) >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - _outputTail = NumberOutput.outputInt(i, _outputBuffer, _outputTail); - _outputBuffer[_outputTail++] = _quoteChar; - } - - @Override - public void writeNumber(long l) throws IOException - { - _verifyValueWrite(WRITE_NUMBER); - if (_cfgNumbersAsStrings) { - _writeQuotedLong(l); - return; - } - if ((_outputTail + 21) >= _outputEnd) { - // up to 20 digits, minus sign - _flushBuffer(); - } - _outputTail = NumberOutput.outputLong(l, _outputBuffer, _outputTail); - } - - private void _writeQuotedLong(long l) throws IOException { - if ((_outputTail + 23) >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - _outputTail = NumberOutput.outputLong(l, _outputBuffer, _outputTail); - _outputBuffer[_outputTail++] = _quoteChar; - } - - // !!! 05-Aug-2008, tatus: Any ways to optimize these? - - @Override - public void writeNumber(BigInteger value) throws IOException - { - _verifyValueWrite(WRITE_NUMBER); - if (value == null) { - _writeNull(); - } else if (_cfgNumbersAsStrings) { - _writeQuotedRaw(value.toString()); - } else { - writeRaw(value.toString()); - } - } - - - @Override - public void writeNumber(double d) throws IOException - { - if (_cfgNumbersAsStrings || - // [JACKSON-139] - (isEnabled(Feature.QUOTE_NON_NUMERIC_NUMBERS) && ((Double.isNaN(d) || Double.isInfinite(d))))) { - writeString(String.valueOf(d)); - return; - } - // What is the max length for doubles? 40 chars? - _verifyValueWrite(WRITE_NUMBER); - writeRaw(String.valueOf(d)); - } - - @Override - public void writeNumber(float f) throws IOException - { - if (_cfgNumbersAsStrings || - // [JACKSON-139] - (isEnabled(Feature.QUOTE_NON_NUMERIC_NUMBERS) && ((Float.isNaN(f) || Float.isInfinite(f))))) { - writeString(String.valueOf(f)); - return; - } - // What is the max length for floats? - _verifyValueWrite(WRITE_NUMBER); - writeRaw(String.valueOf(f)); - } - - @Override - public void writeNumber(BigDecimal value) throws IOException - { - // Don't really know max length for big decimal, no point checking - _verifyValueWrite(WRITE_NUMBER); - if (value == null) { - _writeNull(); - } else if (_cfgNumbersAsStrings) { - _writeQuotedRaw(_asString(value)); - } else { - writeRaw(_asString(value)); - } - } - - @Override - public void writeNumber(String encodedValue) throws IOException - { - _verifyValueWrite(WRITE_NUMBER); - if (_cfgNumbersAsStrings) { - _writeQuotedRaw(encodedValue); - } else { - writeRaw(encodedValue); - } - } - - private void _writeQuotedRaw(String value) throws IOException - { - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - writeRaw(value); - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = _quoteChar; - } - - @Override - public void writeBoolean(boolean state) throws IOException - { - _verifyValueWrite(WRITE_BOOLEAN); - if ((_outputTail + 5) >= _outputEnd) { - _flushBuffer(); - } - int ptr = _outputTail; - char[] buf = _outputBuffer; - if (state) { - buf[ptr] = 't'; - buf[++ptr] = 'r'; - buf[++ptr] = 'u'; - buf[++ptr] = 'e'; - } else { - buf[ptr] = 'f'; - buf[++ptr] = 'a'; - buf[++ptr] = 'l'; - buf[++ptr] = 's'; - buf[++ptr] = 'e'; - } - _outputTail = ptr+1; - } - - @Override - public void writeNull() throws IOException { - _verifyValueWrite(WRITE_NULL); - _writeNull(); - } - - /* - /********************************************************** - /* Implementations for other methods - /********************************************************** - */ - - @Override - protected void _verifyValueWrite(String typeMsg) throws IOException - { - final int status = _writeContext.writeValue(); - if (_cfgPrettyPrinter != null) { - // Otherwise, pretty printer knows what to do... - _verifyPrettyValueWrite(typeMsg, status); - return; - } - char c; - switch (status) { - case JsonWriteContext.STATUS_OK_AS_IS: - default: - return; - case JsonWriteContext.STATUS_OK_AFTER_COMMA: - c = ','; - break; - case JsonWriteContext.STATUS_OK_AFTER_COLON: - c = ':'; - break; - case JsonWriteContext.STATUS_OK_AFTER_SPACE: // root-value separator - if (_rootValueSeparator != null) { - writeRaw(_rootValueSeparator.getValue()); - } - return; - case JsonWriteContext.STATUS_EXPECT_NAME: - _reportCantWriteValueExpectName(typeMsg); - return; - } - if (_outputTail >= _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = c; - } - - /* - /********************************************************** - /* Low-level output handling - /********************************************************** - */ - - @Override - public void flush() throws IOException - { - _flushBuffer(); - if (_writer != null) { - if (isEnabled(Feature.FLUSH_PASSED_TO_STREAM)) { - _writer.flush(); - } - } - } - - @Override - public void close() throws IOException - { - super.close(); - - /* 05-Dec-2008, tatu: To add [JACKSON-27], need to close open - * scopes. - */ - // First: let's see that we still have buffers... - if (_outputBuffer != null - && isEnabled(Feature.AUTO_CLOSE_JSON_CONTENT)) { - while (true) { - JsonStreamContext ctxt = getOutputContext(); - if (ctxt.inArray()) { - writeEndArray(); - } else if (ctxt.inObject()) { - writeEndObject(); - } else { - break; - } - } - } - _flushBuffer(); - _outputHead = 0; - _outputTail = 0; - - /* 25-Nov-2008, tatus: As per [JACKSON-16] we are not to call close() - * on the underlying Reader, unless we "own" it, or auto-closing - * feature is enabled. - * One downside: when using UTF8Writer, underlying buffer(s) - * may not be properly recycled if we don't close the writer. - */ - if (_writer != null) { - if (_ioContext.isResourceManaged() || isEnabled(Feature.AUTO_CLOSE_TARGET)) { - _writer.close(); - } else if (isEnabled(Feature.FLUSH_PASSED_TO_STREAM)) { - // If we can't close it, we should at least flush - _writer.flush(); - } - } - // Internal buffer(s) generator has can now be released as well - _releaseBuffers(); - } - - @Override - protected void _releaseBuffers() - { - char[] buf = _outputBuffer; - if (buf != null) { - _outputBuffer = null; - _ioContext.releaseConcatBuffer(buf); - } - } - - /* - /********************************************************** - /* Internal methods, low-level writing; text, default - /********************************************************** - */ - - private void _writeString(String text) throws IOException - { - /* One check first: if String won't fit in the buffer, let's - * segment writes. No point in extending buffer to huge sizes - * (like if someone wants to include multi-megabyte base64 - * encoded stuff or such) - */ - final int len = text.length(); - if (len > _outputEnd) { // Let's reserve space for entity at begin/end - _writeLongString(text); - return; - } - - // Ok: we know String will fit in buffer ok - // But do we need to flush first? - if ((_outputTail + len) > _outputEnd) { - _flushBuffer(); - } - text.getChars(0, len, _outputBuffer, _outputTail); - - if (_characterEscapes != null) { - _writeStringCustom(len); - } else if (_maximumNonEscapedChar != 0) { - _writeStringASCII(len, _maximumNonEscapedChar); - } else { - _writeString2(len); - } - } - - private void _writeString2(final int len) throws IOException - { - // And then we'll need to verify need for escaping etc: - final int end = _outputTail + len; - final int[] escCodes = _outputEscapes; - final int escLen = escCodes.length; - - output_loop: - while (_outputTail < end) { - // Fast loop for chars not needing escaping - escape_loop: - while (true) { - char c = _outputBuffer[_outputTail]; - if (c < escLen && escCodes[c] != 0) { - break escape_loop; - } - if (++_outputTail >= end) { - break output_loop; - } - } - - // Ok, bumped into something that needs escaping. - /* First things first: need to flush the buffer. - * Inlined, as we don't want to lose tail pointer - */ - int flushLen = (_outputTail - _outputHead); - if (flushLen > 0) { - _writer.write(_outputBuffer, _outputHead, flushLen); - } - /* In any case, tail will be the new start, so hopefully - * we have room now. - */ - char c = _outputBuffer[_outputTail++]; - _prependOrWriteCharacterEscape(c, escCodes[c]); - } - } - - /** - * Method called to write "long strings", strings whose length exceeds - * output buffer length. - */ - private void _writeLongString(String text) throws IOException - { - // First things first: let's flush the buffer to get some more room - _flushBuffer(); - - // Then we can write - final int textLen = text.length(); - int offset = 0; - do { - int max = _outputEnd; - int segmentLen = ((offset + max) > textLen) - ? (textLen - offset) : max; - text.getChars(offset, offset+segmentLen, _outputBuffer, 0); - if (_characterEscapes != null) { - _writeSegmentCustom(segmentLen); - } else if (_maximumNonEscapedChar != 0) { - _writeSegmentASCII(segmentLen, _maximumNonEscapedChar); - } else { - _writeSegment(segmentLen); - } - offset += segmentLen; - } while (offset < textLen); - } - - /** - * Method called to output textual context which has been copied - * to the output buffer prior to call. If any escaping is needed, - * it will also be handled by the method. - *

- * Note: when called, textual content to write is within output - * buffer, right after buffered content (if any). That's why only - * length of that text is passed, as buffer and offset are implied. - */ - private void _writeSegment(int end) throws IOException - { - final int[] escCodes = _outputEscapes; - final int escLen = escCodes.length; - - int ptr = 0; - int start = ptr; - - output_loop: - while (ptr < end) { - // Fast loop for chars not needing escaping - char c; - while (true) { - c = _outputBuffer[ptr]; - if (c < escLen && escCodes[c] != 0) { - break; - } - if (++ptr >= end) { - break; - } - } - - // Ok, bumped into something that needs escaping. - /* First things first: need to flush the buffer. - * Inlined, as we don't want to lose tail pointer - */ - int flushLen = (ptr - start); - if (flushLen > 0) { - _writer.write(_outputBuffer, start, flushLen); - if (ptr >= end) { - break output_loop; - } - } - ++ptr; - // So; either try to prepend (most likely), or write directly: - start = _prependOrWriteCharacterEscape(_outputBuffer, ptr, end, c, escCodes[c]); - } - } - - /** - * This method called when the string content is already in - * a char buffer, and need not be copied for processing. - */ - private void _writeString(char[] text, int offset, int len) throws IOException - { - if (_characterEscapes != null) { - _writeStringCustom(text, offset, len); - return; - } - if (_maximumNonEscapedChar != 0) { - _writeStringASCII(text, offset, len, _maximumNonEscapedChar); - return; - } - - /* Let's just find longest spans of non-escapable - * content, and for each see if it makes sense - * to copy them, or write through - */ - len += offset; // -> len marks the end from now on - final int[] escCodes = _outputEscapes; - final int escLen = escCodes.length; - while (offset < len) { - int start = offset; - - while (true) { - char c = text[offset]; - if (c < escLen && escCodes[c] != 0) { - break; - } - if (++offset >= len) { - break; - } - } - - // Short span? Better just copy it to buffer first: - int newAmount = offset - start; - if (newAmount < SHORT_WRITE) { - // Note: let's reserve room for escaped char (up to 6 chars) - if ((_outputTail + newAmount) > _outputEnd) { - _flushBuffer(); - } - if (newAmount > 0) { - System.arraycopy(text, start, _outputBuffer, _outputTail, newAmount); - _outputTail += newAmount; - } - } else { // Nope: better just write through - _flushBuffer(); - _writer.write(text, start, newAmount); - } - // Was this the end? - if (offset >= len) { // yup - break; - } - // Nope, need to escape the char. - char c = text[offset++]; - _appendCharacterEscape(c, escCodes[c]); - } - } - - /* - /********************************************************** - /* Internal methods, low-level writing, text segment - /* with additional escaping (ASCII or such) - /********************************************************** - */ - - /* Same as "_writeString2()", except needs additional escaping - * for subset of characters - */ - private void _writeStringASCII(final int len, final int maxNonEscaped) - throws IOException, JsonGenerationException - { - // And then we'll need to verify need for escaping etc: - int end = _outputTail + len; - final int[] escCodes = _outputEscapes; - final int escLimit = Math.min(escCodes.length, maxNonEscaped+1); - int escCode = 0; - - output_loop: - while (_outputTail < end) { - char c; - // Fast loop for chars not needing escaping - escape_loop: - while (true) { - c = _outputBuffer[_outputTail]; - if (c < escLimit) { - escCode = escCodes[c]; - if (escCode != 0) { - break escape_loop; - } - } else if (c > maxNonEscaped) { - escCode = CharacterEscapes.ESCAPE_STANDARD; - break escape_loop; - } - if (++_outputTail >= end) { - break output_loop; - } - } - int flushLen = (_outputTail - _outputHead); - if (flushLen > 0) { - _writer.write(_outputBuffer, _outputHead, flushLen); - } - ++_outputTail; - _prependOrWriteCharacterEscape(c, escCode); - } - } - - private void _writeSegmentASCII(int end, final int maxNonEscaped) - throws IOException, JsonGenerationException - { - final int[] escCodes = _outputEscapes; - final int escLimit = Math.min(escCodes.length, maxNonEscaped+1); - - int ptr = 0; - int escCode = 0; - int start = ptr; - - output_loop: - while (ptr < end) { - // Fast loop for chars not needing escaping - char c; - while (true) { - c = _outputBuffer[ptr]; - if (c < escLimit) { - escCode = escCodes[c]; - if (escCode != 0) { - break; - } - } else if (c > maxNonEscaped) { - escCode = CharacterEscapes.ESCAPE_STANDARD; - break; - } - if (++ptr >= end) { - break; - } - } - int flushLen = (ptr - start); - if (flushLen > 0) { - _writer.write(_outputBuffer, start, flushLen); - if (ptr >= end) { - break output_loop; - } - } - ++ptr; - start = _prependOrWriteCharacterEscape(_outputBuffer, ptr, end, c, escCode); - } - } - - private void _writeStringASCII(char[] text, int offset, int len, - final int maxNonEscaped) - throws IOException, JsonGenerationException - { - len += offset; // -> len marks the end from now on - final int[] escCodes = _outputEscapes; - final int escLimit = Math.min(escCodes.length, maxNonEscaped+1); - - int escCode = 0; - - while (offset < len) { - int start = offset; - char c; - - while (true) { - c = text[offset]; - if (c < escLimit) { - escCode = escCodes[c]; - if (escCode != 0) { - break; - } - } else if (c > maxNonEscaped) { - escCode = CharacterEscapes.ESCAPE_STANDARD; - break; - } - if (++offset >= len) { - break; - } - } - - // Short span? Better just copy it to buffer first: - int newAmount = offset - start; - if (newAmount < SHORT_WRITE) { - // Note: let's reserve room for escaped char (up to 6 chars) - if ((_outputTail + newAmount) > _outputEnd) { - _flushBuffer(); - } - if (newAmount > 0) { - System.arraycopy(text, start, _outputBuffer, _outputTail, newAmount); - _outputTail += newAmount; - } - } else { // Nope: better just write through - _flushBuffer(); - _writer.write(text, start, newAmount); - } - // Was this the end? - if (offset >= len) { // yup - break; - } - // Nope, need to escape the char. - ++offset; - _appendCharacterEscape(c, escCode); - } - } - - /* - /********************************************************** - /* Internal methods, low-level writing, text segment - /* with custom escaping (possibly coupling with ASCII limits) - /********************************************************** - */ - - /* Same as "_writeString2()", except needs additional escaping - * for subset of characters - */ - private void _writeStringCustom(final int len) - throws IOException, JsonGenerationException - { - // And then we'll need to verify need for escaping etc: - int end = _outputTail + len; - final int[] escCodes = _outputEscapes; - final int maxNonEscaped = (_maximumNonEscapedChar < 1) ? 0xFFFF : _maximumNonEscapedChar; - final int escLimit = Math.min(escCodes.length, maxNonEscaped+1); - int escCode = 0; - final CharacterEscapes customEscapes = _characterEscapes; - - output_loop: - while (_outputTail < end) { - char c; - // Fast loop for chars not needing escaping - escape_loop: - while (true) { - c = _outputBuffer[_outputTail]; - if (c < escLimit) { - escCode = escCodes[c]; - if (escCode != 0) { - break escape_loop; - } - } else if (c > maxNonEscaped) { - escCode = CharacterEscapes.ESCAPE_STANDARD; - break escape_loop; - } else { - if ((_currentEscape = customEscapes.getEscapeSequence(c)) != null) { - escCode = CharacterEscapes.ESCAPE_CUSTOM; - break escape_loop; - } - } - if (++_outputTail >= end) { - break output_loop; - } - } - int flushLen = (_outputTail - _outputHead); - if (flushLen > 0) { - _writer.write(_outputBuffer, _outputHead, flushLen); - } - ++_outputTail; - _prependOrWriteCharacterEscape(c, escCode); - } - } - - private void _writeSegmentCustom(int end) - throws IOException, JsonGenerationException - { - final int[] escCodes = _outputEscapes; - final int maxNonEscaped = (_maximumNonEscapedChar < 1) ? 0xFFFF : _maximumNonEscapedChar; - final int escLimit = Math.min(escCodes.length, maxNonEscaped+1); - final CharacterEscapes customEscapes = _characterEscapes; - - int ptr = 0; - int escCode = 0; - int start = ptr; - - output_loop: - while (ptr < end) { - // Fast loop for chars not needing escaping - char c; - while (true) { - c = _outputBuffer[ptr]; - if (c < escLimit) { - escCode = escCodes[c]; - if (escCode != 0) { - break; - } - } else if (c > maxNonEscaped) { - escCode = CharacterEscapes.ESCAPE_STANDARD; - break; - } else { - if ((_currentEscape = customEscapes.getEscapeSequence(c)) != null) { - escCode = CharacterEscapes.ESCAPE_CUSTOM; - break; - } - } - if (++ptr >= end) { - break; - } - } - int flushLen = (ptr - start); - if (flushLen > 0) { - _writer.write(_outputBuffer, start, flushLen); - if (ptr >= end) { - break output_loop; - } - } - ++ptr; - start = _prependOrWriteCharacterEscape(_outputBuffer, ptr, end, c, escCode); - } - } - - private void _writeStringCustom(char[] text, int offset, int len) - throws IOException, JsonGenerationException - { - len += offset; // -> len marks the end from now on - final int[] escCodes = _outputEscapes; - final int maxNonEscaped = (_maximumNonEscapedChar < 1) ? 0xFFFF : _maximumNonEscapedChar; - final int escLimit = Math.min(escCodes.length, maxNonEscaped+1); - final CharacterEscapes customEscapes = _characterEscapes; - - int escCode = 0; - - while (offset < len) { - int start = offset; - char c; - - while (true) { - c = text[offset]; - if (c < escLimit) { - escCode = escCodes[c]; - if (escCode != 0) { - break; - } - } else if (c > maxNonEscaped) { - escCode = CharacterEscapes.ESCAPE_STANDARD; - break; - } else { - if ((_currentEscape = customEscapes.getEscapeSequence(c)) != null) { - escCode = CharacterEscapes.ESCAPE_CUSTOM; - break; - } - } - if (++offset >= len) { - break; - } - } - - // Short span? Better just copy it to buffer first: - int newAmount = offset - start; - if (newAmount < SHORT_WRITE) { - // Note: let's reserve room for escaped char (up to 6 chars) - if ((_outputTail + newAmount) > _outputEnd) { - _flushBuffer(); - } - if (newAmount > 0) { - System.arraycopy(text, start, _outputBuffer, _outputTail, newAmount); - _outputTail += newAmount; - } - } else { // Nope: better just write through - _flushBuffer(); - _writer.write(text, start, newAmount); - } - // Was this the end? - if (offset >= len) { // yup - break; - } - // Nope, need to escape the char. - ++offset; - _appendCharacterEscape(c, escCode); - } - } - - /* - /********************************************************** - /* Internal methods, low-level writing; binary - /********************************************************** - */ - - protected void _writeBinary(Base64Variant b64variant, byte[] input, int inputPtr, final int inputEnd) - throws IOException, JsonGenerationException - { - // Encoding is by chunks of 3 input, 4 output chars, so: - int safeInputEnd = inputEnd - 3; - // Let's also reserve room for possible (and quoted) lf char each round - int safeOutputEnd = _outputEnd - 6; - int chunksBeforeLF = b64variant.getMaxLineLength() >> 2; - - // Ok, first we loop through all full triplets of data: - while (inputPtr <= safeInputEnd) { - if (_outputTail > safeOutputEnd) { // need to flush - _flushBuffer(); - } - // First, mash 3 bytes into lsb of 32-bit int - int b24 = ((int) input[inputPtr++]) << 8; - b24 |= ((int) input[inputPtr++]) & 0xFF; - b24 = (b24 << 8) | (((int) input[inputPtr++]) & 0xFF); - _outputTail = b64variant.encodeBase64Chunk(b24, _outputBuffer, _outputTail); - if (--chunksBeforeLF <= 0) { - // note: must quote in JSON value - _outputBuffer[_outputTail++] = '\\'; - _outputBuffer[_outputTail++] = 'n'; - chunksBeforeLF = b64variant.getMaxLineLength() >> 2; - } - } - - // And then we may have 1 or 2 leftover bytes to encode - int inputLeft = inputEnd - inputPtr; // 0, 1 or 2 - if (inputLeft > 0) { // yes, but do we have room for output? - if (_outputTail > safeOutputEnd) { // don't really need 6 bytes but... - _flushBuffer(); - } - int b24 = ((int) input[inputPtr++]) << 16; - if (inputLeft == 2) { - b24 |= (((int) input[inputPtr++]) & 0xFF) << 8; - } - _outputTail = b64variant.encodeBase64Partial(b24, inputLeft, _outputBuffer, _outputTail); - } - } - - // write-method called when length is definitely known - protected int _writeBinary(Base64Variant b64variant, - InputStream data, byte[] readBuffer, int bytesLeft) - throws IOException, JsonGenerationException - { - int inputPtr = 0; - int inputEnd = 0; - int lastFullOffset = -3; - - // Let's also reserve room for possible (and quoted) lf char each round - int safeOutputEnd = _outputEnd - 6; - int chunksBeforeLF = b64variant.getMaxLineLength() >> 2; - - while (bytesLeft > 2) { // main loop for full triplets - if (inputPtr > lastFullOffset) { - inputEnd = _readMore(data, readBuffer, inputPtr, inputEnd, bytesLeft); - inputPtr = 0; - if (inputEnd < 3) { // required to try to read to have at least 3 bytes - break; - } - lastFullOffset = inputEnd-3; - } - if (_outputTail > safeOutputEnd) { // need to flush - _flushBuffer(); - } - int b24 = ((int) readBuffer[inputPtr++]) << 8; - b24 |= ((int) readBuffer[inputPtr++]) & 0xFF; - b24 = (b24 << 8) | (((int) readBuffer[inputPtr++]) & 0xFF); - bytesLeft -= 3; - _outputTail = b64variant.encodeBase64Chunk(b24, _outputBuffer, _outputTail); - if (--chunksBeforeLF <= 0) { - _outputBuffer[_outputTail++] = '\\'; - _outputBuffer[_outputTail++] = 'n'; - chunksBeforeLF = b64variant.getMaxLineLength() >> 2; - } - } - - // And then we may have 1 or 2 leftover bytes to encode - if (bytesLeft > 0) { - inputEnd = _readMore(data, readBuffer, inputPtr, inputEnd, bytesLeft); - inputPtr = 0; - if (inputEnd > 0) { // yes, but do we have room for output? - if (_outputTail > safeOutputEnd) { // don't really need 6 bytes but... - _flushBuffer(); - } - int b24 = ((int) readBuffer[inputPtr++]) << 16; - int amount; - if (inputPtr < inputEnd) { - b24 |= (((int) readBuffer[inputPtr]) & 0xFF) << 8; - amount = 2; - } else { - amount = 1; - } - _outputTail = b64variant.encodeBase64Partial(b24, amount, _outputBuffer, _outputTail); - bytesLeft -= amount; - } - } - return bytesLeft; - } - - // write method when length is unknown - protected int _writeBinary(Base64Variant b64variant, - InputStream data, byte[] readBuffer) - throws IOException, JsonGenerationException - { - int inputPtr = 0; - int inputEnd = 0; - int lastFullOffset = -3; - int bytesDone = 0; - - // Let's also reserve room for possible (and quoted) LF char each round - int safeOutputEnd = _outputEnd - 6; - int chunksBeforeLF = b64variant.getMaxLineLength() >> 2; - - // Ok, first we loop through all full triplets of data: - while (true) { - if (inputPtr > lastFullOffset) { // need to load more - inputEnd = _readMore(data, readBuffer, inputPtr, inputEnd, readBuffer.length); - inputPtr = 0; - if (inputEnd < 3) { // required to try to read to have at least 3 bytes - break; - } - lastFullOffset = inputEnd-3; - } - if (_outputTail > safeOutputEnd) { // need to flush - _flushBuffer(); - } - // First, mash 3 bytes into lsb of 32-bit int - int b24 = ((int) readBuffer[inputPtr++]) << 8; - b24 |= ((int) readBuffer[inputPtr++]) & 0xFF; - b24 = (b24 << 8) | (((int) readBuffer[inputPtr++]) & 0xFF); - bytesDone += 3; - _outputTail = b64variant.encodeBase64Chunk(b24, _outputBuffer, _outputTail); - if (--chunksBeforeLF <= 0) { - _outputBuffer[_outputTail++] = '\\'; - _outputBuffer[_outputTail++] = 'n'; - chunksBeforeLF = b64variant.getMaxLineLength() >> 2; - } - } - - // And then we may have 1 or 2 leftover bytes to encode - if (inputPtr < inputEnd) { // yes, but do we have room for output? - if (_outputTail > safeOutputEnd) { // don't really need 6 bytes but... - _flushBuffer(); - } - int b24 = ((int) readBuffer[inputPtr++]) << 16; - int amount = 1; - if (inputPtr < inputEnd) { - b24 |= (((int) readBuffer[inputPtr]) & 0xFF) << 8; - amount = 2; - } - bytesDone += amount; - _outputTail = b64variant.encodeBase64Partial(b24, amount, _outputBuffer, _outputTail); - } - return bytesDone; - } - - private int _readMore(InputStream in, - byte[] readBuffer, int inputPtr, int inputEnd, - int maxRead) throws IOException - { - // anything to shift to front? - int i = 0; - while (inputPtr < inputEnd) { - readBuffer[i++] = readBuffer[inputPtr++]; - } - inputPtr = 0; - inputEnd = i; - maxRead = Math.min(maxRead, readBuffer.length); - - do { - int length = maxRead - inputEnd; - if (length == 0) { - break; - } - int count = in.read(readBuffer, inputEnd, length); - if (count < 0) { - return inputEnd; - } - inputEnd += count; - } while (inputEnd < 3); - return inputEnd; - } - - /* - /********************************************************** - /* Internal methods, low-level writing, other - /********************************************************** - */ - - private final void _writeNull() throws IOException - { - if ((_outputTail + 4) >= _outputEnd) { - _flushBuffer(); - } - int ptr = _outputTail; - char[] buf = _outputBuffer; - buf[ptr] = 'n'; - buf[++ptr] = 'u'; - buf[++ptr] = 'l'; - buf[++ptr] = 'l'; - _outputTail = ptr+1; - } - - /* - /********************************************************** - /* Internal methods, low-level writing, escapes - /********************************************************** - */ - - /** - * Method called to try to either prepend character escape at front of - * given buffer; or if not possible, to write it out directly. - * Uses head and tail pointers (and updates as necessary) - */ - private void _prependOrWriteCharacterEscape(char ch, int escCode) - throws IOException, JsonGenerationException - { - if (escCode >= 0) { // \\N (2 char) - if (_outputTail >= 2) { // fits, just prepend - int ptr = _outputTail - 2; - _outputHead = ptr; - _outputBuffer[ptr++] = '\\'; - _outputBuffer[ptr] = (char) escCode; - return; - } - // won't fit, write - char[] buf = _entityBuffer; - if (buf == null) { - buf = _allocateEntityBuffer(); - } - _outputHead = _outputTail; - buf[1] = (char) escCode; - _writer.write(buf, 0, 2); - return; - } - if (escCode != CharacterEscapes.ESCAPE_CUSTOM) { // std, \\uXXXX - if (_outputTail >= 6) { // fits, prepend to buffer - char[] buf = _outputBuffer; - int ptr = _outputTail - 6; - _outputHead = ptr; - buf[ptr] = '\\'; - buf[++ptr] = 'u'; - // We know it's a control char, so only the last 2 chars are non-0 - if (ch > 0xFF) { // beyond 8 bytes - int hi = (ch >> 8) & 0xFF; - buf[++ptr] = HEX_CHARS[hi >> 4]; - buf[++ptr] = HEX_CHARS[hi & 0xF]; - ch &= 0xFF; - } else { - buf[++ptr] = '0'; - buf[++ptr] = '0'; - } - buf[++ptr] = HEX_CHARS[ch >> 4]; - buf[++ptr] = HEX_CHARS[ch & 0xF]; - return; - } - // won't fit, flush and write - char[] buf = _entityBuffer; - if (buf == null) { - buf = _allocateEntityBuffer(); - } - _outputHead = _outputTail; - if (ch > 0xFF) { // beyond 8 bytes - int hi = (ch >> 8) & 0xFF; - int lo = ch & 0xFF; - buf[10] = HEX_CHARS[hi >> 4]; - buf[11] = HEX_CHARS[hi & 0xF]; - buf[12] = HEX_CHARS[lo >> 4]; - buf[13] = HEX_CHARS[lo & 0xF]; - _writer.write(buf, 8, 6); - } else { // We know it's a control char, so only the last 2 chars are non-0 - buf[6] = HEX_CHARS[ch >> 4]; - buf[7] = HEX_CHARS[ch & 0xF]; - _writer.write(buf, 2, 6); - } - return; - } - String escape; - - if (_currentEscape == null) { - escape = _characterEscapes.getEscapeSequence(ch).getValue(); - } else { - escape = _currentEscape.getValue(); - _currentEscape = null; - } - int len = escape.length(); - if (_outputTail >= len) { // fits in, prepend - int ptr = _outputTail - len; - _outputHead = ptr; - escape.getChars(0, len, _outputBuffer, ptr); - return; - } - // won't fit, write separately - _outputHead = _outputTail; - _writer.write(escape); - } - - /** - * Method called to try to either prepend character escape at front of - * given buffer; or if not possible, to write it out directly. - * - * @return Pointer to start of prepended entity (if prepended); or 'ptr' - * if not. - */ - private int _prependOrWriteCharacterEscape(char[] buffer, int ptr, int end, - char ch, int escCode) - throws IOException, JsonGenerationException - { - if (escCode >= 0) { // \\N (2 char) - if (ptr > 1 && ptr < end) { // fits, just prepend - ptr -= 2; - buffer[ptr] = '\\'; - buffer[ptr+1] = (char) escCode; - } else { // won't fit, write - char[] ent = _entityBuffer; - if (ent == null) { - ent = _allocateEntityBuffer(); - } - ent[1] = (char) escCode; - _writer.write(ent, 0, 2); - } - return ptr; - } - if (escCode != CharacterEscapes.ESCAPE_CUSTOM) { // std, \\uXXXX - if (ptr > 5 && ptr < end) { // fits, prepend to buffer - ptr -= 6; - buffer[ptr++] = '\\'; - buffer[ptr++] = 'u'; - // We know it's a control char, so only the last 2 chars are non-0 - if (ch > 0xFF) { // beyond 8 bytes - int hi = (ch >> 8) & 0xFF; - buffer[ptr++] = HEX_CHARS[hi >> 4]; - buffer[ptr++] = HEX_CHARS[hi & 0xF]; - ch &= 0xFF; - } else { - buffer[ptr++] = '0'; - buffer[ptr++] = '0'; - } - buffer[ptr++] = HEX_CHARS[ch >> 4]; - buffer[ptr] = HEX_CHARS[ch & 0xF]; - ptr -= 5; - } else { - // won't fit, flush and write - char[] ent = _entityBuffer; - if (ent == null) { - ent = _allocateEntityBuffer(); - } - _outputHead = _outputTail; - if (ch > 0xFF) { // beyond 8 bytes - int hi = (ch >> 8) & 0xFF; - int lo = ch & 0xFF; - ent[10] = HEX_CHARS[hi >> 4]; - ent[11] = HEX_CHARS[hi & 0xF]; - ent[12] = HEX_CHARS[lo >> 4]; - ent[13] = HEX_CHARS[lo & 0xF]; - _writer.write(ent, 8, 6); - } else { // We know it's a control char, so only the last 2 chars are non-0 - ent[6] = HEX_CHARS[ch >> 4]; - ent[7] = HEX_CHARS[ch & 0xF]; - _writer.write(ent, 2, 6); - } - } - return ptr; - } - String escape; - if (_currentEscape == null) { - escape = _characterEscapes.getEscapeSequence(ch).getValue(); - } else { - escape = _currentEscape.getValue(); - _currentEscape = null; - } - int len = escape.length(); - if (ptr >= len && ptr < end) { // fits in, prepend - ptr -= len; - escape.getChars(0, len, buffer, ptr); - } else { // won't fit, write separately - _writer.write(escape); - } - return ptr; - } - - /** - * Method called to append escape sequence for given character, at the - * end of standard output buffer; or if not possible, write out directly. - */ - private void _appendCharacterEscape(char ch, int escCode) - throws IOException, JsonGenerationException - { - if (escCode >= 0) { // \\N (2 char) - if ((_outputTail + 2) > _outputEnd) { - _flushBuffer(); - } - _outputBuffer[_outputTail++] = '\\'; - _outputBuffer[_outputTail++] = (char) escCode; - return; - } - if (escCode != CharacterEscapes.ESCAPE_CUSTOM) { // std, \\uXXXX - if ((_outputTail + 5) >= _outputEnd) { - _flushBuffer(); - } - int ptr = _outputTail; - char[] buf = _outputBuffer; - buf[ptr++] = '\\'; - buf[ptr++] = 'u'; - // We know it's a control char, so only the last 2 chars are non-0 - if (ch > 0xFF) { // beyond 8 bytes - int hi = (ch >> 8) & 0xFF; - buf[ptr++] = HEX_CHARS[hi >> 4]; - buf[ptr++] = HEX_CHARS[hi & 0xF]; - ch &= 0xFF; - } else { - buf[ptr++] = '0'; - buf[ptr++] = '0'; - } - buf[ptr++] = HEX_CHARS[ch >> 4]; - buf[ptr++] = HEX_CHARS[ch & 0xF]; - _outputTail = ptr; - return; - } - String escape; - if (_currentEscape == null) { - escape = _characterEscapes.getEscapeSequence(ch).getValue(); - } else { - escape = _currentEscape.getValue(); - _currentEscape = null; - } - int len = escape.length(); - if ((_outputTail + len) > _outputEnd) { - _flushBuffer(); - if (len > _outputEnd) { // very very long escape; unlikely but theoretically possible - _writer.write(escape); - return; - } - } - escape.getChars(0, len, _outputBuffer, _outputTail); - _outputTail += len; - } - - private char[] _allocateEntityBuffer() - { - char[] buf = new char[14]; - // first 2 chars, non-numeric escapes (like \n) - buf[0] = '\\'; - // next 6; 8-bit escapes (control chars mostly) - buf[2] = '\\'; - buf[3] = 'u'; - buf[4] = '0'; - buf[5] = '0'; - // last 6, beyond 8 bits - buf[8] = '\\'; - buf[9] = 'u'; - _entityBuffer = buf; - return buf; - } - - protected void _flushBuffer() throws IOException - { - int len = _outputTail - _outputHead; - if (len > 0) { - int offset = _outputHead; - _outputTail = _outputHead = 0; - _writer.write(_outputBuffer, offset, len); - } - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/sym/ByteQuadsCanonicalizer.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/sym/ByteQuadsCanonicalizer.java deleted file mode 100644 index b18e70fc..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/sym/ByteQuadsCanonicalizer.java +++ /dev/null @@ -1,1269 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.sym; - -import java.util.Arrays; -import java.util.concurrent.atomic.AtomicReference; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonFactory; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.InternCache; - -/** - * Replacement for BytesToNameCanonicalizer which aims at more localized - * memory access due to flattening of name quad data. - * Performance improvement modest for simple JSON document data binding (maybe 3%), - * but should help more for larger symbol tables, or for binary formats like Smile. - * - * @since 2.6 - */ -public final class ByteQuadsCanonicalizer -{ - /** - * Initial size of the primary hash area. Each entry consumes 4 ints (16 bytes), - * and secondary area is same as primary; so default size will use 2kB of memory_tertiaryStart - * (plus 64x4 or 64x8 (256/512 bytes) for references to Strings, and Strings - * themselves). - */ - private static final int DEFAULT_T_SIZE = 64; -// private static final int DEFAULT_T_SIZE = 256; - - /** - * Let's not expand symbol tables past some maximum size; - * this should protected against OOMEs caused by large documents - * with unique (~= random) names. - * Size is in - */ - private static final int MAX_T_SIZE = 0x10000; // 64k entries == 2M mem hash area - - /** - * No point in trying to construct tiny tables, just need to resize soon. - */ - private final static int MIN_HASH_SIZE = 16; - - /** - * Let's only share reasonably sized symbol tables. Max size set to 3/4 of 8k; - * this corresponds to 256k main hash index. This should allow for enough distinct - * names for almost any case, while preventing ballooning for cases where names - * are unique (or close thereof). - */ - final static int MAX_ENTRIES_FOR_REUSE = 6000; - - /* - /********************************************************** - /* Linkage, needed for merging symbol tables - /********************************************************** - */ - - /** - * Reference to the root symbol table, for child tables, so - * that they can merge table information back as necessary. - */ - final private ByteQuadsCanonicalizer _parent; - - /** - * Member that is only used by the root table instance: root - * passes immutable state into child instances, and children - * may return new state if they add entries to the table. - * Child tables do NOT use the reference. - */ - final private AtomicReference _tableInfo; - - /** - * Seed value we use as the base to make hash codes non-static between - * different runs, but still stable for lifetime of a single symbol table - * instance. - * This is done for security reasons, to avoid potential DoS attack via - * hash collisions. - */ - final private int _seed; - - /* - /********************************************************** - /* Configuration - /********************************************************** - */ - - /** - * Whether canonical symbol Strings are to be intern()ed before added - * to the table or not. - *

- * NOTE: non-final to allow disabling intern()ing in case of excessive - * collisions. - */ - private boolean _intern; - - /** - * Flag that indicates whether we should throw an exception if enough - * hash collisions are detected (true); or just worked around (false). - * - * @since 2.4 - */ - private final boolean _failOnDoS; - - /* - /********************************************************** - /* First, main hash area info - /********************************************************** - */ - - /** - * Primary hash information area: consists of 2 * _hashSize - * entries of 16 bytes (4 ints), arranged in a cascading lookup - * structure (details of which may be tweaked depending on expected rates - * of collisions). - */ - private int[] _hashArea; - - /** - * Number of slots for primary entries within {@link #_hashArea}; which is - * at most 1/8 of actual size of the underlying array (4-int slots, - * primary covers only half of the area; plus, additional area for longer - * symbols after hash area). - */ - private int _hashSize; - - /** - * Offset within {@link #_hashArea} where secondary entries start - */ - private int _secondaryStart; - - /** - * Offset within {@link #_hashArea} where tertiary entries start - */ - private int _tertiaryStart; - - /** - * Constant that determines size of buckets for tertiary entries: - * 1 << _tertiaryShift is the size, and shift value - * is also used for translating from primary offset into - * tertiary bucket (shift right by 4 + _tertiaryShift). - *

- * Default value is 2, for buckets of 4 slots; grows bigger with - * bigger table sizes. - */ - private int _tertiaryShift; - - /** - * Total number of Strings in the symbol table; only used for child tables. - */ - private int _count; - - /** - * Array that contains String instances matching - * entries in {@link #_hashArea}. - * Contains nulls for unused entries. Note that this size is twice - * that of {@link #_hashArea} - */ - private String[] _names; - - /* - /********************************************************** - /* Then information on collisions etc - /********************************************************** - */ - - /** - * Pointer to the offset within spill-over area where there is room - * for more spilled over entries (if any). - * Spill over area is within fixed-size portion of {@link #_hashArea}. - */ - private int _spilloverEnd; - - /** - * Offset within {@link #_hashArea} that follows main slots and contains - * quads for longer names (13 bytes or longers), and points to the - * first available int that may be used for appending quads of the next - * long name. - * Note that long name area follows immediately after the fixed-size - * main hash area ({@link #_hashArea}). - */ - private int _longNameOffset; - - /** - * This flag is set if, after adding a new entry, it is deemed - * that a rehash is warranted if any more entries are to be added. - */ - private transient boolean _needRehash; - - /* - /********************************************************** - /* Sharing, versioning - /********************************************************** - */ - - // // // Which of the buffers may be shared (and are copy-on-write)? - - /** - * Flag that indicates whether underlying data structures for - * the main hash area are shared or not. If they are, then they - * need to be handled in copy-on-write way, i.e. if they need - * to be modified, a copy needs to be made first; at this point - * it will not be shared any more, and can be modified. - *

- * This flag needs to be checked both when adding new main entries, - * and when adding new collision list queues (i.e. creating a new - * collision list head entry) - */ - private boolean _hashShared; - - /* - /********************************************************** - /* Life-cycle: constructors - /********************************************************** - */ - - /** - * Constructor used for creating per-JsonFactory "root" - * symbol tables: ones used for merging and sharing common symbols - * - * @param sz Initial primary hash area size - * @param intern Whether Strings contained should be {@link String#intern}ed - * @param seed Random seed valued used to make it more difficult to cause - * collisions (used for collision-based DoS attacks). - */ - private ByteQuadsCanonicalizer(int sz, boolean intern, int seed, boolean failOnDoS) { - _parent = null; - _seed = seed; - _intern = intern; - _failOnDoS = failOnDoS; - // Sanity check: let's now allow hash sizes below certain minimum value - if (sz < MIN_HASH_SIZE) { - sz = MIN_HASH_SIZE; - } else { - // Also; size must be 2^N; otherwise hash algorithm won't - // work... so let's just pad it up, if so - if ((sz & (sz - 1)) != 0) { // only true if it's 2^N - int curr = MIN_HASH_SIZE; - while (curr < sz) { - curr += curr; - } - sz = curr; - } - } - _tableInfo = new AtomicReference(TableInfo.createInitial(sz)); - } - - /** - * Constructor used when creating a child instance - */ - private ByteQuadsCanonicalizer(ByteQuadsCanonicalizer parent, boolean intern, - int seed, boolean failOnDoS, TableInfo state) - { - _parent = parent; - _seed = seed; - _intern = intern; - _failOnDoS = failOnDoS; - _tableInfo = null; // not used by child tables - - // Then copy shared state - _count = state.count; - _hashSize = state.size; - _secondaryStart = _hashSize << 2; // right after primary area - _tertiaryStart = _secondaryStart + (_secondaryStart >> 1); // right after secondary - _tertiaryShift = state.tertiaryShift; - - _hashArea = state.mainHash; - _names = state.names; - - _spilloverEnd = state.spilloverEnd; - _longNameOffset = state.longNameOffset; - - // and then set other state to reflect sharing status - _needRehash = false; - _hashShared = true; - } - - /* - /********************************************************** - /* Life-cycle: factory methods, merging - /********************************************************** - */ - - /** - * Factory method to call to create a symbol table instance with a - * randomized seed value. - */ - public static ByteQuadsCanonicalizer createRoot() { - /* [jackson-core#21]: Need to use a variable seed, to thwart hash-collision - * based attacks. - */ - long now = System.currentTimeMillis(); - // ensure it's not 0; and might as well require to be odd so: - int seed = (((int) now) + ((int) (now >>> 32))) | 1; - return createRoot(seed); - } - - /** - * Factory method that should only be called from unit tests, where seed - * value should remain the same. - */ - protected static ByteQuadsCanonicalizer createRoot(int seed) { - return new ByteQuadsCanonicalizer(DEFAULT_T_SIZE, true, seed, true); - } - - /** - * Factory method used to create actual symbol table instance to - * use for parsing. - */ - public ByteQuadsCanonicalizer makeChild(int flags) { - return new ByteQuadsCanonicalizer(this, - JsonFactory.Feature.INTERN_FIELD_NAMES.enabledIn(flags), - _seed, - JsonFactory.Feature.FAIL_ON_SYMBOL_HASH_OVERFLOW.enabledIn(flags), - _tableInfo.get()); - } - - /** - * Method called by the using code to indicate it is done - * with this instance. This lets instance merge accumulated - * changes into parent (if need be), safely and efficiently, - * and without calling code having to know about parent - * information - */ - public void release() - { - // we will try to merge if child table has new entries - if (_parent != null && maybeDirty()) { - _parent.mergeChild(new TableInfo(this)); - /* Let's also mark this instance as dirty, so that just in - * case release was too early, there's no corruption of possibly shared data. - */ - _hashShared = true; - } - } - - private void mergeChild(TableInfo childState) - { - final int childCount = childState.count; - TableInfo currState = _tableInfo.get(); - - // Should usually grow; but occasionally could also shrink if (but only if) - // collision list overflow ends up clearing some collision lists. - if (childCount == currState.count) { - return; - } - - // One caveat: let's try to avoid problems with degenerate cases of documents with - // generated "random" names: for these, symbol tables would bloat indefinitely. - // One way to do this is to just purge tables if they grow - // too large, and that's what we'll do here. - if (childCount > MAX_ENTRIES_FOR_REUSE) { - // At any rate, need to clean up the tables - childState = TableInfo.createInitial(DEFAULT_T_SIZE); - } - _tableInfo.compareAndSet(currState, childState); - } - - /* - /********************************************************** - /* API, accessors - /********************************************************** - */ - - public int size() - { - if (_tableInfo != null) { // root table - return _tableInfo.get().count; - } - // nope, child table - return _count; - } - - /** - * Returns number of primary slots table has currently - */ - public int bucketCount() { return _hashSize; } - - /** - * Method called to check to quickly see if a child symbol table - * may have gotten additional entries. Used for checking to see - * if a child table should be merged into shared table. - */ - public boolean maybeDirty() { return !_hashShared; } - - public int hashSeed() { return _seed; } - - /** - * Method mostly needed by unit tests; calculates number of - * entries that are in the primary slot set. These are - * "perfect" entries, accessible with a single lookup - */ - public int primaryCount() - { - int count = 0; - for (int offset = 3, end = _secondaryStart; offset < end; offset += 4) { - if (_hashArea[offset] != 0) { - ++count; - } - } - return count; - } - - /** - * Method mostly needed by unit tests; calculates number of entries - * in secondary buckets - */ - public int secondaryCount() { - int count = 0; - int offset = _secondaryStart + 3; - for (int end = _tertiaryStart; offset < end; offset += 4) { - if (_hashArea[offset] != 0) { - ++count; - } - } - return count; - } - - /** - * Method mostly needed by unit tests; calculates number of entries - * in tertiary buckets - */ - public int tertiaryCount() { - int count = 0; - int offset = _tertiaryStart + 3; // to 1.5x, starting point of tertiary - for (int end = offset + _hashSize; offset < end; offset += 4) { - if (_hashArea[offset] != 0) { - ++count; - } - } - return count; - } - - /** - * Method mostly needed by unit tests; calculates number of entries - * in shared spillover area - */ - public int spilloverCount() { - // difference between spillover end, start, divided by 4 (four ints per slot) - return (_spilloverEnd - _spilloverStart()) >> 2; - } - - public int totalCount() - { - int count = 0; - for (int offset = 3, end = (_hashSize << 3); offset < end; offset += 4) { - if (_hashArea[offset] != 0) { - ++count; - } - } - return count; - } - - @Override - public String toString() { - int pri = primaryCount(); - int sec = secondaryCount(); - int tert = tertiaryCount(); - int spill = spilloverCount(); - int total = totalCount(); - return String.format("[%s: size=%d, hashSize=%d, %d/%d/%d/%d pri/sec/ter/spill (=%s), total:%d]", - getClass().getName(), _count, _hashSize, - pri, sec, tert, spill, (pri+sec+tert+spill), total); - } - - /* - /********************************************************** - /* Public API, accessing symbols - /********************************************************** - */ - - public String findName(int q1) - { - int offset = _calcOffset(calcHash(q1)); - // first: primary match? - final int[] hashArea = _hashArea; - - int len = hashArea[offset+3]; - - if (len == 1) { - if (hashArea[offset] == q1) { - return _names[offset >> 2]; - } - } else if (len == 0) { // empty slot; unlikely but avoid further lookups if so - return null; - } - // secondary? single slot shared by N/2 primaries - int offset2 = _secondaryStart + ((offset >> 3) << 2); - - len = hashArea[offset2+3]; - - if (len == 1) { - if (hashArea[offset2] == q1) { - return _names[offset2 >> 2]; - } - } else if (len == 0) { // empty slot; unlikely but avoid further lookups if so - return null; - } - - // tertiary lookup & spillovers best to offline - return _findSecondary(offset, q1); - } - - public String findName(int q1, int q2) - { - int offset = _calcOffset(calcHash(q1, q2)); - - final int[] hashArea = _hashArea; - - int len = hashArea[offset+3]; - - if (len == 2) { - if ((q1 == hashArea[offset]) && (q2 == hashArea[offset+1])) { - return _names[offset >> 2]; - } - } else if (len == 0) { // empty slot; unlikely but avoid further lookups if so - return null; - } - // secondary? - int offset2 = _secondaryStart + ((offset >> 3) << 2); - - len = hashArea[offset2+3]; - - if (len == 2) { - if ((q1 == hashArea[offset2]) && (q2 == hashArea[offset2+1])) { - return _names[offset2 >> 2]; - } - } else if (len == 0) { // empty slot? Short-circuit if no more spillovers - return null; - } - return _findSecondary(offset, q1, q2); - } - - public String findName(int q1, int q2, int q3) - { - int offset = _calcOffset(calcHash(q1, q2, q3)); - final int[] hashArea = _hashArea; - int len = hashArea[offset+3]; - - if (len == 3) { - if ((q1 == hashArea[offset]) && (hashArea[offset+1] == q2) && (hashArea[offset+2] == q3)) { - return _names[offset >> 2]; - } - } else if (len == 0) { // empty slot; unlikely but avoid further lookups if so - return null; - } - // secondary? - int offset2 = _secondaryStart + ((offset >> 3) << 2); - - len = hashArea[offset2+3]; - - if (len == 3) { - if ((q1 == hashArea[offset2]) && (hashArea[offset2+1] == q2) && (hashArea[offset2+2] == q3)) { - return _names[offset2 >> 2]; - } - } else if (len == 0) { // empty slot? Short-circuit if no more spillovers - return null; - } - return _findSecondary(offset, q1, q2, q3); - } - - public String findName(int[] q, int qlen) - { - /* This version differs significantly, because longer names do not fit within cell. - * Rather, they contain hash in main slot, and offset+length to extension area - * that contains actual quads. - */ - if (qlen < 4) { // another sanity check - if (qlen == 3) { - return findName(q[0], q[1], q[2]); - } - if (qlen == 2) { - return findName(q[0], q[1]); - } - return findName(q[0]); - } - final int hash = calcHash(q, qlen); - int offset = _calcOffset(hash); - - final int[] hashArea = _hashArea; - - final int len = hashArea[offset+3]; - - if ((hash == hashArea[offset]) && (len == qlen)) { - // probable but not guaranteed: verify - if (_verifyLongName(q, qlen, hashArea[offset+1])) { - return _names[offset >> 2]; - } - } - if (len == 0) { // empty slot; unlikely but avoid further lookups if so - return null; - } - // secondary? - int offset2 = _secondaryStart + ((offset >> 3) << 2); - - final int len2 = hashArea[offset2+3]; - if ((hash == hashArea[offset2]) && (len2 == qlen)) { - if (_verifyLongName(q, qlen, hashArea[offset2+1])) { - return _names[offset2 >> 2]; - } - } - return _findSecondary(offset, hash, q, qlen); - } - - private final int _calcOffset(int hash) - { - // NOTE: simple for initial impl, but we may want to interleave it a bit - // in near future - // So: first, hash into primary hash index - int ix = hash & (_hashSize-1); - // keeping in mind we have 4 ints per entry - return (ix << 2); - } - - /* - /********************************************************** - /* Access from spill-over areas - /********************************************************** - */ - - private String _findSecondary(int origOffset, int q1) - { - // tertiary area division is dynamic. First; its size is N/4 compared to - // primary hash size; and offsets are for 4 int slots. So to get to logical - // index would shift by 4. But! Tertiary area is further split into buckets, - // determined by shift value. And finally, from bucket back into physical offsets - int offset = _tertiaryStart + ((origOffset >> (_tertiaryShift + 2)) << _tertiaryShift); - final int[] hashArea = _hashArea; - final int bucketSize = (1 << _tertiaryShift); - for (int end = offset + bucketSize; offset < end; offset += 4) { - int len = hashArea[offset+3]; - if ((q1 == hashArea[offset]) && (1 == len)) { - return _names[offset >> 2]; - } - if (len == 0) { - return null; - } - } - // but if tertiary full, check out spill-over area as last resort - // shared spillover starts at 7/8 of the main hash area - // (which is sized at 2 * _hashSize), so: - for (offset = _spilloverStart(); offset < _spilloverEnd; offset += 4) { - if ((q1 == hashArea[offset]) && (1 == hashArea[offset+3])) { - return _names[offset >> 2]; - } - } - return null; - } - - private String _findSecondary(int origOffset, int q1, int q2) - { - int offset = _tertiaryStart + ((origOffset >> (_tertiaryShift + 2)) << _tertiaryShift); - final int[] hashArea = _hashArea; - - final int bucketSize = (1 << _tertiaryShift); - for (int end = offset + bucketSize; offset < end; offset += 4) { - int len = hashArea[offset+3]; - if ((q1 == hashArea[offset]) && (q2 == hashArea[offset+1]) && (2 == len)) { - return _names[offset >> 2]; - } - if (len == 0) { - return null; - } - } - for (offset = _spilloverStart(); offset < _spilloverEnd; offset += 4) { - if ((q1 == hashArea[offset]) && (q2 == hashArea[offset+1]) && (2 == hashArea[offset+3])) { - return _names[offset >> 2]; - } - } - return null; - } - - private String _findSecondary(int origOffset, int q1, int q2, int q3) - { - int offset = _tertiaryStart + ((origOffset >> (_tertiaryShift + 2)) << _tertiaryShift); - final int[] hashArea = _hashArea; - - final int bucketSize = (1 << _tertiaryShift); - for (int end = offset + bucketSize; offset < end; offset += 4) { - int len = hashArea[offset+3]; - if ((q1 == hashArea[offset]) && (q2 == hashArea[offset+1]) && (q3 == hashArea[offset+2]) && (3 == len)) { - return _names[offset >> 2]; - } - if (len == 0) { - return null; - } - } - for (offset = _spilloverStart(); offset < _spilloverEnd; offset += 4) { - if ((q1 == hashArea[offset]) && (q2 == hashArea[offset+1]) && (q3 == hashArea[offset+2]) - && (3 == hashArea[offset+3])) { - return _names[offset >> 2]; - } - } - return null; - } - - private String _findSecondary(int origOffset, int hash, int[] q, int qlen) - { - int offset = _tertiaryStart + ((origOffset >> (_tertiaryShift + 2)) << _tertiaryShift); - final int[] hashArea = _hashArea; - - final int bucketSize = (1 << _tertiaryShift); - for (int end = offset + bucketSize; offset < end; offset += 4) { - int len = hashArea[offset+3]; - if ((hash == hashArea[offset]) && (qlen == len)) { - if (_verifyLongName(q, qlen, hashArea[offset+1])) { - return _names[offset >> 2]; - } - } - if (len == 0) { - return null; - } - } - for (offset = _spilloverStart(); offset < _spilloverEnd; offset += 4) { - if ((hash == hashArea[offset]) && (qlen == hashArea[offset+3])) { - if (_verifyLongName(q, qlen, hashArea[offset+1])) { - return _names[offset >> 2]; - } - } - } - return null; - } - - private boolean _verifyLongName(int[] q, int qlen, int spillOffset) - { - final int[] hashArea = _hashArea; - // spillOffset assumed to be physical index right into quad string - int ix = 0; - - switch (qlen) { - default: - return _verifyLongName2(q, qlen, spillOffset); - case 8: - if (q[ix++] != hashArea[spillOffset++]) return false; - case 7: - if (q[ix++] != hashArea[spillOffset++]) return false; - case 6: - if (q[ix++] != hashArea[spillOffset++]) return false; - case 5: - if (q[ix++] != hashArea[spillOffset++]) return false; - case 4: // always at least 4 - if (q[ix++] != hashArea[spillOffset++]) return false; - if (q[ix++] != hashArea[spillOffset++]) return false; - if (q[ix++] != hashArea[spillOffset++]) return false; - if (q[ix++] != hashArea[spillOffset++]) return false; - } - return true; - } - - private boolean _verifyLongName2(int[] q, int qlen, int spillOffset) - { - int ix = 0; - do { - if (q[ix++] != _hashArea[spillOffset++]) { - return false; - } - } while (ix < qlen); - return true; - } - - /* - /********************************************************** - /* API, mutators - /********************************************************** - */ - - public String addName(String name, int q1) { - _verifySharing(); - if (_intern) { - name = InternCache.instance.intern(name); - } - int offset = _findOffsetForAdd(calcHash(q1)); - _hashArea[offset] = q1; - _hashArea[offset+3] = 1; - _names[offset >> 2] = name; - ++_count; - _verifyNeedForRehash(); - return name; - } - - public String addName(String name, int q1, int q2) { - _verifySharing(); - if (_intern) { - name = InternCache.instance.intern(name); - } - int hash = (q2 == 0) ? calcHash(q1) : calcHash(q1, q2); - int offset = _findOffsetForAdd(hash); - _hashArea[offset] = q1; - _hashArea[offset+1] = q2; - _hashArea[offset+3] = 2; - _names[offset >> 2] = name; - ++_count; - _verifyNeedForRehash(); - return name; - } - - public String addName(String name, int q1, int q2, int q3) { - _verifySharing(); - if (_intern) { - name = InternCache.instance.intern(name); - } - int offset = _findOffsetForAdd(calcHash(q1, q2, q3)); - _hashArea[offset] = q1; - _hashArea[offset+1] = q2; - _hashArea[offset+2] = q3; - _hashArea[offset+3] = 3; - _names[offset >> 2] = name; - ++_count; - _verifyNeedForRehash(); - return name; - } - - public String addName(String name, int[] q, int qlen) - { - _verifySharing(); - if (_intern) { - name = InternCache.instance.intern(name); - } - int offset; - - switch (qlen) { - case 1: - { - offset = _findOffsetForAdd(calcHash(q[0])); - _hashArea[offset] = q[0]; - _hashArea[offset+3] = 1; - } - break; - case 2: - { - offset = _findOffsetForAdd(calcHash(q[0], q[1])); - _hashArea[offset] = q[0]; - _hashArea[offset+1] = q[1]; - _hashArea[offset+3] = 2; - } - break; - case 3: - { - offset = _findOffsetForAdd(calcHash(q[0], q[1], q[2])); - _hashArea[offset] = q[0]; - _hashArea[offset+1] = q[1]; - _hashArea[offset+2] = q[2]; - _hashArea[offset+3] = 3; - } - break; - default: - final int hash = calcHash(q, qlen); - offset = _findOffsetForAdd(hash); - - _hashArea[offset] = hash; - int longStart = _appendLongName(q, qlen); - _hashArea[offset+1] = longStart; - _hashArea[offset+3] = qlen; - } - // plus add the actual String - _names[offset >> 2] = name; - - // and finally; see if we really should rehash. - ++_count; - _verifyNeedForRehash(); - return name; - } - - private void _verifyNeedForRehash() { - // Yes if above 80%, or above 50% AND have ~1% spill-overs - if (_count > (_hashSize >> 1)) { // over 50% - int spillCount = (_spilloverEnd - _spilloverStart()) >> 2; - if ((spillCount > (1 + _count >> 7)) - || (_count > (_hashSize * 0.80))) { - _needRehash = true; - } - } - } - - private void _verifySharing() - { - if (_hashShared) { - _hashArea = Arrays.copyOf(_hashArea, _hashArea.length); - _names = Arrays.copyOf(_names, _names.length); - _hashShared = false; - // 09-Sep-2015, tatu: As per [jackson-core#216], also need to ensure - // we rehash as needed, as need-rehash flag is not copied from parent - _verifyNeedForRehash(); - } - if (_needRehash) { - rehash(); - } - } - - /** - * Method called to find the location within hash table to add a new symbol in. - */ - private int _findOffsetForAdd(int hash) - { - // first, check the primary: - int offset = _calcOffset(hash); - final int[] hashArea = _hashArea; - if (hashArea[offset+3] == 0) { -//System.err.printf(" PRImary slot #%d, hash %X\n", (offset>>2), hash & 0x7F); - return offset; - } - // then secondary - int offset2 = _secondaryStart + ((offset >> 3) << 2); - if (hashArea[offset2+3] == 0) { -//System.err.printf(" SECondary slot #%d (start x%X), hash %X\n",(offset >> 3), _secondaryStart, (hash & 0x7F)); - return offset2; - } - // if not, tertiary? - - offset2 = _tertiaryStart + ((offset >> (_tertiaryShift + 2)) << _tertiaryShift); - final int bucketSize = (1 << _tertiaryShift); - for (int end = offset2 + bucketSize; offset2 < end; offset2 += 4) { - if (hashArea[offset2+3] == 0) { -//System.err.printf(" TERtiary slot x%X (from x%X, start x%X), hash %X.\n", offset2, ((offset >> (_tertiaryShift + 2)) << _tertiaryShift), _tertiaryStart, (hash & 0x7F)); - return offset2; - } - } - - // and if even tertiary full, append at the end of spill area - offset = _spilloverEnd; - _spilloverEnd += 4; - -//System.err.printf(" SPIll-over at x%X; start x%X; end x%X, hash %X\n", offset, _spilloverStart(), _hashArea.length, (hash & 0x7F)); - - // one caveat: in the unlikely event if spill-over filling up, - // check if that could be considered a DoS attack; handle appropriately - // (NOTE: approximate for now; we could verify details if that becomes necessary) - /* 31-Jul-2015, tatu: Note that spillover area does NOT end at end of array, - * since "long names" area follows. Instead, need to calculate from hash size. - */ - final int end = (_hashSize << 3); - if (_spilloverEnd >= end) { - if (_failOnDoS) { - _reportTooManyCollisions(); - } - // and if we didn't fail, we'll simply force rehash for next add - // (which, in turn, may double up or nuke contents, depending on size etc) - _needRehash = true; - } - return offset; - } - - private int _appendLongName(int[] quads, int qlen) - { - int start = _longNameOffset; - - // note: at this point we must already be shared. But may not have enough space - if ((start + qlen) > _hashArea.length) { - // try to increment in reasonable chunks; at least space that we need - int toAdd = (start + qlen) - _hashArea.length; - // but at least 1/8 of regular hash area size or 16kB (whichever smaller) - int minAdd = Math.min(4096, _hashSize); - - int newSize = _hashArea.length + Math.max(toAdd, minAdd); - _hashArea = Arrays.copyOf(_hashArea, newSize); - } - System.arraycopy(quads, 0, _hashArea, start, qlen); - _longNameOffset += qlen; - return start; - } - - /* - /********************************************************** - /* Hash calculation - /********************************************************** - */ - - /* Note on hash calculation: we try to make it more difficult to - * generate collisions automatically; part of this is to avoid - * simple "multiply-add" algorithm (like JDK String.hashCode()), - * and add bit of shifting. And other part is to make this - * non-linear, at least for shorter symbols. - */ - - // JDK uses 31; other fine choices are 33 and 65599, let's use 33 - // as it seems to give fewest collisions for us - // (see [http://www.cse.yorku.ca/~oz/hash.html] for details) - private final static int MULT = 33; - private final static int MULT2 = 65599; - private final static int MULT3 = 31; - - public int calcHash(int q1) - { - int hash = q1 ^ _seed; - /* 29-Mar-2015, tatu: Earlier used 15 + 9 right shifts, which worked ok - * except for one specific problem case: numbers. So needed to make sure - * that all 4 least-significant bits participate in hash. Couple of ways - * to work it out, but this is the simplest, fast and seems to do ok. - */ - hash += (hash >>> 16); // to xor hi- and low- 16-bits - hash ^= (hash << 3); // shuffle back a bit - hash += (hash >>> 12); // and bit more - return hash; - } - - public int calcHash(int q1, int q2) - { - // For two quads, let's change algorithm a bit, to spice - // things up (can do bit more processing anyway) - int hash = q1; - - hash += (hash >>> 15); // try mixing first and second byte pairs first - hash ^= (hash >>> 9); // as well as lowest 2 bytes - hash += (q2 * MULT); // then add second quad - hash ^= _seed; - hash += (hash >>> 16); // and shuffle some more - hash ^= (hash >>> 4); - hash += (hash << 3); - - return hash; - } - - public int calcHash(int q1, int q2, int q3) - { // use same algorithm as multi-byte, tested to work well - int hash = q1 ^ _seed; - hash += (hash >>> 9); - hash *= MULT3; - hash += q2; - hash *= MULT; - hash += (hash >>> 15); - hash ^= q3; - // 26-Mar-2015, tatu: As per two-quad case, a short shift seems to help more here - hash += (hash >>> 4); - - hash += (hash >>> 15); - hash ^= (hash << 9); - - return hash; - } - - public int calcHash(int[] q, int qlen) - { - if (qlen < 4) { - throw new IllegalArgumentException(); - } - /* And then change handling again for "multi-quad" case; mostly - * to make calculation of collisions less fun. For example, - * add seed bit later in the game, and switch plus/xor around, - * use different shift lengths. - */ - int hash = q[0] ^ _seed; - hash += (hash >>> 9); - hash += q[1]; - hash += (hash >>> 15); - hash *= MULT; - hash ^= q[2]; - hash += (hash >>> 4); - - for (int i = 3; i < qlen; ++i) { - int next = q[i]; - next = next ^ (next >> 21); - hash += next; - } - hash *= MULT2; - - // and finally shuffle some more once done - hash += (hash >>> 19); - hash ^= (hash << 5); - return hash; - } - - /* - /********************************************************** - /* Rehashing - /********************************************************** - */ - - private void rehash() - { - _needRehash = false; - // Note: since we'll make copies, no need to unshare, can just mark as such: - _hashShared = false; - - // And then we can first deal with the main hash area. Since we are expanding - // linearly (double up), we know there'll be no collisions during this phase. - final int[] oldHashArea = _hashArea; - final String[] oldNames = _names; - final int oldSize = _hashSize; - final int oldCount = _count; - final int newSize = oldSize + oldSize; - final int oldEnd = _spilloverEnd; - - /* 13-Mar-2010, tatu: Let's guard against OOME that could be caused by - * large documents with unique (or mostly so) names - */ - if (newSize > MAX_T_SIZE) { - nukeSymbols(true); - return; - } - // double up main hash area, but do not expand long-name area: - _hashArea = new int[oldHashArea.length + (oldSize<<3)]; - _hashSize = newSize; - _secondaryStart = (newSize << 2); // 4 ints per entry - _tertiaryStart = _secondaryStart + (_secondaryStart >> 1); // right after secondary - _tertiaryShift = _calcTertiaryShift(newSize); - - // and simply double up name array - _names = new String[oldNames.length << 1]; - nukeSymbols(false); - - // Plus we can scan only through the primary hash area, looking for non-empty - // slots, without worrying about ordering. This should never reduce priority - // of existing entries: primaries remain primaries; however, due to increased - // space, secondaries may become primaries etc - - int copyCount = 0; - int[] q = new int[16]; - for (int offset = 0, end = oldEnd; offset < end; offset += 4) { - int len = oldHashArea[offset+3]; - if (len == 0) { // empty slot, skip - continue; - } - ++copyCount; - String name = oldNames[offset>>2]; - switch (len) { - case 1: - q[0] = oldHashArea[offset]; - addName(name, q, 1); - break; - case 2: - q[0] = oldHashArea[offset]; - q[1] = oldHashArea[offset+1]; - addName(name, q, 2); - break; - case 3: - q[0] = oldHashArea[offset]; - q[1] = oldHashArea[offset+1]; - q[2] = oldHashArea[offset+2]; - addName(name, q, 3); - break; - default: - if (len > q.length) { - q = new int[len]; - } - // #0 is hash, #1 offset - int qoff = oldHashArea[offset+1]; - System.arraycopy(oldHashArea, qoff, q, 0, len); - addName(name, q, len); - break; - } - } - - // Sanity checks: since corruption difficult to detect, assert explicitly - // with production code - if (copyCount != oldCount) { - throw new IllegalStateException("Failed rehash(): old count="+oldCount+", copyCount="+copyCount); - } - } - - /** - * Helper method called to empty all shared symbols, but to leave - * arrays allocated - */ - private void nukeSymbols(boolean fill) { - _count = 0; - // reset spill-over to empty (starting at 7/8 of hash area) - _spilloverEnd = _spilloverStart(); - // and long name area to empty, starting immediately after hash area - _longNameOffset = _hashSize << 3; - if (fill) { - Arrays.fill(_hashArea, 0); - Arrays.fill(_names, null); - } - } - - /* - /********************************************************** - /* Helper methods - /********************************************************** - */ - - /** - * Helper method that calculates start of the spillover area - */ - private final int _spilloverStart() { - // we'll need slot at 1.75x of hashSize, but with 4-ints per slot. - // So basically multiply by 7 - int offset = _hashSize; - return (offset << 3) - offset; - } - - protected void _reportTooManyCollisions() - { - // First: do not fuzz about small symbol tables; may get balanced by doubling up - if (_hashSize <= 1024) { // would have spill-over area of 128 entries - return; - } - throw new IllegalStateException("Spill-over slots in symbol table with "+_count - +" entries, hash area of "+_hashSize+" slots is now full (all " - +(_hashSize >> 3)+" slots -- suspect a DoS attack based on hash collisions." - +" You can disable the check via `JsonFactory.Feature.FAIL_ON_SYMBOL_HASH_OVERFLOW`"); - } - - static int _calcTertiaryShift(int primarySlots) - { - // first: we only get 1/4 of slots of primary, to divide - int tertSlots = (primarySlots) >> 2; - - // default is for buckets of 4 slots (each 4 ints, i.e. 1 << 4) - if (tertSlots < 64) { - return 4; - } - if (tertSlots <= 256) { // buckets of 8 slots (up to 256 == 32 x 8) - return 5; - } - if (tertSlots <= 1024) { // buckets of 16 slots (up to 1024 == 64 x 16) - return 6; - } - // and biggest buckets have 32 slots - return 7; - } - - /* - /********************************************************** - /* Helper classes - /********************************************************** - */ - - /** - * Immutable value class used for sharing information as efficiently - * as possible, by only require synchronization of reference manipulation - * but not access to contents. - * - * @since 2.1 - */ - private final static class TableInfo - { - public final int size; - public final int count; - public final int tertiaryShift; - public final int[] mainHash; - public final String[] names; - public final int spilloverEnd; - public final int longNameOffset; - - public TableInfo(int size, int count, int tertiaryShift, - int[] mainHash, String[] names, int spilloverEnd, int longNameOffset) - { - this.size = size; - this.count = count; - this.tertiaryShift = tertiaryShift; - this.mainHash = mainHash; - this.names = names; - this.spilloverEnd = spilloverEnd; - this.longNameOffset = longNameOffset; - } - - public TableInfo(ByteQuadsCanonicalizer src) - { - size = src._hashSize; - count = src._count; - tertiaryShift = src._tertiaryShift; - mainHash = src._hashArea; - names = src._names; - spilloverEnd = src._spilloverEnd; - longNameOffset = src._longNameOffset; - } - - public static TableInfo createInitial(int sz) { - int hashAreaSize = sz << 3; - int tertShift = _calcTertiaryShift(sz); - - return new TableInfo(sz, // hashSize - 0, // count - tertShift, - new int[hashAreaSize], // mainHash, 2x slots, 4 ints per slot - new String[sz << 1], // names == 2x slots - hashAreaSize - sz, // at 7/8 of the total area - hashAreaSize // longNameOffset, immediately after main hashes - ); - } - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/sym/CharsToNameCanonicalizer.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/sym/CharsToNameCanonicalizer.java deleted file mode 100644 index 1a9dbb25..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/sym/CharsToNameCanonicalizer.java +++ /dev/null @@ -1,788 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.sym; - -import java.util.Arrays; -import java.util.BitSet; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonFactory; -import autosaveworld.zlibs.com.fasterxml.jackson.core.util.InternCache; - -/** - * This class is a kind of specialized type-safe Map, from char array to - * String value. Specialization means that in addition to type-safety - * and specific access patterns (key char array, Value optionally interned - * String; values added on access if necessary), and that instances are - * meant to be used concurrently, but by using well-defined mechanisms - * to obtain such concurrently usable instances. Main use for the class - * is to store symbol table information for things like compilers and - * parsers; especially when number of symbols (keywords) is limited. - *

- * For optimal performance, usage pattern should be one where matches - * should be very common (especially after "warm-up"), and as with most hash-based - * maps/sets, that hash codes are uniformly distributed. Also, collisions - * are slightly more expensive than with HashMap or HashSet, since hash codes - * are not used in resolving collisions; that is, equals() comparison is - * done with all symbols in same bucket index.
- * Finally, rehashing is also more expensive, as hash codes are not - * stored; rehashing requires all entries' hash codes to be recalculated. - * Reason for not storing hash codes is reduced memory usage, hoping - * for better memory locality. - *

- * Usual usage pattern is to create a single "master" instance, and either - * use that instance in sequential fashion, or to create derived "child" - * instances, which after use, are asked to return possible symbol additions - * to master instance. In either case benefit is that symbol table gets - * initialized so that further uses are more efficient, as eventually all - * symbols needed will already be in symbol table. At that point no more - * Symbol String allocations are needed, nor changes to symbol table itself. - *

- * Note that while individual SymbolTable instances are NOT thread-safe - * (much like generic collection classes), concurrently used "child" - * instances can be freely used without synchronization. However, using - * master table concurrently with child instances can only be done if - * access to master instance is read-only (i.e. no modifications done). - */ -public final class CharsToNameCanonicalizer -{ - /* If we use "multiply-add" based hash algorithm, this is the multiplier - * we use. - *

- * Note that JDK uses 31; but it seems that 33 produces fewer collisions, - * at least with tests we have. - */ - public final static int HASH_MULT = 33; - - /** - * Default initial table size. Shouldn't be miniscule (as there's - * cost to both array realloc and rehashing), but let's keep - * it reasonably small. For systems that properly - * reuse factories it doesn't matter either way; but when - * recreating factories often, initial overhead may dominate. - */ - private static final int DEFAULT_T_SIZE = 64; - - /** - * Let's not expand symbol tables past some maximum size; - * this should protected against OOMEs caused by large documents - * with unique (~= random) names. - */ - private static final int MAX_T_SIZE = 0x10000; // 64k entries == 256k mem - - /** - * Let's only share reasonably sized symbol tables. Max size set to 3/4 of 16k; - * this corresponds to 64k main hash index. This should allow for enough distinct - * names for almost any case. - */ - static final int MAX_ENTRIES_FOR_REUSE = 12000; - - /** - * Also: to thwart attacks based on hash collisions (which may or may not - * be cheap to calculate), we will need to detect "too long" - * collision chains. Let's start with static value of 255 entries - * for the longest legal chain. - *

- * Note: longest chain we have been able to produce without malicious - * intent has been 38 (with "com.fasterxml.jackson.core.main.TestWithTonsaSymbols"); - * our setting should be reasonable here. - *

- * Also note that value was lowered from 255 (2.3 and earlier) to 100 for 2.4 - * - * @since 2.1 - */ - static final int MAX_COLL_CHAIN_LENGTH = 100; - - final static CharsToNameCanonicalizer sBootstrapSymbolTable = new CharsToNameCanonicalizer(); - - /* - /********************************************************** - /* Configuration - /********************************************************** - */ - - /** - * Sharing of learnt symbols is done by optional linking of symbol - * table instances with their parents. When parent linkage is - * defined, and child instance is released (call to release), - * parent's shared tables may be updated from the child instance. - */ - private CharsToNameCanonicalizer _parent; - - /** - * Seed value we use as the base to make hash codes non-static between - * different runs, but still stable for lifetime of a single symbol table - * instance. - * This is done for security reasons, to avoid potential DoS attack via - * hash collisions. - * - * @since 2.1 - */ - final private int _hashSeed; - - final private int _flags; - - /** - * Whether any canonicalization should be attempted (whether using - * intern or not) - */ - private boolean _canonicalize; - - /* - /********************************************************** - /* Actual symbol table data - /********************************************************** - */ - - /** - * Primary matching symbols; it's expected most match occur from - * here. - */ - private String[] _symbols; - - /** - * Overflow buckets; if primary doesn't match, lookup is done - * from here. - *

- * Note: Number of buckets is half of number of symbol entries, on - * assumption there's less need for buckets. - */ - private Bucket[] _buckets; - - /** - * Current size (number of entries); needed to know if and when - * rehash. - */ - private int _size; - - /** - * Limit that indicates maximum size this instance can hold before - * it needs to be expanded and rehashed. Calculated using fill - * factor passed in to constructor. - */ - private int _sizeThreshold; - - /** - * Mask used to get index from hash values; equal to - * _buckets.length - 1, when _buckets.length is - * a power of two. - */ - private int _indexMask; - - /** - * We need to keep track of the longest collision list; this is needed - * both to indicate problems with attacks and to allow flushing for - * other cases. - * - * @since 2.1 - */ - private int _longestCollisionList; - - /* - /********************************************************** - /* State regarding shared arrays - /********************************************************** - */ - - /** - * Flag that indicates if any changes have been made to the data; - * used to both determine if bucket array needs to be copied when - * (first) change is made, and potentially if updated bucket list - * is to be resync'ed back to master instance. - */ - private boolean _dirty; - - /* - /********************************************************** - /* Bit of DoS detection goodness - /********************************************************** - */ - - /** - * Lazily constructed structure that is used to keep track of - * collision buckets that have overflowed once: this is used - * to detect likely attempts at denial-of-service attacks that - * uses hash collisions. - * - * @since 2.4 - */ - private BitSet _overflows; - - /* - /********************************************************** - /* Life-cycle - /********************************************************** - */ - - /** - * Method called to create root canonicalizer for a {@link autosaveworld.zlibs.com.fasterxml.jackson.core.JsonFactory} - * instance. Root instance is never used directly; its main use is for - * storing and sharing underlying symbol arrays as needed. - */ - public static CharsToNameCanonicalizer createRoot() { - /* [Issue-21]: Need to use a variable seed, to thwart hash-collision - * based attacks. - */ - long now = System.currentTimeMillis(); - // ensure it's not 0; and might as well require to be odd so: - int seed = (((int) now) + ((int) (now >>> 32))) | 1; - return createRoot(seed); - } - - protected static CharsToNameCanonicalizer createRoot(int hashSeed) { - return sBootstrapSymbolTable.makeOrphan(hashSeed); - } - - /** - * Main method for constructing a master symbol table instance. - */ - private CharsToNameCanonicalizer() { - // these settings don't really matter for the bootstrap instance - _canonicalize = true; - _flags = -1; - // And we'll also set flags so no copying of buckets is needed: - _dirty = true; - _hashSeed = 0; - _longestCollisionList = 0; - initTables(DEFAULT_T_SIZE); - } - - private void initTables(int initialSize) - { - _symbols = new String[initialSize]; - _buckets = new Bucket[initialSize >> 1]; - // Mask is easy to calc for powers of two. - _indexMask = initialSize - 1; - _size = 0; - _longestCollisionList = 0; - // Hard-coded fill factor is 75% - _sizeThreshold = _thresholdSize(initialSize); - } - - private static int _thresholdSize(int hashAreaSize) { return hashAreaSize - (hashAreaSize >> 2); } - - /** - * Internal constructor used when creating child instances. - */ - private CharsToNameCanonicalizer(CharsToNameCanonicalizer parent, int flags, - String[] symbols, Bucket[] buckets, int size, int hashSeed, int longestColl) { - _parent = parent; - - _flags = flags; - _canonicalize = JsonFactory.Feature.CANONICALIZE_FIELD_NAMES.enabledIn(flags); - - _symbols = symbols; - _buckets = buckets; - _size = size; - _hashSeed = hashSeed; - // Hard-coded fill factor, 75% - int arrayLen = (symbols.length); - _sizeThreshold = _thresholdSize(arrayLen); - _indexMask = (arrayLen - 1); - _longestCollisionList = longestColl; - - // Need to make copies of arrays, if/when adding new entries - _dirty = false; - } - - /** - * "Factory" method; will create a new child instance of this symbol - * table. It will be a copy-on-write instance, ie. it will only use - * read-only copy of parent's data, but when changes are needed, a - * copy will be created. - *

- * Note: while this method is synchronized, it is generally not - * safe to both use makeChild/mergeChild, AND to use instance - * actively. Instead, a separate 'root' instance should be used - * on which only makeChild/mergeChild are called, but instance itself - * is not used as a symbol table. - */ - public CharsToNameCanonicalizer makeChild(int flags) { - /* 24-Jul-2012, tatu: Trying to reduce scope of synchronization, assuming - * that synchronizing construction is the (potentially) expensive part, - * and not so much short copy-the-variables thing. - */ - final String[] symbols; - final Bucket[] buckets; - final int size; - final int hashSeed; - final int longestCollisionList; - - synchronized (this) { - symbols = _symbols; - buckets = _buckets; - size = _size; - hashSeed = _hashSeed; - longestCollisionList = _longestCollisionList; - } - return new CharsToNameCanonicalizer(this, flags, - symbols, buckets, size, hashSeed, longestCollisionList); - } - - private CharsToNameCanonicalizer makeOrphan(int seed) { - return new CharsToNameCanonicalizer(null, -1, _symbols, _buckets, _size, seed, _longestCollisionList); - } - - /** - * Method that allows contents of child table to potentially be - * "merged in" with contents of this symbol table. - *

- * Note that caller has to make sure symbol table passed in is - * really a child or sibling of this symbol table. - */ - private void mergeChild(CharsToNameCanonicalizer child) { - /* One caveat: let's try to avoid problems with - * degenerate cases of documents with generated "random" - * names: for these, symbol tables would bloat indefinitely. - * One way to do this is to just purge tables if they grow - * too large, and that's what we'll do here. - */ - if (child.size() > MAX_ENTRIES_FOR_REUSE) { - // Should there be a way to get notified about this event, to log it or such? - // (as it's somewhat abnormal thing to happen) - // At any rate, need to clean up the tables, then: - synchronized (this) { - initTables(DEFAULT_T_SIZE * 4); // no point in starting from tiny tho - // Dirty flag... well, let's just clear it. Shouldn't really matter for master tables - // (which this is, given something is merged to it) - _dirty = false; - } - } else { - // Otherwise, we'll merge changed stuff in, if there are more entries (which - // may not be the case if one of siblings has added symbols first or such) - if (child.size() <= size()) { // nothing to add - return; - } - // Okie dokie, let's get the data in! - synchronized (this) { - _symbols = child._symbols; - _buckets = child._buckets; - _size = child._size; - _sizeThreshold = child._sizeThreshold; - _indexMask = child._indexMask; - _longestCollisionList = child._longestCollisionList; - // Dirty flag... well, let's just clear it. Shouldn't really matter for master tables - // (which this is, given something is merged to it) - _dirty = false; - } - } - } - - public void release(){ - // If nothing has been added, nothing to do - if (!maybeDirty()) { return; } - if (_parent != null && _canonicalize) { // canonicalize set to false if max size was reached - _parent.mergeChild(this); - /* Let's also mark this instance as dirty, so that just in - * case release was too early, there's no corruption - * of possibly shared data. - */ - _dirty = false; - } - } - - /* - /********************************************************** - /* Public API, generic accessors: - /********************************************************** - */ - - public int size() { return _size; } - - /** - * Method for checking number of primary hash buckets this symbol - * table uses. - * - * @since 2.1 - */ - public int bucketCount() { return _symbols.length; } - public boolean maybeDirty() { return _dirty; } - public int hashSeed() { return _hashSeed; } - - /** - * Method mostly needed by unit tests; calculates number of - * entries that are in collision list. Value can be at most - * ({@link #size} - 1), but should usually be much lower, ideally 0. - * - * @since 2.1 - */ - public int collisionCount() { - int count = 0; - - for (Bucket bucket : _buckets) { - if (bucket != null) { - count += bucket.length; - } - } - return count; - } - - /** - * Method mostly needed by unit tests; calculates length of the - * longest collision chain. This should typically be a low number, - * but may be up to {@link #size} - 1 in the pathological case - * - * @since 2.1 - */ - public int maxCollisionLength() { return _longestCollisionList; } - - /* - /********************************************************** - /* Public API, accessing symbols: - /********************************************************** - */ - - public String findSymbol(char[] buffer, int start, int len, int h) - { - if (len < 1) { // empty Strings are simplest to handle up front - return ""; - } - if (!_canonicalize) { // [JACKSON-259] - return new String(buffer, start, len); - } - - /* Related to problems with sub-standard hashing (somewhat - * relevant for collision attacks too), let's try little - * bit of shuffling to improve hash codes. - * (note, however, that this can't help with full collisions) - */ - int index = _hashToIndex(h); - String sym = _symbols[index]; - - // Optimal case; checking existing primary symbol for hash index: - if (sym != null) { - // Let's inline primary String equality checking: - if (sym.length() == len) { - int i = 0; - while (sym.charAt(i) == buffer[start+i]) { - // Optimal case; primary match found - if (++i == len) { - return sym; - } - } - } - Bucket b = _buckets[index>>1]; - if (b != null) { - sym = b.has(buffer, start, len); - if (sym != null) { - return sym; - } - sym = _findSymbol2(buffer, start, len, b.next); - if (sym != null) { - return sym; - } - } - } - return _addSymbol(buffer, start, len, h, index); - } - - private String _findSymbol2(char[] buffer, int start, int len, Bucket b) { - while (b != null) { - String sym = b.has(buffer, start, len); - if (sym != null) { - return sym; - } - b = b.next; - } - return null; - } - - private String _addSymbol(char[] buffer, int start, int len, int h, int index) - { - if (!_dirty) { //need to do copy-on-write? - copyArrays(); - _dirty = true; - } else if (_size >= _sizeThreshold) { // Need to expand? - rehash(); - /* Need to recalc hash; rare occurence (index mask has been - * recalculated as part of rehash) - */ - index = _hashToIndex(calcHash(buffer, start, len)); - } - - String newSymbol = new String(buffer, start, len); - if (JsonFactory.Feature.INTERN_FIELD_NAMES.enabledIn(_flags)) { - newSymbol = InternCache.instance.intern(newSymbol); - } - ++_size; - // Ok; do we need to add primary entry, or a bucket? - if (_symbols[index] == null) { - _symbols[index] = newSymbol; - } else { - final int bix = (index >> 1); - Bucket newB = new Bucket(newSymbol, _buckets[bix]); - int collLen = newB.length; - if (collLen > MAX_COLL_CHAIN_LENGTH) { - /* 23-May-2014, tatu: Instead of throwing an exception right away, let's handle - * in bit smarter way. - */ - _handleSpillOverflow(bix, newB); - } else { - _buckets[bix] = newB; - _longestCollisionList = Math.max(collLen, _longestCollisionList); - } - } - - return newSymbol; - } - - private void _handleSpillOverflow(int bindex, Bucket newBucket) - { - if (_overflows == null) { - _overflows = new BitSet(); - _overflows.set(bindex); - } else { - if (_overflows.get(bindex)) { - // Has happened once already, so not a coincident... - if (JsonFactory.Feature.FAIL_ON_SYMBOL_HASH_OVERFLOW.enabledIn(_flags)) { - reportTooManyCollisions(MAX_COLL_CHAIN_LENGTH); - } - // but even if we don't fail, we will stop canonicalizing: - _canonicalize = false; - } else { - _overflows.set(bindex); - } - } - // regardless, if we get this far, clear up the bucket, adjust size appropriately. - _symbols[bindex + bindex] = newBucket.symbol; - _buckets[bindex] = null; - // newBucket contains new symbol; but we wil - _size -= (newBucket.length); - // we could calculate longest; but for now just mark as invalid - _longestCollisionList = -1; - } - - /** - * Helper method that takes in a "raw" hash value, shuffles it as necessary, - * and truncates to be used as the index. - */ - public int _hashToIndex(int rawHash) { - // doing these seems to help a bit - rawHash += (rawHash >>> 15); - rawHash ^= (rawHash << 7); - rawHash += (rawHash >>> 3); - return (rawHash & _indexMask); - } - - /** - * Implementation of a hashing method for variable length - * Strings. Most of the time intention is that this calculation - * is done by caller during parsing, not here; however, sometimes - * it needs to be done for parsed "String" too. - * - * @param len Length of String; has to be at least 1 (caller guarantees - * this pre-condition) - */ - public int calcHash(char[] buffer, int start, int len) { - int hash = _hashSeed; - for (int i = start, end = start+len; i < end; ++i) { - hash = (hash * HASH_MULT) + (int) buffer[i]; - } - // NOTE: shuffling, if any, is done in 'findSymbol()', not here: - return (hash == 0) ? 1 : hash; - } - - public int calcHash(String key) - { - final int len = key.length(); - - int hash = _hashSeed; - for (int i = 0; i < len; ++i) { - hash = (hash * HASH_MULT) + (int) key.charAt(i); - } - // NOTE: shuffling, if any, is done in 'findSymbol()', not here: - return (hash == 0) ? 1 : hash; - } - - /* - /********************************************************** - /* Internal methods - /********************************************************** - */ - - /** - * Method called when copy-on-write is needed; generally when first - * change is made to a derived symbol table. - */ - private void copyArrays() { - final String[] oldSyms = _symbols; - _symbols = Arrays.copyOf(oldSyms, oldSyms.length); - final Bucket[] oldBuckets = _buckets; - _buckets = Arrays.copyOf(oldBuckets, oldBuckets.length); - } - - /** - * Method called when size (number of entries) of symbol table grows - * so big that load factor is exceeded. Since size has to remain - * power of two, arrays will then always be doubled. Main work - * is really redistributing old entries into new String/Bucket - * entries. - */ - private void rehash() { - int size = _symbols.length; - int newSize = size + size; - - /* 12-Mar-2010, tatu: Let's actually limit maximum size we are - * prepared to use, to guard against OOME in case of unbounded - * name sets (unique [non-repeating] names) - */ - if (newSize > MAX_T_SIZE) { - /* If this happens, there's no point in either growing or shrinking hash areas. - * Rather, let's just cut our losses and stop canonicalizing. - */ - _size = 0; - _canonicalize = false; - // in theory, could just leave these as null, but... - _symbols = new String[DEFAULT_T_SIZE]; - _buckets = new Bucket[DEFAULT_T_SIZE>>1]; - _indexMask = DEFAULT_T_SIZE-1; - _dirty = true; - return; - } - - String[] oldSyms = _symbols; - Bucket[] oldBuckets = _buckets; - _symbols = new String[newSize]; - _buckets = new Bucket[newSize >> 1]; - // Let's update index mask, threshold, now (needed for rehashing) - _indexMask = newSize - 1; - _sizeThreshold = _thresholdSize(newSize); - - int count = 0; // let's do sanity check - - /* Need to do two loops, unfortunately, since spill-over area is - * only half the size: - */ - int maxColl = 0; - for (int i = 0; i < size; ++i) { - String symbol = oldSyms[i]; - if (symbol != null) { - ++count; - int index = _hashToIndex(calcHash(symbol)); - if (_symbols[index] == null) { - _symbols[index] = symbol; - } else { - int bix = (index >> 1); - Bucket newB = new Bucket(symbol, _buckets[bix]); - _buckets[bix] = newB; - maxColl = Math.max(maxColl, newB.length); - } - } - } - - size >>= 1; - for (int i = 0; i < size; ++i) { - Bucket b = oldBuckets[i]; - while (b != null) { - ++count; - String symbol = b.symbol; - int index = _hashToIndex(calcHash(symbol)); - if (_symbols[index] == null) { - _symbols[index] = symbol; - } else { - int bix = (index >> 1); - Bucket newB = new Bucket(symbol, _buckets[bix]); - _buckets[bix] = newB; - maxColl = Math.max(maxColl, newB.length); - } - b = b.next; - } - } - _longestCollisionList = maxColl; - _overflows = null; - - if (count != _size) { - throw new Error("Internal error on SymbolTable.rehash(): had "+_size+" entries; now have "+count+"."); - } - } - - /** - * @since 2.1 - */ - protected void reportTooManyCollisions(int maxLen) { - throw new IllegalStateException("Longest collision chain in symbol table (of size "+_size - +") now exceeds maximum, "+maxLen+" -- suspect a DoS attack based on hash collisions"); - } - - // For debugging, comment out - /* - @Override - public String toString() - { - StringBuilder sb = new StringBuilder(); - int primaryCount = 0; - for (String s : _symbols) { - if (s != null) ++primaryCount; - } - - sb.append("[BytesToNameCanonicalizer, size: "); - sb.append(_size); - sb.append('/'); - sb.append(_symbols.length); - sb.append(", "); - sb.append(primaryCount); - sb.append('/'); - sb.append(_size - primaryCount); - sb.append(" coll; avg length: "); - - // Average length: minimum of 1 for all (1 == primary hit); - // and then 1 per each traversal for collisions/buckets - //int maxDist = 1; - int pathCount = _size; - for (Bucket b : _buckets) { - if (b != null) { - int spillLen = b.length; - for (int j = 1; j <= spillLen; ++j) { - pathCount += j; - } - } - } - double avgLength; - - if (_size == 0) { - avgLength = 0.0; - } else { - avgLength = (double) pathCount / (double) _size; - } - // let's round up a bit (two 2 decimal places) - //avgLength -= (avgLength % 0.01); - - sb.append(avgLength); - sb.append(']'); - return sb.toString(); - } -*/ - - /* - /********************************************************** - /* Bucket class - /********************************************************** - */ - - /** - * This class is a symbol table entry. Each entry acts as a node - * in a linked list. - */ - static final class Bucket - { - public final String symbol; - public final Bucket next; - public final int length; - - public Bucket(String s, Bucket n) { - symbol = s; - next = n; - length = (n == null) ? 1 : n.length+1; - } - - public String has(char[] buf, int start, int len) { - if (symbol.length() != len) { - return null; - } - int i = 0; - do { - if (symbol.charAt(i) != buf[start+i]) { - return null; - } - } while (++i < len); - return symbol; - } - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/sym/Name.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/sym/Name.java deleted file mode 100644 index e0217758..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/sym/Name.java +++ /dev/null @@ -1,55 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.sym; - -/** - * Base class for tokenized names (key strings in objects) that have - * been tokenized from byte-based input sources (like - * {@link java.io.InputStream}. - * - * @author Tatu Saloranta - */ -public abstract class Name -{ - protected final String _name; - - protected final int _hashCode; - - protected Name(String name, int hashCode) { - _name = name; - _hashCode = hashCode; - } - - public String getName() { return _name; } - - /* - /********************************************************** - /* Methods for package/core parser - /********************************************************** - */ - - public abstract boolean equals(int q1); - - public abstract boolean equals(int q1, int q2); - - /** - * @since 2.6 - */ - public abstract boolean equals(int q1, int q2, int q3); - - public abstract boolean equals(int[] quads, int qlen); - - /* - /********************************************************** - /* Overridden standard methods - /********************************************************** - */ - - @Override public String toString() { return _name; } - - @Override public final int hashCode() { return _hashCode; } - - @Override public boolean equals(Object o) - { - // Canonical instances, can usually just do identity comparison - return (o == this); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/sym/Name1.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/sym/Name1.java deleted file mode 100644 index eec1f8ca..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/sym/Name1.java +++ /dev/null @@ -1,29 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.sym; - -/** - * Specialized implementation of PName: can be used for short Strings - * that consists of at most 4 bytes. Usually this means short - * ascii-only names. - *

- * The reason for such specialized classes is mostly space efficiency; - * and to a lesser degree performance. Both are achieved for short - * Strings by avoiding another level of indirection (via quad arrays) - */ -public final class Name1 extends Name -{ - private final static Name1 EMPTY = new Name1("", 0, 0); - private final int q; - - Name1(String name, int hash, int quad) { - super(name, hash); - q = quad; - } - - public static Name1 getEmptyName() { return EMPTY; } - - @Override public boolean equals(int quad) { return (quad == q); } - @Override public boolean equals(int quad1, int quad2) { return (quad1 == q) && (quad2 == 0); } - @Override public boolean equals(int q1, int q2, int q3) { return false; } - - @Override public boolean equals(int[] quads, int qlen) { return (qlen == 1 && quads[0] == q); } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/sym/Name2.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/sym/Name2.java deleted file mode 100644 index 65dfde59..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/sym/Name2.java +++ /dev/null @@ -1,32 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.sym; - -/** - * Specialized implementation of PName: can be used for short Strings - * that consists of 5 to 8 bytes. Usually this means relatively short - * ascii-only names. - *

- * The reason for such specialized classes is mostly space efficiency; - * and to a lesser degree performance. Both are achieved for short - * Strings by avoiding another level of indirection (via quad arrays) - */ -public final class Name2 extends Name -{ - private final int q1, q2; - - Name2(String name, int hash, int quad1, int quad2) { - super(name, hash); - q1 = quad1; - q2 = quad2; - } - - @Override - public boolean equals(int quad) { return false; } - - @Override - public boolean equals(int quad1, int quad2) { return (quad1 == q1) && (quad2 == q2); } - - @Override public boolean equals(int quad1, int quad2, int q3) { return false; } - - @Override - public boolean equals(int[] quads, int qlen) { return (qlen == 2 && quads[0] == q1 && quads[1] == q2); } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/sym/Name3.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/sym/Name3.java deleted file mode 100644 index a6595c59..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/sym/Name3.java +++ /dev/null @@ -1,36 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.sym; - -/** - * Specialized implementation of PName: can be used for short Strings - * that consists of 9 to 12 bytes. It's the longest special purpose - * implementaion; longer ones are expressed using {@link NameN}. - */ -public final class Name3 extends Name -{ - private final int q1, q2, q3; - - Name3(String name, int hash, int i1, int i2, int i3) { - super(name, hash); - q1 = i1; - q2 = i2; - q3 = i3; - } - - // Implies quad length == 1, never matches - @Override - public boolean equals(int quad) { return false; } - - // Implies quad length == 2, never matches - @Override - public boolean equals(int quad1, int quad2) { return false; } - - @Override - public boolean equals(int quad1, int quad2, int quad3) { - return (q1 == quad1) && (q2 == quad2) && (q3 == quad3); - } - - @Override - public boolean equals(int[] quads, int qlen) { - return (qlen == 3) && (quads[0] == q1) && (quads[1] == q2) && (quads[2] == q3); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/sym/NameN.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/sym/NameN.java deleted file mode 100644 index 88c0c476..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/sym/NameN.java +++ /dev/null @@ -1,100 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.sym; - -import java.util.Arrays; - -/** - * Generic implementation of PName used for "long" names, where long - * means that its byte (UTF-8) representation is 13 bytes or more. - */ -public final class NameN extends Name -{ - private final int q1, q2, q3, q4; // first four quads - private final int qlen; // total number of quads (4 + q.length) - private final int[] q; - - NameN(String name, int hash, int q1, int q2, int q3, int q4, - int[] quads, int quadLen) { - super(name, hash); - this.q1 = q1; - this.q2 = q2; - this.q3 = q3; - this.q4 = q4; - q = quads; - qlen = quadLen; - } - - public static NameN construct(String name, int hash, int[] q, int qlen) - { - /* We have specialized implementations for shorter - * names, so let's not allow runt instances here - */ - if (qlen < 4) { - throw new IllegalArgumentException(); - } - int q1 = q[0]; - int q2 = q[1]; - int q3 = q[2]; - int q4 = q[3]; - - int rem = qlen - 4; - - int[] buf; - - if (rem > 0) { - buf = Arrays.copyOfRange(q, 4, qlen); - } else { - buf = null; - } - return new NameN(name, hash, q1, q2, q3, q4, buf, qlen); - - } - - // Implies quad length == 1, never matches - @Override - public boolean equals(int quad) { return false; } - - // Implies quad length == 2, never matches - @Override - public boolean equals(int quad1, int quad2) { return false; } - - // Implies quad length == 3, never matches - @Override - public boolean equals(int quad1, int quad2, int quad3) { return false; } - - @Override - public boolean equals(int[] quads, int len) { - if (len != qlen) { return false; } - - // Will always have >= 4 quads, can unroll - if (quads[0] != q1) return false; - if (quads[1] != q2) return false; - if (quads[2] != q3) return false; - if (quads[3] != q4) return false; - - switch (len) { - default: - return _equals2(quads); - case 8: - if (quads[7] != q[3]) return false; - case 7: - if (quads[6] != q[2]) return false; - case 6: - if (quads[5] != q[1]) return false; - case 5: - if (quads[4] != q[0]) return false; - case 4: - } - return true; - } - - private final boolean _equals2(int[] quads) - { - final int end = qlen-4; - for (int i = 0; i < end; ++i) { - if (quads[i+4] != q[i]) { - return false; - } - } - return true; - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/type/ResolvedType.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/type/ResolvedType.java deleted file mode 100644 index 4b0a53dd..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/type/ResolvedType.java +++ /dev/null @@ -1,169 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.type; - -/** - * Type abstraction that represents Java type that has been resolved - * (i.e. has all generic information, if any, resolved to concrete - * types). - * Note that this is an intermediate type, and all concrete instances - * MUST be of type JavaType from "databind" bundle -- this - * abstraction is only needed so that types can be passed through - * {@link autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser#readValueAs} methods. - * - * @since 2.0 - */ -public abstract class ResolvedType -{ - /* - /********************************************************** - /* Public API, simple property accessors - /********************************************************** - */ - - /** - * Accessor for type-erased {@link Class} of resolved type. - */ - public abstract Class getRawClass(); - - public abstract boolean hasRawClass(Class clz); - - public abstract boolean isAbstract(); - - public abstract boolean isConcrete(); - - public abstract boolean isThrowable(); - - public abstract boolean isArrayType(); - - public abstract boolean isEnumType(); - - public abstract boolean isInterface(); - - public abstract boolean isPrimitive(); - - public abstract boolean isFinal(); - - public abstract boolean isContainerType(); - - public abstract boolean isCollectionLikeType(); - - /** - * Whether this type is a referential type, meaning that values are - * basically pointers to "real" values (or null) and not regular - * values themselves. Typical examples include things like - * {@link java.util.concurrent.atomic.AtomicReference}, and various - * Optional types (in JDK8, Guava). - * - * @since 2.6 - */ - public boolean isReferenceType() { - return getReferencedType() != null; - } - - public abstract boolean isMapLikeType(); - - /* - /********************************************************** - /* Public API, type parameter access - /********************************************************** - */ - - /** - * Method that can be used to find out if the type directly declares generic - * parameters (for its direct super-class and/or super-interfaces). - */ - public abstract boolean hasGenericTypes(); - - /** - * Accessor that can be used to find out type for which parameterization - * is applied: this is often NOT same as what {@link #getRawClass} returns, - * but rather one of it supertype. - *

- * For example: for type like {@link java.util.HashMap}, raw type is - * {@link java.util.HashMap}; but this method would return - * {@link java.util.Map}, because relevant type parameters that are - * resolved (and accessible using {@link #containedType(int)} and - * {@link #getKeyType()}) are parameter for {@link java.util.Map} - * (which may or may not be same as type parameters for subtype; - * in case of {@link java.util.HashMap} they are, but for further - * subtypes they may be different parameters or possibly none at all). - * - * @since 2.5 - * - * @deprecated Since 2.7: does not have meaning as parameters depend on type - * resolved. - */ - @Deprecated // since 2.7 - public Class getParameterSource() { - return null; - } - - /** - * Method for accessing key type for this type, assuming type - * has such a concept (only Map types do) - */ - public abstract ResolvedType getKeyType(); - - /** - * Method for accessing content type of this type, if type has - * such a thing: simple types do not, structured types do - * (like arrays, Collections and Maps) - */ - public abstract ResolvedType getContentType(); - - /** - * Method for accessing type of value that instances of this - * type references, if any. - * - * @return Referenced type, if any; null if not. - * - * @since 2.6 - */ - public abstract ResolvedType getReferencedType(); - - /** - * Method for checking how many contained types this type - * has. Contained types are usually generic types, so that - * generic Maps have 2 contained types. - */ - public abstract int containedTypeCount(); - - /** - * Method for accessing definitions of contained ("child") - * types. - * - * @param index Index of contained type to return - * - * @return Contained type at index, or null if no such type - * exists (no exception thrown) - */ - public abstract ResolvedType containedType(int index); - - /** - * Method for accessing name of type variable in indicated - * position. If no name is bound, will use placeholders (derived - * from 0-based index); if no type variable or argument exists - * with given index, null is returned. - * - * @param index Index of contained type to return - * - * @return Contained type at index, or null if no such type - * exists (no exception thrown) - */ - public abstract String containedTypeName(int index); - - /* - /********************************************************** - /* Public API, other - /********************************************************** - */ - - /** - * Method that can be used to serialize type into form from which - * it can be fully deserialized from at a later point (using - * TypeFactory from mapper package). - * For simple types this is same as calling - * {@link Class#getName}, but for structured types it may additionally - * contain type information about contents. - */ - public abstract String toCanonical(); -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/type/TypeReference.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/type/TypeReference.java deleted file mode 100644 index c3a97bb6..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/type/TypeReference.java +++ /dev/null @@ -1,58 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.type; - -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; - -/** - * This generic abstract class is used for obtaining full generics type information - * by sub-classing; it must be converted to {@link ResolvedType} implementation - * (implemented by JavaType from "databind" bundle) to be used. - * Class is based on ideas from - * http://gafter.blogspot.com/2006/12/super-type-tokens.html, - * Additional idea (from a suggestion made in comments of the article) - * is to require bogus implementation of Comparable - * (any such generic interface would do, as long as it forces a method - * with generic type to be implemented). - * to ensure that a Type argument is indeed given. - *

- * Usage is by sub-classing: here is one way to instantiate reference - * to generic type List<Integer>: - *

- *  TypeReference ref = new TypeReference<List<Integer>>() { };
- *
- * which can be passed to methods that accept TypeReference, or resolved - * using TypeFactory to obtain {@link ResolvedType}. - */ -public abstract class TypeReference implements Comparable> -{ - protected final Type _type; - - protected TypeReference() - { - Type superClass = getClass().getGenericSuperclass(); - if (superClass instanceof Class) { // sanity check, should never happen - throw new IllegalArgumentException("Internal error: TypeReference constructed without actual type information"); - } - /* 22-Dec-2008, tatu: Not sure if this case is safe -- I suspect - * it is possible to make it fail? - * But let's deal with specific - * case when we know an actual use case, and thereby suitable - * workarounds for valid case(s) and/or error to throw - * on invalid one(s). - */ - _type = ((ParameterizedType) superClass).getActualTypeArguments()[0]; - } - - public Type getType() { return _type; } - - /** - * The only reason we define this method (and require implementation - * of Comparable) is to prevent constructing a - * reference without type information. - */ - @Override - public int compareTo(TypeReference o) { return 0; } - // just need an implementation, not a good one... hence ^^^ -} - diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/BufferRecycler.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/BufferRecycler.java deleted file mode 100644 index 875f8146..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/BufferRecycler.java +++ /dev/null @@ -1,157 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.util; - -/** - * This is a small utility class, whose main functionality is to allow - * simple reuse of raw byte/char buffers. It is usually used through - * ThreadLocal member of the owning class pointing to - * instance of this class through a SoftReference. The - * end result is a low-overhead GC-cleanable recycling: hopefully - * ideal for use by stream readers. - */ -public class BufferRecycler -{ - /** - * Buffer used for reading byte-based input. - */ - public final static int BYTE_READ_IO_BUFFER = 0; - - /** - * Buffer used for temporarily storing encoded content; used - * for example by UTF-8 encoding writer - */ - public final static int BYTE_WRITE_ENCODING_BUFFER = 1; - - /** - * Buffer used for temporarily concatenating output; used for - * example when requesting output as byte array. - */ - public final static int BYTE_WRITE_CONCAT_BUFFER = 2; - - /** - * Buffer used for concatenating binary data that is either being - * encoded as base64 output, or decoded from base64 input. - * - * @since 2.1 - */ - public final static int BYTE_BASE64_CODEC_BUFFER = 3; - - public final static int CHAR_TOKEN_BUFFER = 0; // Tokenizable input - public final static int CHAR_CONCAT_BUFFER = 1; // concatenated output - public final static int CHAR_TEXT_BUFFER = 2; // Text content from input - public final static int CHAR_NAME_COPY_BUFFER = 3; // Temporary buffer for getting name characters - - // Buffer lengths, defined in 2.4 (smaller before that) - - private final static int[] BYTE_BUFFER_LENGTHS = new int[] { 8000, 8000, 2000, 2000 }; - private final static int[] CHAR_BUFFER_LENGTHS = new int[] { 4000, 4000, 200, 200 }; - - final protected byte[][] _byteBuffers; - final protected char[][] _charBuffers; - - /* - /********************************************************** - /* Construction - /********************************************************** - */ - - /** - * Default constructor used for creating instances of this default - * implementation. - */ - public BufferRecycler() { - this(4, 4); - } - - /** - * Alternate constructor to be used by sub-classes, to allow customization - * of number of low-level buffers in use. - * - * @since 2.4 - */ - protected BufferRecycler(int bbCount, int cbCount) { - _byteBuffers = new byte[bbCount][]; - _charBuffers = new char[cbCount][]; - } - - /* - /********************************************************** - /* Public API, byte buffers - /********************************************************** - */ - - /** - * @param ix One of READ_IO_BUFFER constants. - */ - public final byte[] allocByteBuffer(int ix) { - return allocByteBuffer(ix, 0); - } - - public byte[] allocByteBuffer(int ix, int minSize) { - final int DEF_SIZE = byteBufferLength(ix); - if (minSize < DEF_SIZE) { - minSize = DEF_SIZE; - } - byte[] buffer = _byteBuffers[ix]; - if (buffer == null || buffer.length < minSize) { - buffer = balloc(minSize); - } else { - _byteBuffers[ix] = null; - } - return buffer; - } - - public final void releaseByteBuffer(int ix, byte[] buffer) { - _byteBuffers[ix] = buffer; - } - - /* - /********************************************************** - /* Public API, char buffers - /********************************************************** - */ - - public final char[] allocCharBuffer(int ix) { - return allocCharBuffer(ix, 0); - } - - public char[] allocCharBuffer(int ix, int minSize) { - final int DEF_SIZE = charBufferLength(ix); - if (minSize < DEF_SIZE) { - minSize = DEF_SIZE; - } - char[] buffer = _charBuffers[ix]; - if (buffer == null || buffer.length < minSize) { - buffer = calloc(minSize); - } else { - _charBuffers[ix] = null; - } - return buffer; - } - - public void releaseCharBuffer(int ix, char[] buffer) { - _charBuffers[ix] = buffer; - } - - /* - /********************************************************** - /* Overridable helper methods - /********************************************************** - */ - - protected int byteBufferLength(int ix) { - return BYTE_BUFFER_LENGTHS[ix]; - } - - protected int charBufferLength(int ix) { - return CHAR_BUFFER_LENGTHS[ix]; - } - - /* - /********************************************************** - /* Actual allocations separated for easier debugging/profiling - /********************************************************** - */ - - protected byte[] balloc(int size) { return new byte[size]; } - protected char[] calloc(int size) { return new char[size]; } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/ByteArrayBuilder.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/ByteArrayBuilder.java deleted file mode 100644 index 72bee125..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/ByteArrayBuilder.java +++ /dev/null @@ -1,244 +0,0 @@ -/* Jackson JSON-processor. - * - * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi - */ - -package autosaveworld.zlibs.com.fasterxml.jackson.core.util; - -import java.io.OutputStream; -import java.util.LinkedList; - -/** - * Helper class that is similar to {@link java.io.ByteArrayOutputStream} - * in usage, but more geared to Jackson use cases internally. - * Specific changes include segment storage (no need to have linear - * backing buffer, can avoid reallocations, copying), as well API - * not based on {@link java.io.OutputStream}. In short, a very much - * specialized builder object. - *

- * Also implements {@link OutputStream} to allow - * efficient aggregation of output content as a byte array, similar - * to how {@link java.io.ByteArrayOutputStream} works, but somewhat more - * efficiently for many use cases. - */ -public final class ByteArrayBuilder extends OutputStream -{ - public final static byte[] NO_BYTES = new byte[0]; - - // Size of the first block we will allocate. - private final static int INITIAL_BLOCK_SIZE = 500; - - // Maximum block size we will use for individual non-aggregated - // blocks. Let's limit to using 256k chunks. - private final static int MAX_BLOCK_SIZE = (1 << 18); - - final static int DEFAULT_BLOCK_ARRAY_SIZE = 40; - - // Optional buffer recycler instance that we can use for allocating the first block. - private final BufferRecycler _bufferRecycler; - private final LinkedList _pastBlocks = new LinkedList(); - - // Number of bytes within byte arrays in {@link _pastBlocks}. - private int _pastLen; - private byte[] _currBlock; - private int _currBlockPtr; - - public ByteArrayBuilder() { this(null); } - public ByteArrayBuilder(BufferRecycler br) { this(br, INITIAL_BLOCK_SIZE); } - public ByteArrayBuilder(int firstBlockSize) { this(null, firstBlockSize); } - - public ByteArrayBuilder(BufferRecycler br, int firstBlockSize) { - _bufferRecycler = br; - _currBlock = (br == null) ? new byte[firstBlockSize] : br.allocByteBuffer(BufferRecycler.BYTE_WRITE_CONCAT_BUFFER); - } - - public void reset() { - _pastLen = 0; - _currBlockPtr = 0; - - if (!_pastBlocks.isEmpty()) { - _pastBlocks.clear(); - } - } - - /** - * Clean up method to call to release all buffers this object may be - * using. After calling the method, no other accessors can be used (and - * attempt to do so may result in an exception) - */ - public void release() { - reset(); - if (_bufferRecycler != null && _currBlock != null) { - _bufferRecycler.releaseByteBuffer(BufferRecycler.BYTE_WRITE_CONCAT_BUFFER, _currBlock); - _currBlock = null; - } - } - - public void append(int i) { - if (_currBlockPtr >= _currBlock.length) { - _allocMore(); - } - _currBlock[_currBlockPtr++] = (byte) i; - } - - public void appendTwoBytes(int b16) { - if ((_currBlockPtr + 1) < _currBlock.length) { - _currBlock[_currBlockPtr++] = (byte) (b16 >> 8); - _currBlock[_currBlockPtr++] = (byte) b16; - } else { - append(b16 >> 8); - append(b16); - } - } - - public void appendThreeBytes(int b24) { - if ((_currBlockPtr + 2) < _currBlock.length) { - _currBlock[_currBlockPtr++] = (byte) (b24 >> 16); - _currBlock[_currBlockPtr++] = (byte) (b24 >> 8); - _currBlock[_currBlockPtr++] = (byte) b24; - } else { - append(b24 >> 16); - append(b24 >> 8); - append(b24); - } - } - - /** - * Method called when results are finalized and we can get the - * full aggregated result buffer to return to the caller - */ - public byte[] toByteArray() - { - int totalLen = _pastLen + _currBlockPtr; - - if (totalLen == 0) { // quick check: nothing aggregated? - return NO_BYTES; - } - - byte[] result = new byte[totalLen]; - int offset = 0; - - for (byte[] block : _pastBlocks) { - int len = block.length; - System.arraycopy(block, 0, result, offset, len); - offset += len; - } - System.arraycopy(_currBlock, 0, result, offset, _currBlockPtr); - offset += _currBlockPtr; - if (offset != totalLen) { // just a sanity check - throw new RuntimeException("Internal error: total len assumed to be "+totalLen+", copied "+offset+" bytes"); - } - // Let's only reset if there's sizable use, otherwise will get reset later on - if (!_pastBlocks.isEmpty()) { - reset(); - } - return result; - } - - /* - /********************************************************** - /* Non-stream API (similar to TextBuffer), since 1.6 - /********************************************************** - */ - - /** - * Method called when starting "manual" output: will clear out - * current state and return the first segment buffer to fill - */ - public byte[] resetAndGetFirstSegment() { - reset(); - return _currBlock; - } - - /** - * Method called when the current segment buffer is full; will - * append to current contents, allocate a new segment buffer - * and return it - */ - public byte[] finishCurrentSegment() { - _allocMore(); - return _currBlock; - } - - /** - * Method that will complete "manual" output process, coalesce - * content (if necessary) and return results as a contiguous buffer. - * - * @param lastBlockLength Amount of content in the current segment - * buffer. - * - * @return Coalesced contents - */ - public byte[] completeAndCoalesce(int lastBlockLength) { - _currBlockPtr = lastBlockLength; - return toByteArray(); - } - - public byte[] getCurrentSegment() { return _currBlock; } - public void setCurrentSegmentLength(int len) { _currBlockPtr = len; } - public int getCurrentSegmentLength() { return _currBlockPtr; } - - /* - /********************************************************** - /* OutputStream implementation - /********************************************************** - */ - - @Override - public void write(byte[] b) { - write(b, 0, b.length); - } - - @Override - public void write(byte[] b, int off, int len) - { - while (true) { - int max = _currBlock.length - _currBlockPtr; - int toCopy = Math.min(max, len); - if (toCopy > 0) { - System.arraycopy(b, off, _currBlock, _currBlockPtr, toCopy); - off += toCopy; - _currBlockPtr += toCopy; - len -= toCopy; - } - if (len <= 0) break; - _allocMore(); - } - } - - @Override - public void write(int b) { - append(b); - } - - @Override public void close() { /* NOP */ } - @Override public void flush() { /* NOP */ } - - /* - /********************************************************** - /* Internal methods - /********************************************************** - */ - - private void _allocMore() - { - _pastLen += _currBlock.length; - - /* Let's allocate block that's half the total size, except - * never smaller than twice the initial block size. - * The idea is just to grow with reasonable rate, to optimize - * between minimal number of chunks and minimal amount of - * wasted space. - */ - int newSize = Math.max((_pastLen >> 1), (INITIAL_BLOCK_SIZE + INITIAL_BLOCK_SIZE)); - // plus not to exceed max we define... - if (newSize > MAX_BLOCK_SIZE) { - newSize = MAX_BLOCK_SIZE; - } - _pastBlocks.add(_currBlock); - _currBlock = new byte[newSize]; - _currBlockPtr = 0; - } - -} - diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/DefaultIndenter.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/DefaultIndenter.java deleted file mode 100644 index 5bd438fd..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/DefaultIndenter.java +++ /dev/null @@ -1,105 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.util; - -import java.io.IOException; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; - -/** - * Default linefeed-based indenter, used by {@link DefaultPrettyPrinter} (unless - * overridden). Uses system-specific linefeeds and 2 spaces for indentation per level. - * - * @since 2.5 - */ -public class DefaultIndenter - extends DefaultPrettyPrinter.NopIndenter -{ - private static final long serialVersionUID = 1L; - - public final static String SYS_LF; - static { - String lf; - try { - lf = System.getProperty("line.separator"); - } catch (Throwable t) { - lf = "\n"; // fallback when security manager denies access - } - SYS_LF = lf; - } - - public static final DefaultIndenter SYSTEM_LINEFEED_INSTANCE = new DefaultIndenter(" ", SYS_LF); - - /** - * We expect to rarely get indentation deeper than this number of levels, - * and try not to pre-generate more indentations than needed. - */ - private final static int INDENT_LEVELS = 16; - private final char[] indents; - private final int charsPerLevel; - private final String eol; - - /** - * Indent with two spaces and the system's default line feed - */ - public DefaultIndenter() { - this(" ", SYS_LF); - } - - /** - * Create an indenter which uses the indent string to indent one level - * and the eol string to separate lines. - */ - public DefaultIndenter(String indent, String eol) - { - charsPerLevel = indent.length(); - - indents = new char[indent.length() * INDENT_LEVELS]; - int offset = 0; - for (int i=0; i 0) { // should we err on negative values (as there's some flaw?) - level *= charsPerLevel; - while (level > indents.length) { // unlike to happen but just in case - jg.writeRaw(indents, 0, indents.length); - level -= indents.length; - } - jg.writeRaw(indents, 0, level); - } - } - - public String getEol() { - return eol; - } - - public String getIndent() { - return new String(indents, 0, charsPerLevel); - } -} \ No newline at end of file diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/DefaultPrettyPrinter.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/DefaultPrettyPrinter.java deleted file mode 100644 index ba9761b0..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/DefaultPrettyPrinter.java +++ /dev/null @@ -1,404 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.util; - -import java.io.IOException; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.PrettyPrinter; -import autosaveworld.zlibs.com.fasterxml.jackson.core.SerializableString; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.SerializedString; - -/** - * Default {@link PrettyPrinter} implementation that uses 2-space - * indentation with platform-default linefeeds. - * Usually this class is not instantiated directly, but instead - * method {@link JsonGenerator#useDefaultPrettyPrinter} is - * used, which will use an instance of this class for operation. - */ -@SuppressWarnings("serial") -public class DefaultPrettyPrinter - implements PrettyPrinter, Instantiatable, - java.io.Serializable -{ - private static final long serialVersionUID = 1; - - /** - * Constant that specifies default "root-level" separator to use between - * root values: a single space character. - * - * @since 2.1 - */ - public final static SerializedString DEFAULT_ROOT_VALUE_SEPARATOR = new SerializedString(" "); - - /** - * Interface that defines objects that can produce indentation used - * to separate object entries and array values. Indentation in this - * context just means insertion of white space, independent of whether - * linefeeds are output. - */ - public interface Indenter - { - void writeIndentation(JsonGenerator jg, int level) throws IOException; - - /** - * @return True if indenter is considered inline (does not add linefeeds), - * false otherwise - */ - boolean isInline(); - } - - // // // Config, indentation - - /** - * By default, let's use only spaces to separate array values. - */ - protected Indenter _arrayIndenter = FixedSpaceIndenter.instance; - - /** - * By default, let's use linefeed-adding indenter for separate - * object entries. We'll further configure indenter to use - * system-specific linefeeds, and 2 spaces per level (as opposed to, - * say, single tabs) - */ - protected Indenter _objectIndenter = DefaultIndenter.SYSTEM_LINEFEED_INSTANCE; - - /** - * String printed between root-level values, if any. - */ - protected final SerializableString _rootSeparator; - - // // // Config, other white space configuration - - /** - * By default we will add spaces around colons used to - * separate object fields and values. - * If disabled, will not use spaces around colon. - */ - protected boolean _spacesInObjectEntries = true; - - // // // State: - - /** - * Number of open levels of nesting. Used to determine amount of - * indentation to use. - */ - protected transient int _nesting; - - /* - /********************************************************** - /* Life-cycle (construct, configure) - /********************************************************** - */ - - public DefaultPrettyPrinter() { - this(DEFAULT_ROOT_VALUE_SEPARATOR); - } - - /** - * Constructor that specifies separator String to use between root values; - * if null, no separator is printed. - *

- * Note: simply constructs a {@link SerializedString} out of parameter, - * calls {@link #DefaultPrettyPrinter(SerializableString)} - * - * @param rootSeparator - * - * @since 2.1 - */ - public DefaultPrettyPrinter(String rootSeparator) { - this((rootSeparator == null) ? null : new SerializedString(rootSeparator)); - } - - /** - * Constructor that specifies separator String to use between root values; - * if null, no separator is printed. - * - * @param rootSeparator - * - * @since 2.1 - */ - public DefaultPrettyPrinter(SerializableString rootSeparator) { - _rootSeparator = rootSeparator; - } - - public DefaultPrettyPrinter(DefaultPrettyPrinter base) { - this(base, base._rootSeparator); - } - - public DefaultPrettyPrinter(DefaultPrettyPrinter base, - SerializableString rootSeparator) - { - _arrayIndenter = base._arrayIndenter; - _objectIndenter = base._objectIndenter; - _spacesInObjectEntries = base._spacesInObjectEntries; - _nesting = base._nesting; - - _rootSeparator = rootSeparator; - } - - public DefaultPrettyPrinter withRootSeparator(SerializableString rootSeparator) - { - if (_rootSeparator == rootSeparator || - (rootSeparator != null && rootSeparator.equals(_rootSeparator))) { - return this; - } - return new DefaultPrettyPrinter(this, rootSeparator); - } - - /** - * @since 2.6.0 - */ - public DefaultPrettyPrinter withRootSeparator(String rootSeparator) { - return withRootSeparator((rootSeparator == null) ? null : new SerializedString(rootSeparator)); - } - - public void indentArraysWith(Indenter i) { - _arrayIndenter = (i == null) ? NopIndenter.instance : i; - } - - public void indentObjectsWith(Indenter i) { - _objectIndenter = (i == null) ? NopIndenter.instance : i; - } - - /** - * @deprecated Since 2.3 use {@link #withSpacesInObjectEntries} and {@link #withoutSpacesInObjectEntries()} - */ - @Deprecated - public void spacesInObjectEntries(boolean b) { _spacesInObjectEntries = b; } - - /** - * @since 2.3 - */ - public DefaultPrettyPrinter withArrayIndenter(Indenter i) { - if (i == null) { - i = NopIndenter.instance; - } - if (_arrayIndenter == i) { - return this; - } - DefaultPrettyPrinter pp = new DefaultPrettyPrinter(this); - pp._arrayIndenter = i; - return pp; - } - - /** - * @since 2.3 - */ - public DefaultPrettyPrinter withObjectIndenter(Indenter i) { - if (i == null) { - i = NopIndenter.instance; - } - if (_objectIndenter == i) { - return this; - } - DefaultPrettyPrinter pp = new DefaultPrettyPrinter(this); - pp._objectIndenter = i; - return pp; - } - - /** - * "Mutant factory" method that will return a pretty printer instance - * that does use spaces inside object entries; if 'this' instance already - * does this, it is returned; if not, a new instance will be constructed - * and returned. - * - * @since 2.3 - */ - public DefaultPrettyPrinter withSpacesInObjectEntries() { - return _withSpaces(true); - } - - /** - * "Mutant factory" method that will return a pretty printer instance - * that does not use spaces inside object entries; if 'this' instance already - * does this, it is returned; if not, a new instance will be constructed - * and returned. - * - * @since 2.3 - */ - public DefaultPrettyPrinter withoutSpacesInObjectEntries() { - return _withSpaces(false); - } - - protected DefaultPrettyPrinter _withSpaces(boolean state) - { - if (_spacesInObjectEntries == state) { - return this; - } - DefaultPrettyPrinter pp = new DefaultPrettyPrinter(this); - pp._spacesInObjectEntries = state; - return pp; - } - - /* - /********************************************************** - /* Instantiatable impl - /********************************************************** - */ - - @Override - public DefaultPrettyPrinter createInstance() { - return new DefaultPrettyPrinter(this); - } - - /* - /********************************************************** - /* PrettyPrinter impl - /********************************************************** - */ - - @Override - public void writeRootValueSeparator(JsonGenerator jg) throws IOException - { - if (_rootSeparator != null) { - jg.writeRaw(_rootSeparator); - } - } - - @Override - public void writeStartObject(JsonGenerator jg) throws IOException - { - jg.writeRaw('{'); - if (!_objectIndenter.isInline()) { - ++_nesting; - } - } - - @Override - public void beforeObjectEntries(JsonGenerator jg) throws IOException - { - _objectIndenter.writeIndentation(jg, _nesting); - } - - /** - * Method called after an object field has been output, but - * before the value is output. - *

- * Default handling (without pretty-printing) will output a single - * colon to separate the two. Pretty-printer is - * to output a colon as well, but can surround that with other - * (white-space) decoration. - */ - @Override - public void writeObjectFieldValueSeparator(JsonGenerator jg) throws IOException - { - if (_spacesInObjectEntries) { - jg.writeRaw(" : "); - } else { - jg.writeRaw(':'); - } - } - - /** - * Method called after an object entry (field:value) has been completely - * output, and before another value is to be output. - *

- * Default handling (without pretty-printing) will output a single - * comma to separate the two. Pretty-printer is - * to output a comma as well, but can surround that with other - * (white-space) decoration. - */ - @Override - public void writeObjectEntrySeparator(JsonGenerator jg) throws IOException - { - jg.writeRaw(','); - _objectIndenter.writeIndentation(jg, _nesting); - } - - @Override - public void writeEndObject(JsonGenerator jg, int nrOfEntries) throws IOException - { - if (!_objectIndenter.isInline()) { - --_nesting; - } - if (nrOfEntries > 0) { - _objectIndenter.writeIndentation(jg, _nesting); - } else { - jg.writeRaw(' '); - } - jg.writeRaw('}'); - } - - @Override - public void writeStartArray(JsonGenerator jg) throws IOException - { - if (!_arrayIndenter.isInline()) { - ++_nesting; - } - jg.writeRaw('['); - } - - @Override - public void beforeArrayValues(JsonGenerator jg) throws IOException { - _arrayIndenter.writeIndentation(jg, _nesting); - } - - /** - * Method called after an array value has been completely - * output, and before another value is to be output. - *

- * Default handling (without pretty-printing) will output a single - * comma to separate the two. Pretty-printer is - * to output a comma as well, but can surround that with other - * (white-space) decoration. - */ - @Override - public void writeArrayValueSeparator(JsonGenerator gen) throws IOException - { - gen.writeRaw(','); - _arrayIndenter.writeIndentation(gen, _nesting); - } - - @Override - public void writeEndArray(JsonGenerator gen, int nrOfValues) throws IOException - { - if (!_arrayIndenter.isInline()) { - --_nesting; - } - if (nrOfValues > 0) { - _arrayIndenter.writeIndentation(gen, _nesting); - } else { - gen.writeRaw(' '); - } - gen.writeRaw(']'); - } - - /* - /********************************************************** - /* Helper classes - /********************************************************** - */ - - /** - * Dummy implementation that adds no indentation whatsoever - */ - public static class NopIndenter - implements Indenter, java.io.Serializable - { - public static final NopIndenter instance = new NopIndenter(); - - @Override - public void writeIndentation(JsonGenerator jg, int level) throws IOException { } - - @Override - public boolean isInline() { return true; } - } - - /** - * This is a very simple indenter that only adds a - * single space for indentation. It is used as the default - * indenter for array values. - */ - public static class FixedSpaceIndenter extends NopIndenter - { - public static final FixedSpaceIndenter instance = new FixedSpaceIndenter(); - - @Override - public void writeIndentation(JsonGenerator jg, int level) throws IOException - { - jg.writeRaw(' '); - } - - @Override - public boolean isInline() { return true; } - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/Instantiatable.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/Instantiatable.java deleted file mode 100644 index 24f86b85..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/Instantiatable.java +++ /dev/null @@ -1,24 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.util; - -/** - * Add-on interface used to indicate things that may be "blueprint" objects - * which can not be used as is, but are used for creating usable per-process - * (serialization, deserialization) instances, using - * {@link #createInstance} method. - *

- * Note that some implementations may choose to implement {@link #createInstance} - * by simply returning 'this': this is acceptable if instances are stateless. - * - * @see DefaultPrettyPrinter - * - * @since 2.1 - */ -public interface Instantiatable -{ - /** - * Method called to ensure that we have a non-blueprint object to use; - * it is either this object (if stateless), or a newly created object - * with separate state. - */ - T createInstance(); -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/InternCache.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/InternCache.java deleted file mode 100644 index fb05b008..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/InternCache.java +++ /dev/null @@ -1,65 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.util; - -import java.util.LinkedHashMap; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Singleton class that adds a simple first-level cache in front of - * regular String.intern() functionality. This is done as a minor - * performance optimization, to avoid calling native intern() method - * in cases where same String is being interned multiple times. - *

- * Note: that this class extends {@link LinkedHashMap} is an implementation - * detail -- no code should ever directly call Map methods. - */ -public final class InternCache - extends ConcurrentHashMap // since 2.3 -{ - private static final long serialVersionUID = 1L; - - /** - * Size to use is somewhat arbitrary, so let's choose something that's - * neither too small (low hit ratio) nor too large (waste of memory). - *

- * One consideration is possible attack via colliding {@link String#hashCode}; - * because of this, limit to reasonably low setting. - */ - private final static int MAX_ENTRIES = 180; - - public final static InternCache instance = new InternCache(); - - /** - * As minor optimization let's try to avoid "flush storms", - * cases where multiple threads might try to concurrently - * flush the map. - */ - private final Object lock = new Object(); - - private InternCache() { super(MAX_ENTRIES, 0.8f, 4); } - - public String intern(String input) { - String result = get(input); - if (result != null) { return result; } - - /* 18-Sep-2013, tatu: We used to use LinkedHashMap, which has simple LRU - * method. No such functionality exists with CHM; and let's use simplest - * possible limitation: just clear all contents. This because otherwise - * we are simply likely to keep on clearing same, commonly used entries. - */ - if (size() >= MAX_ENTRIES) { - /* Not incorrect wrt well-known double-locking anti-pattern because underlying - * storage gives close enough answer to real one here; and we are - * more concerned with flooding than starvation. - */ - synchronized (lock) { - if (size() >= MAX_ENTRIES) { - clear(); - } - } - } - result = input.intern(); - put(result, result); - return result; - } -} - diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/JsonGeneratorDelegate.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/JsonGeneratorDelegate.java deleted file mode 100644 index ff341b5a..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/JsonGeneratorDelegate.java +++ /dev/null @@ -1,461 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.util; - -import java.io.IOException; -import java.io.InputStream; -import java.math.BigDecimal; -import java.math.BigInteger; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.Base64Variant; -import autosaveworld.zlibs.com.fasterxml.jackson.core.FormatSchema; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonStreamContext; -import autosaveworld.zlibs.com.fasterxml.jackson.core.ObjectCodec; -import autosaveworld.zlibs.com.fasterxml.jackson.core.PrettyPrinter; -import autosaveworld.zlibs.com.fasterxml.jackson.core.SerializableString; -import autosaveworld.zlibs.com.fasterxml.jackson.core.TreeNode; -import autosaveworld.zlibs.com.fasterxml.jackson.core.Version; -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.CharacterEscapes; - -public class JsonGeneratorDelegate extends JsonGenerator -{ - /** - * Delegate object that method calls are delegated to. - */ - protected JsonGenerator delegate; - - /** - * Whether copy methods - * ({@link #copyCurrentEvent}, {@link #copyCurrentStructure}, {@link #writeTree} and {@link #writeObject}) - * are to be called (true), or handled by this object (false). - */ - protected boolean delegateCopyMethods; - - /* - /********************************************************** - /* Construction, initialization - /********************************************************** - */ - - public JsonGeneratorDelegate(JsonGenerator d) { - this(d, true); - } - - /** - * @param delegateCopyMethods Flag assigned to delagateCopyMethod - * and which defines whether copy methods are handled locally (false), or - * delegated to configured - */ - public JsonGeneratorDelegate(JsonGenerator d, boolean delegateCopyMethods) { - delegate = d; - this.delegateCopyMethods = delegateCopyMethods; - } - - @Override - public Object getCurrentValue() { - return delegate.getCurrentValue(); - } - - @Override - public void setCurrentValue(Object v) { - delegate.setCurrentValue(v); - } - - /* - /********************************************************** - /* Extended API - /********************************************************** - */ - - public JsonGenerator getDelegate() { return delegate; } - - /* - /********************************************************** - /* Public API, metadata - /********************************************************** - */ - - @Override public ObjectCodec getCodec() { return delegate.getCodec(); } - - @Override public JsonGenerator setCodec(ObjectCodec oc) { - delegate.setCodec(oc); - return this; - } - - @Override public void setSchema(FormatSchema schema) { delegate.setSchema(schema); } - @Override public FormatSchema getSchema() { return delegate.getSchema(); } - @Override public Version version() { return delegate.version(); } - @Override public Object getOutputTarget() { return delegate.getOutputTarget(); } - @Override public int getOutputBuffered() { return delegate.getOutputBuffered(); } - - /* - /********************************************************** - /* Public API, capability introspection (since 2.3, mostly) - /********************************************************** - */ - - @Override - public boolean canUseSchema(FormatSchema schema) { return delegate.canUseSchema(schema); } - - @Override - public boolean canWriteTypeId() { return delegate.canWriteTypeId(); } - - @Override - public boolean canWriteObjectId() { return delegate.canWriteObjectId(); } - - @Override - public boolean canWriteBinaryNatively() { return delegate.canWriteBinaryNatively(); } - - @Override - public boolean canOmitFields() { return delegate.canOmitFields(); } - - /* - /********************************************************** - /* Public API, configuration - /********************************************************** - */ - - @Override - public JsonGenerator enable(Feature f) { - delegate.enable(f); - return this; - } - - @Override - public JsonGenerator disable(Feature f) { - delegate.disable(f); - return this; - } - - @Override - public boolean isEnabled(Feature f) { return delegate.isEnabled(f); } - - // final, can't override (and no need to) - //public final JsonGenerator configure(Feature f, boolean state) - - @Override - public int getFeatureMask() { return delegate.getFeatureMask(); } - - @Override - @Deprecated - public JsonGenerator setFeatureMask(int mask) { - delegate.setFeatureMask(mask); - return this; - } - - @Override - public JsonGenerator overrideStdFeatures(int values, int mask) { - delegate.overrideStdFeatures(values, mask); - return this; - } - - @Override - public JsonGenerator overrideFormatFeatures(int values, int mask) { - delegate.overrideFormatFeatures(values, mask); - return this; - } - - /* - /********************************************************** - /* Configuring generator - /********************************************************** - */ - - @Override - public JsonGenerator setPrettyPrinter(PrettyPrinter pp) { - delegate.setPrettyPrinter(pp); - return this; - } - - @Override - public PrettyPrinter getPrettyPrinter() { return delegate.getPrettyPrinter(); } - - @Override - public JsonGenerator useDefaultPrettyPrinter() { delegate.useDefaultPrettyPrinter(); - return this; } - - @Override - public JsonGenerator setHighestNonEscapedChar(int charCode) { delegate.setHighestNonEscapedChar(charCode); - return this; } - - @Override - public int getHighestEscapedChar() { return delegate.getHighestEscapedChar(); } - - @Override - public CharacterEscapes getCharacterEscapes() { return delegate.getCharacterEscapes(); } - - @Override - public JsonGenerator setCharacterEscapes(CharacterEscapes esc) { delegate.setCharacterEscapes(esc); - return this; } - - @Override - public JsonGenerator setRootValueSeparator(SerializableString sep) { delegate.setRootValueSeparator(sep); - return this; } - - /* - /********************************************************** - /* Public API, write methods, structural - /********************************************************** - */ - - @Override - public void writeStartArray() throws IOException { delegate.writeStartArray(); } - - @Override - public void writeStartArray(int size) throws IOException { delegate.writeStartArray(size); } - - @Override - public void writeEndArray() throws IOException { delegate.writeEndArray(); } - - @Override - public void writeStartObject() throws IOException { delegate.writeStartObject(); } - - @Override - public void writeStartObject(Object forValue) throws IOException { delegate.writeStartObject(forValue); } - - @Override - public void writeEndObject() throws IOException { delegate.writeEndObject(); } - - @Override - public void writeFieldName(String name) throws IOException { - delegate.writeFieldName(name); - } - - @Override - public void writeFieldName(SerializableString name) throws IOException { - delegate.writeFieldName(name); - } - - @Override - public void writeFieldId(long id) throws IOException { - delegate.writeFieldId(id); - } - - @Override - public void writeArray(int[] array, int offset, int length) throws IOException { - delegate.writeArray(array, offset, length); - } - - @Override - public void writeArray(long[] array, int offset, int length) throws IOException { - delegate.writeArray(array, offset, length); - } - - @Override - public void writeArray(double[] array, int offset, int length) throws IOException { - delegate.writeArray(array, offset, length); - } - - /* - /********************************************************** - /* Public API, write methods, text/String values - /********************************************************** - */ - - @Override - public void writeString(String text) throws IOException { delegate.writeString(text); } - - @Override - public void writeString(char[] text, int offset, int len) throws IOException { delegate.writeString(text, offset, len); } - - @Override - public void writeString(SerializableString text) throws IOException { delegate.writeString(text); } - - @Override - public void writeRawUTF8String(byte[] text, int offset, int length) throws IOException { delegate.writeRawUTF8String(text, offset, length); } - - @Override - public void writeUTF8String(byte[] text, int offset, int length) throws IOException { delegate.writeUTF8String(text, offset, length); } - - /* - /********************************************************** - /* Public API, write methods, binary/raw content - /********************************************************** - */ - - @Override - public void writeRaw(String text) throws IOException { delegate.writeRaw(text); } - - @Override - public void writeRaw(String text, int offset, int len) throws IOException { delegate.writeRaw(text, offset, len); } - - @Override - public void writeRaw(SerializableString raw) throws IOException { delegate.writeRaw(raw); } - - @Override - public void writeRaw(char[] text, int offset, int len) throws IOException { delegate.writeRaw(text, offset, len); } - - @Override - public void writeRaw(char c) throws IOException { delegate.writeRaw(c); } - - @Override - public void writeRawValue(String text) throws IOException { delegate.writeRawValue(text); } - - @Override - public void writeRawValue(String text, int offset, int len) throws IOException { delegate.writeRawValue(text, offset, len); } - - @Override - public void writeRawValue(char[] text, int offset, int len) throws IOException { delegate.writeRawValue(text, offset, len); } - - @Override - public void writeBinary(Base64Variant b64variant, byte[] data, int offset, int len) throws IOException { delegate.writeBinary(b64variant, data, offset, len); } - - @Override - public int writeBinary(Base64Variant b64variant, InputStream data, int dataLength) throws IOException { return delegate.writeBinary(b64variant, data, dataLength); } - - /* - /********************************************************** - /* Public API, write methods, other value types - /********************************************************** - */ - - @Override - public void writeNumber(short v) throws IOException { delegate.writeNumber(v); } - - @Override - public void writeNumber(int v) throws IOException { delegate.writeNumber(v); } - - @Override - public void writeNumber(long v) throws IOException { delegate.writeNumber(v); } - - @Override - public void writeNumber(BigInteger v) throws IOException { delegate.writeNumber(v); } - - @Override - public void writeNumber(double v) throws IOException { delegate.writeNumber(v); } - - @Override - public void writeNumber(float v) throws IOException { delegate.writeNumber(v); } - - @Override - public void writeNumber(BigDecimal v) throws IOException { delegate.writeNumber(v); } - - @Override - public void writeNumber(String encodedValue) throws IOException, UnsupportedOperationException { delegate.writeNumber(encodedValue); } - - @Override - public void writeBoolean(boolean state) throws IOException { delegate.writeBoolean(state); } - - @Override - public void writeNull() throws IOException { delegate.writeNull(); } - - /* - /********************************************************** - /* Overridden field methods - /********************************************************** - */ - - @Override - public void writeOmittedField(String fieldName) throws IOException { delegate.writeOmittedField(fieldName); } - - /* - /********************************************************** - /* Public API, write methods, Native Ids - /********************************************************** - */ - - @Override - public void writeObjectId(Object id) throws IOException { delegate.writeObjectId(id); } - - @Override - public void writeObjectRef(Object id) throws IOException { delegate.writeObjectRef(id); } - - @Override - public void writeTypeId(Object id) throws IOException { delegate.writeTypeId(id); } - - @Override - public void writeEmbeddedObject(Object object) throws IOException { delegate.writeEmbeddedObject(object); } - - /* - /********************************************************** - /* Public API, write methods, serializing Java objects - /********************************************************** - */ - - @Override - public void writeObject(Object pojo) throws IOException { - if (delegateCopyMethods) { - delegate.writeObject(pojo); - return; - } - if (pojo == null) { - writeNull(); - } else { - ObjectCodec c = getCodec(); - if (c != null) { - c.writeValue(this, pojo); - return; - } - _writeSimpleObject(pojo); - } - } - - @Override - public void writeTree(TreeNode tree) throws IOException { - if (delegateCopyMethods) { - delegate.writeTree(tree); - return; - } - // As with 'writeObject()', we are not check if write would work - if (tree == null) { - writeNull(); - } else { - ObjectCodec c = getCodec(); - if (c == null) { - throw new IllegalStateException("No ObjectCodec defined"); - } - c.writeTree(this, tree); - } - } - - /* - /********************************************************** - /* Public API, convenience field write methods - /********************************************************** - */ - - // // These are fine, just delegate to other methods... - - /* - /********************************************************** - /* Public API, copy-through methods - /********************************************************** - */ - - @Override - public void copyCurrentEvent(JsonParser p) throws IOException { - if (delegateCopyMethods) delegate.copyCurrentEvent(p); - else super.copyCurrentEvent(p); - } - - @Override - public void copyCurrentStructure(JsonParser p) throws IOException { - if (delegateCopyMethods) delegate.copyCurrentStructure(p); - else super.copyCurrentStructure(p); - } - - /* - /********************************************************** - /* Public API, context access - /********************************************************** - */ - - @Override public JsonStreamContext getOutputContext() { return delegate.getOutputContext(); } - - /* - /********************************************************** - /* Public API, buffer handling - /********************************************************** - */ - - @Override public void flush() throws IOException { delegate.flush(); } - @Override public void close() throws IOException { delegate.close(); } - - /* - /********************************************************** - /* Closeable implementation - /********************************************************** - */ - - @Override public boolean isClosed() { return delegate.isClosed(); } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/JsonParserDelegate.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/JsonParserDelegate.java deleted file mode 100644 index bd36203e..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/JsonParserDelegate.java +++ /dev/null @@ -1,244 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.util; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.Writer; -import java.math.BigDecimal; -import java.math.BigInteger; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.Base64Variant; -import autosaveworld.zlibs.com.fasterxml.jackson.core.FormatSchema; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonLocation; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonStreamContext; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; -import autosaveworld.zlibs.com.fasterxml.jackson.core.ObjectCodec; -import autosaveworld.zlibs.com.fasterxml.jackson.core.Version; - -/** - * Helper class that implements - * delegation pattern for {@link JsonParser}, - * to allow for simple overridability of basic parsing functionality. - * The idea is that any functionality to be modified can be simply - * overridden; and anything else will be delegated by default. - */ -public class JsonParserDelegate extends JsonParser -{ - /** - * Delegate object that method calls are delegated to. - */ - protected JsonParser delegate; - - public JsonParserDelegate(JsonParser d) { - delegate = d; - } - - @Override - public Object getCurrentValue() { - return delegate.getCurrentValue(); - } - - @Override - public void setCurrentValue(Object v) { - delegate.setCurrentValue(v); - } - - /* - /********************************************************** - /* Public API, configuration - /********************************************************** - */ - - @Override public void setCodec(ObjectCodec c) { delegate.setCodec(c); } - @Override public ObjectCodec getCodec() { return delegate.getCodec(); } - - @Override - public JsonParser enable(Feature f) { - delegate.enable(f); - return this; - } - - @Override - public JsonParser disable(Feature f) { - delegate.disable(f); - return this; - } - - @Override public boolean isEnabled(Feature f) { return delegate.isEnabled(f); } - @Override public int getFeatureMask() { return delegate.getFeatureMask(); } - - @Override - @Deprecated // since 2.7 - public JsonParser setFeatureMask(int mask) { - delegate.setFeatureMask(mask); - return this; - } - - @Override - public JsonParser overrideStdFeatures(int values, int mask) { - delegate.overrideStdFeatures(values, mask); - return this; - } - - @Override - public JsonParser overrideFormatFeatures(int values, int mask) { - delegate.overrideFormatFeatures(values, mask); - return this; - } - - @Override public FormatSchema getSchema() { return delegate.getSchema(); } - @Override public void setSchema(FormatSchema schema) { delegate.setSchema(schema); } - @Override public boolean canUseSchema(FormatSchema schema) { return delegate.canUseSchema(schema); } - @Override public Version version() { return delegate.version(); } - @Override public Object getInputSource() { return delegate.getInputSource(); } - - /* - /********************************************************** - /* Capability introspection - /********************************************************** - */ - - @Override public boolean requiresCustomCodec() { return delegate.requiresCustomCodec(); } - - /* - /********************************************************** - /* Closeable impl - /********************************************************** - */ - - @Override public void close() throws IOException { delegate.close(); } - @Override public boolean isClosed() { return delegate.isClosed(); } - - /* - /********************************************************** - /* Public API, token accessors - /********************************************************** - */ - - @Override public JsonToken currentToken() { return delegate.currentToken(); } - @Override public int currentTokenId() { return delegate.currentTokenId(); } - - @Override public JsonToken getCurrentToken() { return delegate.getCurrentToken(); } - @Override public int getCurrentTokenId() { return delegate.getCurrentTokenId(); } - @Override public boolean hasCurrentToken() { return delegate.hasCurrentToken(); } - @Override public boolean hasTokenId(int id) { return delegate.hasTokenId(id); } - @Override public boolean hasToken(JsonToken t) { return delegate.hasToken(t); } - - @Override public String getCurrentName() throws IOException { return delegate.getCurrentName(); } - @Override public JsonLocation getCurrentLocation() { return delegate.getCurrentLocation(); } - @Override public JsonStreamContext getParsingContext() { return delegate.getParsingContext(); } - @Override public boolean isExpectedStartArrayToken() { return delegate.isExpectedStartArrayToken(); } - @Override public boolean isExpectedStartObjectToken() { return delegate.isExpectedStartObjectToken(); } - - /* - /********************************************************** - /* Public API, token state overrides - /********************************************************** - */ - - @Override public void clearCurrentToken() { delegate.clearCurrentToken(); } - @Override public JsonToken getLastClearedToken() { return delegate.getLastClearedToken(); } - @Override public void overrideCurrentName(String name) { delegate.overrideCurrentName(name); } - - /* - /********************************************************** - /* Public API, access to token information, text - /********************************************************** - */ - - @Override public String getText() throws IOException { return delegate.getText(); } - @Override public boolean hasTextCharacters() { return delegate.hasTextCharacters(); } - @Override public char[] getTextCharacters() throws IOException { return delegate.getTextCharacters(); } - @Override public int getTextLength() throws IOException { return delegate.getTextLength(); } - @Override public int getTextOffset() throws IOException { return delegate.getTextOffset(); } - @Override public int getText(Writer writer) throws IOException, UnsupportedOperationException { return delegate.getText(writer); } - - /* - /********************************************************** - /* Public API, access to token information, numeric - /********************************************************** - */ - - @Override - public BigInteger getBigIntegerValue() throws IOException { return delegate.getBigIntegerValue(); } - - @Override - public boolean getBooleanValue() throws IOException { return delegate.getBooleanValue(); } - - @Override - public byte getByteValue() throws IOException { return delegate.getByteValue(); } - - @Override - public short getShortValue() throws IOException { return delegate.getShortValue(); } - - @Override - public BigDecimal getDecimalValue() throws IOException { return delegate.getDecimalValue(); } - - @Override - public double getDoubleValue() throws IOException { return delegate.getDoubleValue(); } - - @Override - public float getFloatValue() throws IOException { return delegate.getFloatValue(); } - - @Override - public int getIntValue() throws IOException { return delegate.getIntValue(); } - - @Override - public long getLongValue() throws IOException { return delegate.getLongValue(); } - - @Override - public NumberType getNumberType() throws IOException { return delegate.getNumberType(); } - - @Override - public Number getNumberValue() throws IOException { return delegate.getNumberValue(); } - - /* - /********************************************************** - /* Public API, access to token information, coercion/conversion - /********************************************************** - */ - - @Override public int getValueAsInt() throws IOException { return delegate.getValueAsInt(); } - @Override public int getValueAsInt(int defaultValue) throws IOException { return delegate.getValueAsInt(defaultValue); } - @Override public long getValueAsLong() throws IOException { return delegate.getValueAsLong(); } - @Override public long getValueAsLong(long defaultValue) throws IOException { return delegate.getValueAsLong(defaultValue); } - @Override public double getValueAsDouble() throws IOException { return delegate.getValueAsDouble(); } - @Override public double getValueAsDouble(double defaultValue) throws IOException { return delegate.getValueAsDouble(defaultValue); } - @Override public boolean getValueAsBoolean() throws IOException { return delegate.getValueAsBoolean(); } - @Override public boolean getValueAsBoolean(boolean defaultValue) throws IOException { return delegate.getValueAsBoolean(defaultValue); } - @Override public String getValueAsString() throws IOException { return delegate.getValueAsString(); } - @Override public String getValueAsString(String defaultValue) throws IOException { return delegate.getValueAsString(defaultValue); } - - /* - /********************************************************** - /* Public API, access to token values, other - /********************************************************** - */ - - @Override public Object getEmbeddedObject() throws IOException { return delegate.getEmbeddedObject(); } - @Override public byte[] getBinaryValue(Base64Variant b64variant) throws IOException { return delegate.getBinaryValue(b64variant); } - @Override public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws IOException { return delegate.readBinaryValue(b64variant, out); } - @Override public JsonLocation getTokenLocation() { return delegate.getTokenLocation(); } - @Override public JsonToken nextToken() throws IOException { return delegate.nextToken(); } - @Override public JsonToken nextValue() throws IOException { return delegate.nextValue(); } - - @Override public void finishToken() throws IOException { delegate.finishToken(); } - - @Override - public JsonParser skipChildren() throws IOException { - delegate.skipChildren(); - // NOTE: must NOT delegate this method to delegate, needs to be self-reference for chaining - return this; - } - - /* - /********************************************************** - /* Public API, Native Ids (type, object) - /********************************************************** - */ - - @Override public boolean canReadObjectId() { return delegate.canReadObjectId(); } - @Override public boolean canReadTypeId() { return delegate.canReadTypeId(); } - @Override public Object getObjectId() throws IOException { return delegate.getObjectId(); } - @Override public Object getTypeId() throws IOException { return delegate.getTypeId(); } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/JsonParserSequence.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/JsonParserSequence.java deleted file mode 100644 index 61212908..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/JsonParserSequence.java +++ /dev/null @@ -1,211 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.util; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken; - -/** - * Helper class that can be used to sequence multiple physical - * {@link JsonParser}s to create a single logical sequence of - * tokens, as a single {@link JsonParser}. - *

- * Fairly simple use of {@link JsonParserDelegate}: only need - * to override {@link #nextToken} to handle transition - */ -public class JsonParserSequence extends JsonParserDelegate -{ - /** - * Parsers other than the first one (which is initially assigned - * as delegate) - */ - protected final JsonParser[] _parsers; - - /** - * Configuration that determines whether state of parsers is first verified - * to see if parser already points to a token (that is, - * {@link JsonParser#hasCurrentToken()} returns true), and if so - * that token is first return before {@link JsonParser#nextToken} is called. - * If enabled, this check is made; if disabled, no check is made and - * {@link JsonParser#nextToken} is always called for all parsers. - *

- * Default setting is false (for backwards-compatibility) - * so that possible existing token is not considered for parsers. - * - * @since 2.8 - */ - protected final boolean _checkForExistingToken; - - /** - * Index of the next parser in {@link #_parsers}. - */ - protected int _nextParserIndex; - - /** - * Flag used to indicate that `JsonParser.nextToken()` should not be called, - * due to parser already pointing to a token. - * - * @since 2.8 - */ - protected boolean _hasToken; - - /* - ******************************************************* - * Construction - ******************************************************* - */ - - @Deprecated // since 2.8 - protected JsonParserSequence(JsonParser[] parsers) { - this(false, parsers); - } - - /** - * @since 2.8 - */ - protected JsonParserSequence(boolean checkForExistingToken, JsonParser[] parsers) - { - super(parsers[0]); - _checkForExistingToken = checkForExistingToken; - _hasToken = checkForExistingToken && delegate.hasCurrentToken(); - _parsers = parsers; - _nextParserIndex = 1; - } - - /** - * Method that will construct a parser (possibly a sequence) that - * contains all given sub-parsers. - * All parsers given are checked to see if they are sequences: and - * if so, they will be "flattened", that is, contained parsers are - * directly added in a new sequence instead of adding sequences - * within sequences. This is done to minimize delegation depth, - * ideally only having just a single level of delegation. - */ - public static JsonParserSequence createFlattened(boolean checkForExistingToken, - JsonParser first, JsonParser second) - { - if (!(first instanceof JsonParserSequence || second instanceof JsonParserSequence)) { - return new JsonParserSequence(checkForExistingToken, - new JsonParser[] { first, second }); - } - ArrayList p = new ArrayList(); - if (first instanceof JsonParserSequence) { - ((JsonParserSequence) first).addFlattenedActiveParsers(p); - } else { - p.add(first); - } - if (second instanceof JsonParserSequence) { - ((JsonParserSequence) second).addFlattenedActiveParsers(p); - } else { - p.add(second); - } - return new JsonParserSequence(checkForExistingToken, - p.toArray(new JsonParser[p.size()])); - } - - /** - * @deprecated Since 2.8 use {@link #createFlattened(boolean, JsonParser, JsonParser)} - * instead - */ - @Deprecated // since 2.8 - public static JsonParserSequence createFlattened(JsonParser first, JsonParser second) { - return createFlattened(false, first, second); - } - - protected void addFlattenedActiveParsers(List listToAddIn) - { - for (int i = _nextParserIndex-1, len = _parsers.length; i < len; ++i) { - JsonParser p = _parsers[i]; - if (p instanceof JsonParserSequence) { - ((JsonParserSequence) p).addFlattenedActiveParsers(listToAddIn); - } else { - listToAddIn.add(p); - } - } - } - - /* - /******************************************************* - /* Overridden methods, needed: cases where default - /* delegation does not work - /******************************************************* - */ - - @Override - public void close() throws IOException { - do { delegate.close(); } while (switchToNext()); - } - - @Override - public JsonToken nextToken() throws IOException - { - if (delegate == null) { - return null; - } - if (_hasToken) { - _hasToken = false; - return delegate.currentToken(); - } - JsonToken t = delegate.nextToken(); - if (t == null) { - return switchAndReturnNext(); - } - return t; - } - - /* - /******************************************************* - /* Additional extended API - /******************************************************* - */ - - /** - * Method that is most useful for debugging or testing; - * returns actual number of underlying parsers sequence - * was constructed with (nor just ones remaining active) - */ - public int containedParsersCount() { - return _parsers.length; - } - - /* - /******************************************************* - /* Helper methods - /******************************************************* - */ - - /** - * Method that will switch active delegate parser from the current one - * to the next parser in sequence, if there is another parser left: - * if so, the next parser will become the active delegate parser. - * - * @return True if switch succeeded; false otherwise - * - * @since 2.8 - */ - protected boolean switchToNext() - { - if (_nextParserIndex < _parsers.length) { - delegate = _parsers[_nextParserIndex++]; - return true; - } - return false; - } - - protected JsonToken switchAndReturnNext() throws IOException - { - while (_nextParserIndex < _parsers.length) { - delegate = _parsers[_nextParserIndex++]; - if (_checkForExistingToken && delegate.hasCurrentToken()) { - return delegate.getCurrentToken(); - } - JsonToken t = delegate.nextToken(); - if (t != null) { - return t; - } - } - return null; - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/MinimalPrettyPrinter.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/MinimalPrettyPrinter.java deleted file mode 100644 index 1c8169dc..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/MinimalPrettyPrinter.java +++ /dev/null @@ -1,153 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.util; - -import java.io.IOException; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerationException; -import autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator; -import autosaveworld.zlibs.com.fasterxml.jackson.core.PrettyPrinter; - -/** - * {@link PrettyPrinter} implementation that adds no indentation, - * just implements everything necessary for value output to work - * as expected, and provide simpler extension points to allow - * for creating simple custom implementations that add specific - * decoration or overrides. Since behavior then is very similar - * to using no pretty printer at all, usually sub-classes are used. - *

- * Beyond purely minimal implementation, there is limited amount of - * configurability which may be useful for actual use: for example, - * it is possible to redefine separator used between root-level - * values (default is single space; can be changed to line-feed). - *

- * Note: does NOT implement {@link Instantiatable} since this is - * a stateless implementation; that is, a single instance can be - * shared between threads. - */ -public class MinimalPrettyPrinter - implements PrettyPrinter, java.io.Serializable -{ - private static final long serialVersionUID = 1L; - - /** - * Default String used for separating root values is single space. - */ - public final static String DEFAULT_ROOT_VALUE_SEPARATOR = " "; - - protected String _rootValueSeparator = DEFAULT_ROOT_VALUE_SEPARATOR; - - /* - /********************************************************** - /* Life-cycle, construction, configuration - /********************************************************** - */ - - public MinimalPrettyPrinter() { - this(DEFAULT_ROOT_VALUE_SEPARATOR); - } - - public MinimalPrettyPrinter(String rootValueSeparator) { - _rootValueSeparator = rootValueSeparator; - } - - public void setRootValueSeparator(String sep) { - _rootValueSeparator = sep; - } - - /* - /********************************************************** - /* PrettyPrinter impl - /********************************************************** - */ - - @Override - public void writeRootValueSeparator(JsonGenerator jg) throws IOException, JsonGenerationException - { - if (_rootValueSeparator != null) { - jg.writeRaw(_rootValueSeparator); - } - } - - @Override - public void writeStartObject(JsonGenerator jg) - throws IOException, JsonGenerationException - { - jg.writeRaw('{'); - } - - @Override - public void beforeObjectEntries(JsonGenerator jg) - throws IOException, JsonGenerationException - { - // nothing special, since no indentation is added - } - - /** - * Method called after an object field has been output, but - * before the value is output. - *

- * Default handling will just output a single - * colon to separate the two, without additional spaces. - */ - @Override - public void writeObjectFieldValueSeparator(JsonGenerator jg) - throws IOException, JsonGenerationException - { - jg.writeRaw(':'); - } - - /** - * Method called after an object entry (field:value) has been completely - * output, and before another value is to be output. - *

- * Default handling (without pretty-printing) will output a single - * comma to separate the two. - */ - @Override - public void writeObjectEntrySeparator(JsonGenerator jg) - throws IOException, JsonGenerationException - { - jg.writeRaw(','); - } - - @Override - public void writeEndObject(JsonGenerator jg, int nrOfEntries) - throws IOException, JsonGenerationException - { - jg.writeRaw('}'); - } - - @Override - public void writeStartArray(JsonGenerator jg) - throws IOException, JsonGenerationException - { - jg.writeRaw('['); - } - - @Override - public void beforeArrayValues(JsonGenerator jg) - throws IOException, JsonGenerationException - { - // nothing special, since no indentation is added - } - - /** - * Method called after an array value has been completely - * output, and before another value is to be output. - *

- * Default handling (without pretty-printing) will output a single - * comma to separate values. - */ - @Override - public void writeArrayValueSeparator(JsonGenerator jg) - throws IOException, JsonGenerationException - { - jg.writeRaw(','); - } - - @Override - public void writeEndArray(JsonGenerator jg, int nrOfValues) - throws IOException, JsonGenerationException - { - jg.writeRaw(']'); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/RequestPayload.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/RequestPayload.java deleted file mode 100644 index c5524499..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/RequestPayload.java +++ /dev/null @@ -1,67 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.util; - -import java.io.IOException; - -/** - * Container object used to contain optional information on content - * being parsed, passed to {@link autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParseException} in case of - * exception being thrown; this may be useful for caller to display - * information on failure. - * - * @since 2.8 - */ -public class RequestPayload - implements java.io.Serializable // just in case, even though likely included as transient -{ - private static final long serialVersionUID = 1L; - - // request payload as byte[] - protected byte[] _payloadAsBytes; - - // request payload as String - protected CharSequence _payloadAsText; - - // Charset if the request payload is set in bytes - protected String _charset; - - public RequestPayload(byte[] bytes, String charset) { - if (bytes == null) { - throw new IllegalArgumentException(); - } - _payloadAsBytes = bytes; - _charset = (charset == null || charset.isEmpty()) ? "UTF-8" : charset; - } - - public RequestPayload(CharSequence str) { - if (str == null) { - throw new IllegalArgumentException(); - } - _payloadAsText = str; - } - - /** - * Returns the raw request payload object i.e, either byte[] or String - * - * @return Object which is a raw request payload i.e, either byte[] or - * String - */ - public Object getRawPayload() { - if (_payloadAsBytes != null) { - return _payloadAsBytes; - } - - return _payloadAsText; - } - - @Override - public String toString() { - if (_payloadAsBytes != null) { - try { - return new String(_payloadAsBytes, _charset); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - return _payloadAsText.toString(); - } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/TextBuffer.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/TextBuffer.java deleted file mode 100644 index 55f2eb20..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/TextBuffer.java +++ /dev/null @@ -1,781 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.util; - -import java.io.IOException; -import java.io.Writer; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Arrays; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.io.NumberInput; - -/** - * TextBuffer is a class similar to {@link StringBuffer}, with - * following differences: - *

    - *
  • TextBuffer uses segments character arrays, to avoid having - * to do additional array copies when array is not big enough. - * This means that only reallocating that is necessary is done only once: - * if and when caller - * wants to access contents in a linear array (char[], String). - *
  • -*
  • TextBuffer can also be initialized in "shared mode", in which -* it will just act as a wrapper to a single char array managed -* by another object (like parser that owns it) - *
  • - *
  • TextBuffer is not synchronized. - *
  • - *
- */ -public final class TextBuffer -{ - final static char[] NO_CHARS = new char[0]; - - /** - * Let's start with sizable but not huge buffer, will grow as necessary - */ - final static int MIN_SEGMENT_LEN = 1000; - - /** - * Let's limit maximum segment length to something sensible - * like 256k - */ - final static int MAX_SEGMENT_LEN = 0x40000; - - /* - /********************************************************** - /* Configuration: - /********************************************************** - */ - - private final BufferRecycler _allocator; - - /* - /********************************************************** - /* Shared input buffers - /********************************************************** - */ - - /** - * Shared input buffer; stored here in case some input can be returned - * as is, without being copied to collector's own buffers. Note that - * this is read-only for this Object. - */ - private char[] _inputBuffer; - - /** - * Character offset of first char in input buffer; -1 to indicate - * that input buffer currently does not contain any useful char data - */ - private int _inputStart; - - private int _inputLen; - - /* - /********************************************************** - /* Aggregation segments (when not using input buf) - /********************************************************** - */ - - /** - * List of segments prior to currently active segment. - */ - private ArrayList _segments; - - /** - * Flag that indicates whether _seqments is non-empty - */ - private boolean _hasSegments; - - // // // Currently used segment; not (yet) contained in _seqments - - /** - * Amount of characters in segments in {@link _segments} - */ - private int _segmentSize; - - private char[] _currentSegment; - - /** - * Number of characters in currently active (last) segment - */ - private int _currentSize; - - /* - /********************************************************** - /* Caching of results - /********************************************************** - */ - - /** - * String that will be constructed when the whole contents are - * needed; will be temporarily stored in case asked for again. - */ - private String _resultString; - - private char[] _resultArray; - - /* - /********************************************************** - /* Life-cycle - /********************************************************** - */ - - public TextBuffer(BufferRecycler allocator) { - _allocator = allocator; - } - - /** - * Method called to indicate that the underlying buffers should now - * be recycled if they haven't yet been recycled. Although caller - * can still use this text buffer, it is not advisable to call this - * method if that is likely, since next time a buffer is needed, - * buffers need to reallocated. - * Note: calling this method automatically also clears contents - * of the buffer. - */ - public void releaseBuffers() - { - if (_allocator == null) { - resetWithEmpty(); - } else { - if (_currentSegment != null) { - // First, let's get rid of all but the largest char array - resetWithEmpty(); - // And then return that array - char[] buf = _currentSegment; - _currentSegment = null; - _allocator.releaseCharBuffer(BufferRecycler.CHAR_TEXT_BUFFER, buf); - } - } - } - - /** - * Method called to clear out any content text buffer may have, and - * initializes buffer to use non-shared data. - */ - public void resetWithEmpty() - { - _inputStart = -1; // indicates shared buffer not used - _currentSize = 0; - _inputLen = 0; - - _inputBuffer = null; - _resultString = null; - _resultArray = null; - - // And then reset internal input buffers, if necessary: - if (_hasSegments) { - clearSegments(); - } - } - - /** - * Method called to initialize the buffer with a shared copy of data; - * this means that buffer will just have pointers to actual data. It - * also means that if anything is to be appended to the buffer, it - * will first have to unshare it (make a local copy). - */ - public void resetWithShared(char[] buf, int start, int len) - { - // First, let's clear intermediate values, if any: - _resultString = null; - _resultArray = null; - - // Then let's mark things we need about input buffer - _inputBuffer = buf; - _inputStart = start; - _inputLen = len; - - // And then reset internal input buffers, if necessary: - if (_hasSegments) { - clearSegments(); - } - } - - public void resetWithCopy(char[] buf, int start, int len) - { - _inputBuffer = null; - _inputStart = -1; // indicates shared buffer not used - _inputLen = 0; - - _resultString = null; - _resultArray = null; - - // And then reset internal input buffers, if necessary: - if (_hasSegments) { - clearSegments(); - } else if (_currentSegment == null) { - _currentSegment = buf(len); - } - _currentSize = _segmentSize = 0; - append(buf, start, len); - } - - public void resetWithString(String value) - { - _inputBuffer = null; - _inputStart = -1; - _inputLen = 0; - - _resultString = value; - _resultArray = null; - - if (_hasSegments) { - clearSegments(); - } - _currentSize = 0; - - } - - /** - * Helper method used to find a buffer to use, ideally one - * recycled earlier. - */ - private char[] buf(int needed) - { - if (_allocator != null) { - return _allocator.allocCharBuffer(BufferRecycler.CHAR_TEXT_BUFFER, needed); - } - return new char[Math.max(needed, MIN_SEGMENT_LEN)]; - } - - private void clearSegments() - { - _hasSegments = false; - /* Let's start using _last_ segment from list; for one, it's - * the biggest one, and it's also most likely to be cached - */ - /* 28-Aug-2009, tatu: Actually, the current segment should - * be the biggest one, already - */ - //_currentSegment = _segments.get(_segments.size() - 1); - _segments.clear(); - _currentSize = _segmentSize = 0; - } - - /* - /********************************************************** - /* Accessors for implementing public interface - /********************************************************** - */ - - /** - * @return Number of characters currently stored by this collector - */ - public int size() { - if (_inputStart >= 0) { // shared copy from input buf - return _inputLen; - } - if (_resultArray != null) { - return _resultArray.length; - } - if (_resultString != null) { - return _resultString.length(); - } - // local segmented buffers - return _segmentSize + _currentSize; - } - - public int getTextOffset() { - /* Only shared input buffer can have non-zero offset; buffer - * segments start at 0, and if we have to create a combo buffer, - * that too will start from beginning of the buffer - */ - return (_inputStart >= 0) ? _inputStart : 0; - } - - /** - * Method that can be used to check whether textual contents can - * be efficiently accessed using {@link #getTextBuffer}. - */ - public boolean hasTextAsCharacters() - { - // if we have array in some form, sure - if (_inputStart >= 0 || _resultArray != null) return true; - // not if we have String as value - if (_resultString != null) return false; - return true; - } - - /** - * Accessor that may be used to get the contents of this buffer in a single - * char array regardless of whether they were collected in a segmented - * fashion or not. - */ - public char[] getTextBuffer() - { - // Are we just using shared input buffer? - if (_inputStart >= 0) return _inputBuffer; - if (_resultArray != null) return _resultArray; - if (_resultString != null) { - return (_resultArray = _resultString.toCharArray()); - } - // Nope; but does it fit in just one segment? - if (!_hasSegments) { - return (_currentSegment == null) ? NO_CHARS : _currentSegment; - } - // Nope, need to have/create a non-segmented array and return it - return contentsAsArray(); - } - - /* - /********************************************************** - /* Other accessors: - /********************************************************** - */ - - public String contentsAsString() - { - if (_resultString == null) { - // Has array been requested? Can make a shortcut, if so: - if (_resultArray != null) { - _resultString = new String(_resultArray); - } else { - // Do we use shared array? - if (_inputStart >= 0) { - if (_inputLen < 1) { - return (_resultString = ""); - } - _resultString = new String(_inputBuffer, _inputStart, _inputLen); - } else { // nope... need to copy - // But first, let's see if we have just one buffer - int segLen = _segmentSize; - int currLen = _currentSize; - - if (segLen == 0) { // yup - _resultString = (currLen == 0) ? "" : new String(_currentSegment, 0, currLen); - } else { // no, need to combine - StringBuilder sb = new StringBuilder(segLen + currLen); - // First stored segments - if (_segments != null) { - for (int i = 0, len = _segments.size(); i < len; ++i) { - char[] curr = _segments.get(i); - sb.append(curr, 0, curr.length); - } - } - // And finally, current segment: - sb.append(_currentSegment, 0, _currentSize); - _resultString = sb.toString(); - } - } - } - } - return _resultString; - } - - public char[] contentsAsArray() { - char[] result = _resultArray; - if (result == null) { - _resultArray = result = resultArray(); - } - return result; - } - - /** - * Convenience method for converting contents of the buffer - * into a {@link BigDecimal}. - */ - public BigDecimal contentsAsDecimal() throws NumberFormatException - { - // Already got a pre-cut array? - if (_resultArray != null) { - return NumberInput.parseBigDecimal(_resultArray); - } - // Or a shared buffer? - if ((_inputStart >= 0) && (_inputBuffer != null)) { - return NumberInput.parseBigDecimal(_inputBuffer, _inputStart, _inputLen); - } - // Or if not, just a single buffer (the usual case) - if ((_segmentSize == 0) && (_currentSegment != null)) { - return NumberInput.parseBigDecimal(_currentSegment, 0, _currentSize); - } - // If not, let's just get it aggregated... - return NumberInput.parseBigDecimal(contentsAsArray()); - } - - /** - * Convenience method for converting contents of the buffer - * into a Double value. - */ - public double contentsAsDouble() throws NumberFormatException { - return NumberInput.parseDouble(contentsAsString()); - } - - /** - * @since 2.8 - */ - public int contentsToWriter(Writer w) throws IOException - { - if (_resultArray != null) { - w.write(_resultArray); - return _resultArray.length; - } - if (_resultString != null) { // Can take a shortcut... - w.write(_resultString); - return _resultString.length(); - } - // Do we use shared array? - if (_inputStart >= 0) { - final int len = _inputLen; - if (len > 0) { - w.write(_inputBuffer, _inputStart, len); - } - return len; - } - // nope, not shared - int total = 0; - if (_segments != null) { - for (int i = 0, end = _segments.size(); i < end; ++i) { - char[] curr = _segments.get(i); - int currLen = curr.length; - w.write(curr, 0, currLen); - total += currLen; - } - } - int len = _currentSize; - if (len > 0) { - w.write(_currentSegment, 0, len); - total += len; - } - return total; - } - - /* - /********************************************************** - /* Public mutators: - /********************************************************** - */ - - /** - * Method called to make sure that buffer is not using shared input - * buffer; if it is, it will copy such contents to private buffer. - */ - public void ensureNotShared() { - if (_inputStart >= 0) { - unshare(16); - } - } - - public void append(char c) { - // Using shared buffer so far? - if (_inputStart >= 0) { - unshare(16); - } - _resultString = null; - _resultArray = null; - // Room in current segment? - char[] curr = _currentSegment; - if (_currentSize >= curr.length) { - expand(1); - curr = _currentSegment; - } - curr[_currentSize++] = c; - } - - public void append(char[] c, int start, int len) - { - // Can't append to shared buf (sanity check) - if (_inputStart >= 0) { - unshare(len); - } - _resultString = null; - _resultArray = null; - - // Room in current segment? - char[] curr = _currentSegment; - int max = curr.length - _currentSize; - - if (max >= len) { - System.arraycopy(c, start, curr, _currentSize, len); - _currentSize += len; - return; - } - // No room for all, need to copy part(s): - if (max > 0) { - System.arraycopy(c, start, curr, _currentSize, max); - start += max; - len -= max; - } - /* And then allocate new segment; we are guaranteed to now - * have enough room in segment. - */ - // Except, as per [Issue-24], not for HUGE appends... so: - do { - expand(len); - int amount = Math.min(_currentSegment.length, len); - System.arraycopy(c, start, _currentSegment, 0, amount); - _currentSize += amount; - start += amount; - len -= amount; - } while (len > 0); - } - - public void append(String str, int offset, int len) - { - // Can't append to shared buf (sanity check) - if (_inputStart >= 0) { - unshare(len); - } - _resultString = null; - _resultArray = null; - - // Room in current segment? - char[] curr = _currentSegment; - int max = curr.length - _currentSize; - if (max >= len) { - str.getChars(offset, offset+len, curr, _currentSize); - _currentSize += len; - return; - } - // No room for all, need to copy part(s): - if (max > 0) { - str.getChars(offset, offset+max, curr, _currentSize); - len -= max; - offset += max; - } - /* And then allocate new segment; we are guaranteed to now - * have enough room in segment. - */ - // Except, as per [Issue-24], not for HUGE appends... so: - do { - expand(len); - int amount = Math.min(_currentSegment.length, len); - str.getChars(offset, offset+amount, _currentSegment, 0); - _currentSize += amount; - offset += amount; - len -= amount; - } while (len > 0); - } - - /* - /********************************************************** - /* Raw access, for high-performance use: - /********************************************************** - */ - - public char[] getCurrentSegment() - { - /* Since the intention of the caller is to directly add stuff into - * buffers, we should NOT have anything in shared buffer... ie. may - * need to unshare contents. - */ - if (_inputStart >= 0) { - unshare(1); - } else { - char[] curr = _currentSegment; - if (curr == null) { - _currentSegment = buf(0); - } else if (_currentSize >= curr.length) { - // Plus, we better have room for at least one more char - expand(1); - } - } - return _currentSegment; - } - - public char[] emptyAndGetCurrentSegment() - { - // inlined 'resetWithEmpty()' - _inputStart = -1; // indicates shared buffer not used - _currentSize = 0; - _inputLen = 0; - - _inputBuffer = null; - _resultString = null; - _resultArray = null; - - // And then reset internal input buffers, if necessary: - if (_hasSegments) { - clearSegments(); - } - char[] curr = _currentSegment; - if (curr == null) { - _currentSegment = curr = buf(0); - } - return curr; - } - - public int getCurrentSegmentSize() { return _currentSize; } - public void setCurrentLength(int len) { _currentSize = len; } - - /** - * @since 2.6 - */ - public String setCurrentAndReturn(int len) { - _currentSize = len; - // We can simplify handling here compared to full `contentsAsString()`: - if (_segmentSize > 0) { // longer text; call main method - return contentsAsString(); - } - // more common case: single segment - int currLen = _currentSize; - String str = (currLen == 0) ? "" : new String(_currentSegment, 0, currLen); - _resultString = str; - return str; - } - - public char[] finishCurrentSegment() { - if (_segments == null) { - _segments = new ArrayList(); - } - _hasSegments = true; - _segments.add(_currentSegment); - int oldLen = _currentSegment.length; - _segmentSize += oldLen; - _currentSize = 0; - - // Let's grow segments by 50% - int newLen = oldLen + (oldLen >> 1); - if (newLen < MIN_SEGMENT_LEN) { - newLen = MIN_SEGMENT_LEN; - } else if (newLen > MAX_SEGMENT_LEN) { - newLen = MAX_SEGMENT_LEN; - } - char[] curr = carr(newLen); - _currentSegment = curr; - return curr; - } - - /** - * Method called to expand size of the current segment, to - * accommodate for more contiguous content. Usually only - * used when parsing tokens like names if even then. - */ - public char[] expandCurrentSegment() - { - final char[] curr = _currentSegment; - // Let's grow by 50% by default - final int len = curr.length; - int newLen = len + (len >> 1); - // but above intended maximum, slow to increase by 25% - if (newLen > MAX_SEGMENT_LEN) { - newLen = len + (len >> 2); - } - return (_currentSegment = Arrays.copyOf(curr, newLen)); - } - - /** - * Method called to expand size of the current segment, to - * accommodate for more contiguous content. Usually only - * used when parsing tokens like names if even then. - * - * @param minSize Required minimum strength of the current segment - * - * @since 2.4.0 - */ - public char[] expandCurrentSegment(int minSize) { - char[] curr = _currentSegment; - if (curr.length >= minSize) return curr; - _currentSegment = curr = Arrays.copyOf(curr, minSize); - return curr; - } - - /* - /********************************************************** - /* Standard methods: - /********************************************************** - */ - - /** - * Note: calling this method may not be as efficient as calling - * {@link #contentsAsString}, since it's not guaranteed that resulting - * String is cached. - */ - @Override public String toString() { return contentsAsString(); } - - /* - /********************************************************** - /* Internal methods: - /********************************************************** - */ - - /** - * Method called if/when we need to append content when we have been - * initialized to use shared buffer. - */ - private void unshare(int needExtra) - { - int sharedLen = _inputLen; - _inputLen = 0; - char[] inputBuf = _inputBuffer; - _inputBuffer = null; - int start = _inputStart; - _inputStart = -1; - - // Is buffer big enough, or do we need to reallocate? - int needed = sharedLen+needExtra; - if (_currentSegment == null || needed > _currentSegment.length) { - _currentSegment = buf(needed); - } - if (sharedLen > 0) { - System.arraycopy(inputBuf, start, _currentSegment, 0, sharedLen); - } - _segmentSize = 0; - _currentSize = sharedLen; - } - - /** - * Method called when current segment is full, to allocate new - * segment. - */ - private void expand(int minNewSegmentSize) - { - // First, let's move current segment to segment list: - if (_segments == null) { - _segments = new ArrayList(); - } - char[] curr = _currentSegment; - _hasSegments = true; - _segments.add(curr); - _segmentSize += curr.length; - _currentSize = 0; - int oldLen = curr.length; - - // Let's grow segments by 50% minimum - int newLen = oldLen + (oldLen >> 1); - if (newLen < MIN_SEGMENT_LEN) { - newLen = MIN_SEGMENT_LEN; - } else if (newLen > MAX_SEGMENT_LEN) { - newLen = MAX_SEGMENT_LEN; - } - _currentSegment = carr(newLen); - } - - private char[] resultArray() - { - if (_resultString != null) { // Can take a shortcut... - return _resultString.toCharArray(); - } - // Do we use shared array? - if (_inputStart >= 0) { - final int len = _inputLen; - if (len < 1) { - return NO_CHARS; - } - final int start = _inputStart; - if (start == 0) { - return Arrays.copyOf(_inputBuffer, len); - } - return Arrays.copyOfRange(_inputBuffer, start, start+len); - } - // nope, not shared - int size = size(); - if (size < 1) { - return NO_CHARS; - } - int offset = 0; - final char[] result = carr(size); - if (_segments != null) { - for (int i = 0, len = _segments.size(); i < len; ++i) { - char[] curr = _segments.get(i); - int currLen = curr.length; - System.arraycopy(curr, 0, result, offset, currLen); - offset += currLen; - } - } - System.arraycopy(_currentSegment, 0, result, offset, _currentSize); - return result; - } - - private char[] carr(int len) { return new char[len]; } -} diff --git a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/VersionUtil.java b/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/VersionUtil.java deleted file mode 100644 index 6760c109..00000000 --- a/src/autosaveworld/zlibs/com/fasterxml/jackson/core/util/VersionUtil.java +++ /dev/null @@ -1,166 +0,0 @@ -package autosaveworld.zlibs.com.fasterxml.jackson.core.util; - -import java.io.Closeable; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import java.util.regex.Pattern; - -import autosaveworld.zlibs.com.fasterxml.jackson.core.Version; -import autosaveworld.zlibs.com.fasterxml.jackson.core.Versioned; - -/** - * Functionality for supporting exposing of component {@link Version}s. - * Also contains other misc methods that have no other place to live in. - *

- * Note that this class can be used in two roles: first, as a static - * utility class for loading purposes, and second, as a singleton - * loader of per-module version information. - *

- * Note that method for accessing version information changed between versions - * 2.1 and 2.2; earlier code used file named "VERSION.txt"; but this has serious - * performance issues on some platforms (Android), so a replacement system - * was implemented to use class generation and dynamic class loading. - *

- * Note that functionality for reading "VERSION.txt" was removed completely - * from Jackson 2.6. - */ -public class VersionUtil -{ - private final static Pattern V_SEP = Pattern.compile("[-_./;:]"); - - /* - /********************************************************** - /* Instance life-cycle - /********************************************************** - */ - - protected VersionUtil() { } - - @Deprecated // since 2.9 - public Version version() { return Version.unknownVersion(); } - - /* - /********************************************************** - /* Static load methods - /********************************************************** - */ - - /** - * Helper method that will try to load version information for specified - * class. Implementation is as follows: - * - * First, tries to load version info from a class named - * "PackageVersion" in the same package as the class. - * - * If no version information is found, {@link Version#unknownVersion()} is returned. - */ - public static Version versionFor(Class cls) - { - Version version = packageVersionFor(cls); - return version == null ? Version.unknownVersion() : version; - } - - /** - * Loads version information by introspecting a class named - * "PackageVersion" in the same package as the given class. - *

- * If the class could not be found or does not have a public - * static Version field named "VERSION", returns null. - */ - public static Version packageVersionFor(Class cls) - { - Version v = null; - try { - String versionInfoClassName = cls.getPackage().getName() + ".PackageVersion"; - Class vClass = Class.forName(versionInfoClassName, true, cls.getClassLoader()); - // However, if class exists, it better work correctly, no swallowing exceptions - try { - v = ((Versioned) vClass.newInstance()).version(); - } catch (Exception e) { - throw new IllegalArgumentException("Failed to get Versioned out of "+vClass); - } - } catch (Exception e) { // ok to be missing (not good but acceptable) - ; - } - return (v == null) ? Version.unknownVersion() : v; - } - - /** - * Will attempt to load the maven version for the given groupId and - * artifactId. Maven puts a pom.properties file in - * META-INF/maven/groupId/artifactId, containing the groupId, - * artifactId and version of the library. - * - * @param cl the ClassLoader to load the pom.properties file from - * @param groupId the groupId of the library - * @param artifactId the artifactId of the library - * @return The version - * - * @deprecated Since 2.6: functionality not used by any official Jackson component, should be - * moved out if anyone needs it - */ - @Deprecated // since 2.6 - public static Version mavenVersionFor(ClassLoader cl, String groupId, String artifactId) - { - InputStream pomProperties = cl.getResourceAsStream("META-INF/maven/" - + groupId.replaceAll("\\.", "/")+ "/" + artifactId + "/pom.properties"); - if (pomProperties != null) { - try { - Properties props = new Properties(); - props.load(pomProperties); - String versionStr = props.getProperty("version"); - String pomPropertiesArtifactId = props.getProperty("artifactId"); - String pomPropertiesGroupId = props.getProperty("groupId"); - return parseVersion(versionStr, pomPropertiesGroupId, pomPropertiesArtifactId); - } catch (IOException e) { - // Ignore - } finally { - _close(pomProperties); - } - } - return Version.unknownVersion(); - } - - /** - * Method used by PackageVersion classes to decode version injected by Maven build. - */ - public static Version parseVersion(String s, String groupId, String artifactId) - { - if (s != null && (s = s.trim()).length() > 0) { - String[] parts = V_SEP.split(s); - return new Version(parseVersionPart(parts[0]), - (parts.length > 1) ? parseVersionPart(parts[1]) : 0, - (parts.length > 2) ? parseVersionPart(parts[2]) : 0, - (parts.length > 3) ? parts[3] : null, - groupId, artifactId); - } - return Version.unknownVersion(); - } - - protected static int parseVersionPart(String s) { - int number = 0; - for (int i = 0, len = s.length(); i < len; ++i) { - char c = s.charAt(i); - if (c > '9' || c < '0') break; - number = (number * 10) + (c - '0'); - } - return number; - } - - private final static void _close(Closeable c) { - try { - c.close(); - } catch (IOException e) { } - } - - /* - /********************************************************** - /* Orphan utility methods - /********************************************************** - */ - - public final static void throwInternal() { - throw new RuntimeException("Internal error: this code path should never get executed"); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/AuthorizationCodeFlow.java b/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/AuthorizationCodeFlow.java deleted file mode 100644 index 20f4e04e..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/AuthorizationCodeFlow.java +++ /dev/null @@ -1,866 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.oauth2; - -import java.io.IOException; -import java.util.Collection; -import java.util.Collections; - -import autosaveworld.zlibs.com.google.api.client.auth.oauth2.Credential.AccessMethod; -import autosaveworld.zlibs.com.google.api.client.http.GenericUrl; -import autosaveworld.zlibs.com.google.api.client.http.HttpExecuteInterceptor; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequestInitializer; -import autosaveworld.zlibs.com.google.api.client.http.HttpTransport; -import autosaveworld.zlibs.com.google.api.client.json.JsonFactory; -import autosaveworld.zlibs.com.google.api.client.util.Beta; -import autosaveworld.zlibs.com.google.api.client.util.Clock; -import autosaveworld.zlibs.com.google.api.client.util.Joiner; -import autosaveworld.zlibs.com.google.api.client.util.Lists; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.store.DataStore; -import autosaveworld.zlibs.com.google.api.client.util.store.DataStoreFactory; - -/** - * Thread-safe OAuth 2.0 authorization code flow that manages and persists end-user credentials. - * - *

- * This is designed to simplify the flow in which an end-user authorizes the application to access - * their protected data, and then the application has access to their data based on an access token - * and a refresh token to refresh that access token when it expires. - *

- * - *

- * The first step is to call {@link #loadCredential(String)} based on the known user ID to check if - * the end-user's credentials are already known. If not, call {@link #newAuthorizationUrl()} and - * direct the end-user's browser to an authorization page. The web browser will then redirect to the - * redirect URL with a {@code "code"} query parameter which can then be used to request an access - * token using {@link #newTokenRequest(String)}. Finally, use - * {@link #createAndStoreCredential(TokenResponse, String)} to store and obtain a credential for - * accessing protected resources. - *

- * - * @since 1.7 - * @author Yaniv Inbar - */ -public class AuthorizationCodeFlow { - - /** - * Method of presenting the access token to the resource server (for example - * {@link BearerToken#authorizationHeaderAccessMethod}). - */ - private final AccessMethod method; - - /** HTTP transport. */ - private final HttpTransport transport; - - /** JSON factory. */ - private final JsonFactory jsonFactory; - - /** Token server encoded URL. */ - private final String tokenServerEncodedUrl; - - /** - * Client authentication or {@code null} for none (see - * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}). - */ - private final HttpExecuteInterceptor clientAuthentication; - - /** Client identifier. */ - private final String clientId; - - /** Authorization server encoded URL. */ - private final String authorizationServerEncodedUrl; - - /** Credential persistence store or {@code null} for none. */ - @Beta - @Deprecated - private final CredentialStore credentialStore; - - /** Stored credential data store or {@code null} for none. */ - @Beta - private final DataStore credentialDataStore; - - /** HTTP request initializer or {@code null} for none. */ - private final HttpRequestInitializer requestInitializer; - - /** Clock passed along to Credential. */ - private final Clock clock; - - /** Collection of scopes. */ - private final Collection scopes; - - /** Credential created listener or {@code null} for none. */ - private final CredentialCreatedListener credentialCreatedListener; - - /** Refresh listeners provided by the client. */ - private final Collection refreshListeners; - - /** - * @param method method of presenting the access token to the resource server (for example - * {@link BearerToken#authorizationHeaderAccessMethod}) - * @param transport HTTP transport - * @param jsonFactory JSON factory - * @param tokenServerUrl token server URL - * @param clientAuthentication client authentication or {@code null} for none (see - * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}) - * @param clientId client identifier - * @param authorizationServerEncodedUrl authorization server encoded URL - * - * @since 1.14 - */ - public AuthorizationCodeFlow(AccessMethod method, - HttpTransport transport, - JsonFactory jsonFactory, - GenericUrl tokenServerUrl, - HttpExecuteInterceptor clientAuthentication, - String clientId, - String authorizationServerEncodedUrl) { - this(new Builder(method, - transport, - jsonFactory, - tokenServerUrl, - clientAuthentication, - clientId, - authorizationServerEncodedUrl)); - } - - /** - * @param builder authorization code flow builder - * - * @since 1.14 - */ - protected AuthorizationCodeFlow(Builder builder) { - method = Preconditions.checkNotNull(builder.method); - transport = Preconditions.checkNotNull(builder.transport); - jsonFactory = Preconditions.checkNotNull(builder.jsonFactory); - tokenServerEncodedUrl = Preconditions.checkNotNull(builder.tokenServerUrl).build(); - clientAuthentication = builder.clientAuthentication; - clientId = Preconditions.checkNotNull(builder.clientId); - authorizationServerEncodedUrl = - Preconditions.checkNotNull(builder.authorizationServerEncodedUrl); - requestInitializer = builder.requestInitializer; - credentialStore = builder.credentialStore; - credentialDataStore = builder.credentialDataStore; - scopes = Collections.unmodifiableCollection(builder.scopes); - clock = Preconditions.checkNotNull(builder.clock); - credentialCreatedListener = builder.credentialCreatedListener; - refreshListeners = Collections.unmodifiableCollection(builder.refreshListeners); - } - - /** - * Returns a new instance of an authorization code request URL. - * - *

- * This is a builder for an authorization web page to allow the end user to authorize the - * application to access their protected resources and that returns an authorization code. It uses - * the {@link #getAuthorizationServerEncodedUrl()}, {@link #getClientId()}, and - * {@link #getScopes()}. Sample usage: - *

- * - *
-  private AuthorizationCodeFlow flow;
-
-  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
-    String url = flow.newAuthorizationUrl().setState("xyz")
-        .setRedirectUri("https://client.example.com/rd").build();
-    response.sendRedirect(url);
-  }
-   * 
- */ - public AuthorizationCodeRequestUrl newAuthorizationUrl() { - return new AuthorizationCodeRequestUrl(authorizationServerEncodedUrl, clientId).setScopes( - scopes); - } - - /** - * Returns a new instance of an authorization code token request based on the given authorization - * code. - * - *

- * This is used to make a request for an access token using the authorization code. It uses - * {@link #getTransport()}, {@link #getJsonFactory()}, {@link #getTokenServerEncodedUrl()}, - * {@link #getClientAuthentication()}, {@link #getRequestInitializer()}, and {@link #getScopes()}. - *

- * - *
-  static TokenResponse requestAccessToken(AuthorizationCodeFlow flow, String code)
-      throws IOException, TokenResponseException {
-    return flow.newTokenRequest(code).setRedirectUri("https://client.example.com/rd").execute();
-  }
-   * 
- * - * @param authorizationCode authorization code. - */ - public AuthorizationCodeTokenRequest newTokenRequest(String authorizationCode) { - return new AuthorizationCodeTokenRequest(transport, jsonFactory, - new GenericUrl(tokenServerEncodedUrl), authorizationCode).setClientAuthentication( - clientAuthentication).setRequestInitializer(requestInitializer).setScopes(scopes); - } - - /** - * Creates a new credential for the given user ID based on the given token response and store in - * the credential store. - * - * @param response token response - * @param userId user ID or {@code null} if not using a persisted credential store - * @return newly created credential - */ - @SuppressWarnings("deprecation") - public Credential createAndStoreCredential(TokenResponse response, String userId) - throws IOException { - Credential credential = newCredential(userId).setFromTokenResponse(response); - if (credentialStore != null) { - credentialStore.store(userId, credential); - } - if (credentialDataStore != null) { - credentialDataStore.set(userId, new StoredCredential(credential)); - } - if (credentialCreatedListener != null) { - credentialCreatedListener.onCredentialCreated(credential, response); - } - return credential; - } - - /** - * Loads the credential of the given user ID from the credential store. - * - * @param userId user ID or {@code null} if not using a persisted credential store - * @return credential found in the credential store of the given user ID or {@code null} for none - * found - */ - @SuppressWarnings("deprecation") - public Credential loadCredential(String userId) throws IOException { - if (credentialDataStore == null && credentialStore == null) { - return null; - } - Credential credential = newCredential(userId); - if (credentialDataStore != null) { - StoredCredential stored = credentialDataStore.get(userId); - if (stored == null) { - return null; - } - credential.setAccessToken(stored.getAccessToken()); - credential.setRefreshToken(stored.getRefreshToken()); - credential.setExpirationTimeMilliseconds(stored.getExpirationTimeMilliseconds()); - } else if (!credentialStore.load(userId, credential)) { - return null; - } - return credential; - } - - /** - * Returns a new credential instance based on the given user ID. - * - * @param userId user ID or {@code null} if not using a persisted credential store - */ - @SuppressWarnings("deprecation") - private Credential newCredential(String userId) { - Credential.Builder builder = new Credential.Builder(method).setTransport(transport) - .setJsonFactory(jsonFactory) - .setTokenServerEncodedUrl(tokenServerEncodedUrl) - .setClientAuthentication(clientAuthentication) - .setRequestInitializer(requestInitializer) - .setClock(clock); - if (credentialDataStore != null) { - builder.addRefreshListener( - new DataStoreCredentialRefreshListener(userId, credentialDataStore)); - } else if (credentialStore != null) { - builder.addRefreshListener(new CredentialStoreRefreshListener(userId, credentialStore)); - } - builder.getRefreshListeners().addAll(refreshListeners); - return builder.build(); - } - - /** - * Returns the method of presenting the access token to the resource server (for example - * {@link BearerToken#authorizationHeaderAccessMethod}). - */ - public final AccessMethod getMethod() { - return method; - } - - /** Returns the HTTP transport. */ - public final HttpTransport getTransport() { - return transport; - } - - /** Returns the JSON factory. */ - public final JsonFactory getJsonFactory() { - return jsonFactory; - } - - /** Returns the token server encoded URL. */ - public final String getTokenServerEncodedUrl() { - return tokenServerEncodedUrl; - } - - /** - * Returns the client authentication or {@code null} for none (see - * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}). - */ - public final HttpExecuteInterceptor getClientAuthentication() { - return clientAuthentication; - } - - /** Returns the client identifier. */ - public final String getClientId() { - return clientId; - } - - /** Returns the authorization server encoded URL. */ - public final String getAuthorizationServerEncodedUrl() { - return authorizationServerEncodedUrl; - } - - /** - * {@link Beta}
- * Returns the credential persistence store or {@code null} for none. - * @deprecated (to be removed in the future) Use {@link #getCredentialDataStore()} instead. - */ - @Beta - @Deprecated - public final CredentialStore getCredentialStore() { - return credentialStore; - } - - /** - * {@link Beta}
- * Returns the stored credential data store or {@code null} for none. - * - * @since 1.16 - */ - @Beta - public final DataStore getCredentialDataStore() { - return credentialDataStore; - } - - /** Returns the HTTP request initializer or {@code null} for none. */ - public final HttpRequestInitializer getRequestInitializer() { - return requestInitializer; - } - - /** - * Returns the space-separated list of scopes. - * - * @since 1.15 - */ - public final String getScopesAsString() { - return Joiner.on(' ').join(scopes); - } - - /** Returns the a collection of scopes. */ - public final Collection getScopes() { - return scopes; - } - - /** - * Returns the clock which will be passed along to the Credential. - * @since 1.9 - */ - public final Clock getClock() { - return clock; - } - - /** - * Returns the unmodifiable list of listeners for refresh token results. - * - * @since 1.15 - */ - public final Collection getRefreshListeners() { - return refreshListeners; - } - - /** - * Listener for a created credential after a successful token response in - * {@link #createAndStoreCredential}. - * - * @since 1.14 - */ - public interface CredentialCreatedListener { - - /** - * Notifies of a created credential after a successful token response in - * {@link #createAndStoreCredential}. - * - *

- * Typical use is to parse additional fields from the credential created, such as an ID token. - *

- * - * @param credential created credential - * @param tokenResponse successful token response - */ - void onCredentialCreated(Credential credential, TokenResponse tokenResponse) throws IOException; - } - - /** - * Authorization code flow builder. - * - *

- * Implementation is not thread-safe. - *

- */ - public static class Builder { - - /** - * Method of presenting the access token to the resource server (for example - * {@link BearerToken#authorizationHeaderAccessMethod}). - */ - AccessMethod method; - - /** HTTP transport. */ - HttpTransport transport; - - /** JSON factory. */ - JsonFactory jsonFactory; - - /** Token server URL. */ - GenericUrl tokenServerUrl; - - /** - * Client authentication or {@code null} for none (see - * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}). - */ - HttpExecuteInterceptor clientAuthentication; - - /** Client identifier. */ - String clientId; - - /** Authorization server encoded URL. */ - String authorizationServerEncodedUrl; - - /** Credential persistence store or {@code null} for none. */ - @Deprecated - @Beta - CredentialStore credentialStore; - - /** Stored credential data store or {@code null} for none. */ - @Beta - DataStore credentialDataStore; - - /** HTTP request initializer or {@code null} for none. */ - HttpRequestInitializer requestInitializer; - - /** Collection of scopes. */ - Collection scopes = Lists.newArrayList(); - - /** Clock passed along to the Credential. */ - Clock clock = Clock.SYSTEM; - - /** Credential created listener or {@code null} for none. */ - CredentialCreatedListener credentialCreatedListener; - - /** Refresh listeners provided by the client. */ - Collection refreshListeners = Lists.newArrayList(); - - /** - * @param method method of presenting the access token to the resource server (for example - * {@link BearerToken#authorizationHeaderAccessMethod}) - * @param transport HTTP transport - * @param jsonFactory JSON factory - * @param tokenServerUrl token server URL - * @param clientAuthentication client authentication or {@code null} for none (see - * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}) - * @param clientId client identifier - * @param authorizationServerEncodedUrl authorization server encoded URL - */ - public Builder(AccessMethod method, - HttpTransport transport, - JsonFactory jsonFactory, - GenericUrl tokenServerUrl, - HttpExecuteInterceptor clientAuthentication, - String clientId, - String authorizationServerEncodedUrl) { - setMethod(method); - setTransport(transport); - setJsonFactory(jsonFactory); - setTokenServerUrl(tokenServerUrl); - setClientAuthentication(clientAuthentication); - setClientId(clientId); - setAuthorizationServerEncodedUrl(authorizationServerEncodedUrl); - } - - /** Returns a new instance of an authorization code flow based on this builder. */ - public AuthorizationCodeFlow build() { - return new AuthorizationCodeFlow(this); - } - - /** - * Returns the method of presenting the access token to the resource server (for example - * {@link BearerToken#authorizationHeaderAccessMethod}). - */ - public final AccessMethod getMethod() { - return method; - } - - /** - * Sets the method of presenting the access token to the resource server (for example - * {@link BearerToken#authorizationHeaderAccessMethod}). - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * @since 1.11 - */ - public Builder setMethod(AccessMethod method) { - this.method = Preconditions.checkNotNull(method); - return this; - } - - /** Returns the HTTP transport. */ - public final HttpTransport getTransport() { - return transport; - } - - /** - * Sets the HTTP transport. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * @since 1.11 - */ - public Builder setTransport(HttpTransport transport) { - this.transport = Preconditions.checkNotNull(transport); - return this; - } - - /** Returns the JSON factory. */ - public final JsonFactory getJsonFactory() { - return jsonFactory; - } - - /** - * Sets the JSON factory. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * @since 1.11 - */ - public Builder setJsonFactory(JsonFactory jsonFactory) { - this.jsonFactory = Preconditions.checkNotNull(jsonFactory); - return this; - } - - /** Returns the token server URL. */ - public final GenericUrl getTokenServerUrl() { - return tokenServerUrl; - } - - /** - * Sets the token server URL. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * @since 1.11 - */ - public Builder setTokenServerUrl(GenericUrl tokenServerUrl) { - this.tokenServerUrl = Preconditions.checkNotNull(tokenServerUrl); - return this; - } - - /** - * Returns the client authentication or {@code null} for none (see - * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}). - */ - public final HttpExecuteInterceptor getClientAuthentication() { - return clientAuthentication; - } - - /** - * Sets the client authentication or {@code null} for none (see - * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}). - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * @since 1.11 - */ - public Builder setClientAuthentication(HttpExecuteInterceptor clientAuthentication) { - this.clientAuthentication = clientAuthentication; - return this; - } - - /** Returns the client identifier. */ - public final String getClientId() { - return clientId; - } - - /** - * Sets the client identifier. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * @since 1.11 - */ - public Builder setClientId(String clientId) { - this.clientId = Preconditions.checkNotNull(clientId); - return this; - } - - /** Returns the authorization server encoded URL. */ - public final String getAuthorizationServerEncodedUrl() { - return authorizationServerEncodedUrl; - } - - /** - * Sets the authorization server encoded URL. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * @since 1.11 - */ - public Builder setAuthorizationServerEncodedUrl(String authorizationServerEncodedUrl) { - this.authorizationServerEncodedUrl = - Preconditions.checkNotNull(authorizationServerEncodedUrl); - return this; - } - - /** - * {@link Beta}
- * Returns the credential persistence store or {@code null} for none. - * @deprecated (to be removed in the future) Use {@link #getCredentialDataStore()} instead. - */ - @Beta - @Deprecated - public final CredentialStore getCredentialStore() { - return credentialStore; - } - - /** - * {@link Beta}
- * Returns the stored credential data store or {@code null} for none. - * - * @since 1.16 - */ - @Beta - public final DataStore getCredentialDataStore() { - return credentialDataStore; - } - - /** - * Returns the clock passed along to the Credential or {@link Clock#SYSTEM} when system default - * is used. - * @since 1.9 - */ - public final Clock getClock() { - return clock; - } - - /** - * Sets the clock to pass to the Credential. - * - *

- * The default value for this parameter is {@link Clock#SYSTEM} - *

- * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * @since 1.9 - */ - public Builder setClock(Clock clock) { - this.clock = Preconditions.checkNotNull(clock); - return this; - } - - /** - * {@link Beta}
- * Sets the credential persistence store or {@code null} for none. - * - *

- * Warning: not compatible with {@link #setDataStoreFactory} or {@link #setCredentialDataStore}, - * and if either of those is called before this method is called, this method will throw an - * {@link IllegalArgumentException}. - *

- * - *

- *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @deprecated (to be removed in the future) Use - * {@link #setDataStoreFactory(DataStoreFactory)} or - * {@link #setCredentialDataStore(DataStore)} instead. - */ - @Beta - @Deprecated - public Builder setCredentialStore(CredentialStore credentialStore) { - Preconditions.checkArgument(credentialDataStore == null); - this.credentialStore = credentialStore; - return this; - } - - /** - * {@link Beta}
- * Sets the data store factory or {@code null} for none. - * - *

- * Warning: not compatible with {@link #setCredentialStore}, and if it is called before this - * method is called, this method will throw an {@link IllegalArgumentException}. - *

- * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.16 - */ - @Beta - public Builder setDataStoreFactory(DataStoreFactory dataStoreFactory) throws IOException { - return setCredentialDataStore(StoredCredential.getDefaultDataStore(dataStoreFactory)); - } - - /** - * {@link Beta}
- * Sets the stored credential data store or {@code null} for none. - * - *

- * Warning: not compatible with {@link #setCredentialStore}, and if it is called before this - * method is called, this method will throw an {@link IllegalArgumentException}. - *

- * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.16 - */ - @Beta - public Builder setCredentialDataStore(DataStore credentialDataStore) { - Preconditions.checkArgument(credentialStore == null); - this.credentialDataStore = credentialDataStore; - return this; - } - - /** Returns the HTTP request initializer or {@code null} for none. */ - public final HttpRequestInitializer getRequestInitializer() { - return requestInitializer; - } - - /** - * Sets the HTTP request initializer or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setRequestInitializer(HttpRequestInitializer requestInitializer) { - this.requestInitializer = requestInitializer; - return this; - } - - /** - * Sets the collection of scopes. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @param scopes collection of scopes - * @since 1.15 - */ - public Builder setScopes(Collection scopes) { - this.scopes = Preconditions.checkNotNull(scopes); - return this; - } - - /** Returns a collection of scopes. */ - public final Collection getScopes() { - return scopes; - } - - /** - * Sets the credential created listener or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.14 - */ - public Builder setCredentialCreatedListener( - CredentialCreatedListener credentialCreatedListener) { - this.credentialCreatedListener = credentialCreatedListener; - return this; - } - - /** - * Adds a listener for refresh token results. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @param refreshListener refresh listener - * @since 1.15 - */ - public Builder addRefreshListener(CredentialRefreshListener refreshListener) { - refreshListeners.add(Preconditions.checkNotNull(refreshListener)); - return this; - } - - /** - * Returns the listeners for refresh token results. - * - * @since 1.15 - */ - public final Collection getRefreshListeners() { - return refreshListeners; - } - - /** - * Sets the listeners for refresh token results. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.15 - */ - public Builder setRefreshListeners(Collection refreshListeners) { - this.refreshListeners = Preconditions.checkNotNull(refreshListeners); - return this; - } - - /** - * Returns the credential created listener or {@code null} for none. - * - * @since 1.14 - */ - public final CredentialCreatedListener getCredentialCreatedListener() { - return credentialCreatedListener; - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/AuthorizationCodeRequestUrl.java b/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/AuthorizationCodeRequestUrl.java deleted file mode 100644 index 0d704d79..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/AuthorizationCodeRequestUrl.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.oauth2; - -import java.util.Collection; -import java.util.Collections; - -/** - * OAuth 2.0 URL builder for an authorization web page to allow the end user to authorize the - * application to access their protected resources and that returns an authorization code, as - * specified in Authorization Code - * Grant. - * - *

- * The default for {@link #getResponseTypes()} is {@code "code"}. Use - * {@link AuthorizationCodeResponseUrl} to parse the redirect response after the end user - * grants/denies the request. Using the authorization code in this response, use - * {@link AuthorizationCodeTokenRequest} to request the access token. - *

- * - *

- * Sample usage for a web application: - *

- * - *
-  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
-    String url =
-        new AuthorizationCodeRequestUrl("https://server.example.com/authorize", "s6BhdRkqt3")
-            .setState("xyz").setRedirectUri("https://client.example.com/rd").build();
-    response.sendRedirect(url);
-  }
- * 
- * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.7 - * @author Yaniv Inbar - */ -public class AuthorizationCodeRequestUrl extends AuthorizationRequestUrl { - - /** - * @param authorizationServerEncodedUrl authorization server encoded URL - * @param clientId client identifier - */ - public AuthorizationCodeRequestUrl(String authorizationServerEncodedUrl, String clientId) { - super(authorizationServerEncodedUrl, clientId, Collections.singleton("code")); - } - - @Override - public AuthorizationCodeRequestUrl setResponseTypes(Collection responseTypes) { - return (AuthorizationCodeRequestUrl) super.setResponseTypes(responseTypes); - } - - @Override - public AuthorizationCodeRequestUrl setRedirectUri(String redirectUri) { - return (AuthorizationCodeRequestUrl) super.setRedirectUri(redirectUri); - } - - @Override - public AuthorizationCodeRequestUrl setScopes(Collection scopes) { - return (AuthorizationCodeRequestUrl) super.setScopes(scopes); - } - - @Override - public AuthorizationCodeRequestUrl setClientId(String clientId) { - return (AuthorizationCodeRequestUrl) super.setClientId(clientId); - } - - @Override - public AuthorizationCodeRequestUrl setState(String state) { - return (AuthorizationCodeRequestUrl) super.setState(state); - } - - @Override - public AuthorizationCodeRequestUrl set(String fieldName, Object value) { - return (AuthorizationCodeRequestUrl) super.set(fieldName, value); - } - - @Override - public AuthorizationCodeRequestUrl clone() { - return (AuthorizationCodeRequestUrl) super.clone(); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/AuthorizationCodeResponseUrl.java b/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/AuthorizationCodeResponseUrl.java deleted file mode 100644 index c2a74010..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/AuthorizationCodeResponseUrl.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.oauth2; - -import autosaveworld.zlibs.com.google.api.client.http.GenericUrl; -import autosaveworld.zlibs.com.google.api.client.util.Key; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * OAuth 2.0 URL parser for the redirect URL after end user grants or denies authorization as - * specified in Authorization - * Response. - * - *

- * Check if {@link #getError()} is {@code null} to check if the end-user granted authorization. - *

- * - *

- * Sample usage: - *

- * - *
-  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
-    StringBuffer fullUrlBuf = request.getRequestURL();
-    if (request.getQueryString() != null) {
-      fullUrlBuf.append('?').append(request.getQueryString());
-    }
-    AuthorizationCodeResponseUrl authResponse =
-        new AuthorizationCodeResponseUrl(fullUrlBuf.toString());
-    // check for user-denied error
-    if (authResponse.getError() != null) {
-      // authorization denied...
-    } else {
-      // request access token using authResponse.getCode()...
-    }
-  }
- * 
- * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.7 - * @author Yaniv Inbar - */ -public class AuthorizationCodeResponseUrl extends GenericUrl { - - /** Authorization code generated by the authorization server or {@code null} for none. */ - @Key - private String code; - - /** - * State parameter matching the state parameter in the authorization request or {@code null} for - * none. - */ - @Key - private String state; - - /** - * Error code ({@code "invalid_request"}, {@code "unauthorized_client"}, {@code "access_denied"}, - * {@code "unsupported_response_type"}, {@code "invalid_scope"}, {@code "server_error"}, - * {@code "temporarily_unavailable"}, or an extension error code as specified in Defining Additional Error Codes) or - * {@code null} for none. - */ - @Key - private String error; - - /** - * Human-readable text providing additional information used to assist the client developer in - * understanding the error that occurred or {@code null} for none. - */ - @Key("error_description") - private String errorDescription; - - /** - * URI identifying a human-readable web page with information about the error used to provide the - * client developer with additional information about the error or {@code null} for none. - */ - @Key("error_uri") - private String errorUri; - - /** - * @param encodedResponseUrl encoded authorization code response URL - */ - public AuthorizationCodeResponseUrl(String encodedResponseUrl) { - super(encodedResponseUrl); - // either error or code but not both - Preconditions.checkArgument((code == null) != (error == null)); - } - - /** - * Returns the authorization code generated by the authorization server or {@code null} for none. - */ - public final String getCode() { - return code; - } - - /** - * Sets the authorization code generated by the authorization server or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public AuthorizationCodeResponseUrl setCode(String code) { - this.code = code; - return this; - } - - /** - * Returns the state parameter matching the state parameter in the authorization request or - * {@code null} for none. - */ - public final String getState() { - return state; - } - - /** - * Sets the state parameter matching the state parameter in the authorization request or - * {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public AuthorizationCodeResponseUrl setState(String state) { - this.state = state; - return this; - } - - /** - * Returns the error code ({@code "invalid_request"}, {@code "unauthorized_client"}, - * {@code "access_denied"}, {@code "unsupported_response_type"}, {@code "invalid_scope"}, - * {@code "server_error"}, {@code "temporarily_unavailable"}, or an extension error code as - * specified in Defining Additional Error - * Codes) or {@code null} for none. - */ - public final String getError() { - return error; - } - - /** - * Sets the error code ({@code "invalid_request"}, {@code "unauthorized_client"}, - * {@code "access_denied"}, {@code "unsupported_response_type"}, {@code "invalid_scope"}, - * {@code "server_error"}, {@code "temporarily_unavailable"}, or an extension error code as - * specified in Defining Additional Error - * Codes) or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public AuthorizationCodeResponseUrl setError(String error) { - this.error = error; - return this; - } - - /** - * Returns the human-readable text providing additional information used to assist the client - * developer in understanding the error that occurred or {@code null} for none. - */ - public final String getErrorDescription() { - return errorDescription; - } - - /** - * Sets the human-readable text providing additional information used to assist the client - * developer in understanding the error that occurred or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public AuthorizationCodeResponseUrl setErrorDescription(String errorDescription) { - this.errorDescription = errorDescription; - return this; - } - - /** - * Returns the URI identifying a human-readable web page with information about the error used to - * provide the client developer with additional information about the error or {@code null} for - * none. - */ - public final String getErrorUri() { - return errorUri; - } - - /** - * Sets the URI identifying a human-readable web page with information about the error used to - * provide the client developer with additional information about the error or {@code null} for - * none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public AuthorizationCodeResponseUrl setErrorUri(String errorUri) { - this.errorUri = errorUri; - return this; - } - - @Override - public AuthorizationCodeResponseUrl set(String fieldName, Object value) { - return (AuthorizationCodeResponseUrl) super.set(fieldName, value); - } - - @Override - public AuthorizationCodeResponseUrl clone() { - return (AuthorizationCodeResponseUrl) super.clone(); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/AuthorizationCodeTokenRequest.java b/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/AuthorizationCodeTokenRequest.java deleted file mode 100644 index e896f8c2..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/AuthorizationCodeTokenRequest.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.oauth2; - -import java.util.Collection; - -import autosaveworld.zlibs.com.google.api.client.http.GenericUrl; -import autosaveworld.zlibs.com.google.api.client.http.HttpExecuteInterceptor; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequestInitializer; -import autosaveworld.zlibs.com.google.api.client.http.HttpTransport; -import autosaveworld.zlibs.com.google.api.client.json.JsonFactory; -import autosaveworld.zlibs.com.google.api.client.util.Key; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * OAuth 2.0 request for an access token using an authorization code as specified in Access Token Request. - * - *

- * Use {@link Credential} to access protected resources from the resource server using the - * {@link TokenResponse} returned by {@link #execute()}. On error, it will instead throw - * {@link TokenResponseException}. - *

- * - *

- * Sample usage: - *

- * - *
-  static void requestAccessToken() throws IOException {
-    try {
-      TokenResponse response =
-          new AuthorizationCodeTokenRequest(new NetHttpTransport(), new JacksonFactory(),
-              new GenericUrl("https://server.example.com/token"), "SplxlOBeZQQYbYS6WxSbIA")
-              .setRedirectUri("https://client.example.com/rd")
-              .setClientAuthentication(
-                  new BasicAuthentication("s6BhdRkqt3", "7Fjfp0ZBr1KtDRbnfVdmIw")).execute();
-      System.out.println("Access token: " + response.getAccessToken());
-    } catch (TokenResponseException e) {
-      if (e.getDetails() != null) {
-        System.err.println("Error: " + e.getDetails().getError());
-        if (e.getDetails().getErrorDescription() != null) {
-          System.err.println(e.getDetails().getErrorDescription());
-        }
-        if (e.getDetails().getErrorUri() != null) {
-          System.err.println(e.getDetails().getErrorUri());
-        }
-      } else {
-        System.err.println(e.getMessage());
-      }
-    }
-  }
- * 
- * - *

- * Some OAuth 2.0 providers don't support {@link BasicAuthentication} but instead support - * {@link ClientParametersAuthentication}. In the above sample code, simply replace the class name - * and it will work the same way. - *

- * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.7 - * @author Yaniv Inbar - */ -public class AuthorizationCodeTokenRequest extends TokenRequest { - - /** Authorization code received from the authorization server. */ - @Key - private String code; - - /** - * Redirect URI parameter matching the redirect URI parameter in the authorization request or - * {@code null} for none. - */ - @Key("redirect_uri") - private String redirectUri; - - /** - * @param transport HTTP transport - * @param jsonFactory JSON factory - * @param tokenServerUrl token server URL - * @param code authorization code generated by the authorization server - */ - public AuthorizationCodeTokenRequest( - HttpTransport transport, JsonFactory jsonFactory, GenericUrl tokenServerUrl, String code) { - super(transport, jsonFactory, tokenServerUrl, "authorization_code"); - setCode(code); - } - - @Override - public AuthorizationCodeTokenRequest setRequestInitializer( - HttpRequestInitializer requestInitializer) { - return (AuthorizationCodeTokenRequest) super.setRequestInitializer(requestInitializer); - } - - @Override - public AuthorizationCodeTokenRequest setTokenServerUrl(GenericUrl tokenServerUrl) { - return (AuthorizationCodeTokenRequest) super.setTokenServerUrl(tokenServerUrl); - } - - @Override - public AuthorizationCodeTokenRequest setScopes(Collection scopes) { - return (AuthorizationCodeTokenRequest) super.setScopes(scopes); - } - - @Override - public AuthorizationCodeTokenRequest setGrantType(String grantType) { - return (AuthorizationCodeTokenRequest) super.setGrantType(grantType); - } - - @Override - public AuthorizationCodeTokenRequest setClientAuthentication( - HttpExecuteInterceptor clientAuthentication) { - return (AuthorizationCodeTokenRequest) super.setClientAuthentication(clientAuthentication); - } - - /** Returns the authorization code generated by the authorization server. */ - public final String getCode() { - return code; - } - - /** - * Sets the authorization code generated by the authorization server. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public AuthorizationCodeTokenRequest setCode(String code) { - this.code = Preconditions.checkNotNull(code); - return this; - } - - /** - * Returns the redirect URI parameter matching the redirect URI parameter in the authorization - * request or {@code null} for none. - */ - public final String getRedirectUri() { - return redirectUri; - } - - /** - * Sets the redirect URI parameter matching the redirect URI parameter in the authorization - * request or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public AuthorizationCodeTokenRequest setRedirectUri(String redirectUri) { - this.redirectUri = redirectUri; - return this; - } - - @Override - public AuthorizationCodeTokenRequest set(String fieldName, Object value) { - return (AuthorizationCodeTokenRequest) super.set(fieldName, value); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/AuthorizationRequestUrl.java b/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/AuthorizationRequestUrl.java deleted file mode 100644 index a41ffd2b..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/AuthorizationRequestUrl.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.oauth2; - -import java.util.Collection; - -import autosaveworld.zlibs.com.google.api.client.http.GenericUrl; -import autosaveworld.zlibs.com.google.api.client.util.Joiner; -import autosaveworld.zlibs.com.google.api.client.util.Key; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * OAuth 2.0 URL builder for an authorization web page to allow the end user to authorize the - * application to access their protected resources, as specified in Authorization Endpoint. - * - *

- * Sample usage for a web application: - *

- * - *
-  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
-    String url = new AuthorizationRequestUrl(
-        "https://server.example.com/authorize", "s6BhdRkqt3", Arrays.asList("code")).setState("xyz")
-        .setRedirectUri("https://client.example.com/rd").build();
-    response.sendRedirect(url);
-  }
- * 
- * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.7 - * @author Yaniv Inbar - */ -public class AuthorizationRequestUrl extends GenericUrl { - - /** - * Response type, which must be - * {@code "code"} for requesting an authorization code, {@code "token"} for requesting an access - * token (implicit grant), or space-separated registered extension values. - */ - @Key("response_type") - private String responseTypes; - - /** - * URI that the authorization server directs the resource owner's user-agent back to the client - * after a successful authorization grant (as specified in Redirection Endpoint) or - * {@code null} for none. - */ - @Key("redirect_uri") - private String redirectUri; - - /** - * Space-separated list of scopes (as specified in Access Token Scope) or {@code null} - * for none. - */ - @Key("scope") - private String scopes; - - /** Client identifier. */ - @Key("client_id") - private String clientId; - - /** - * State (an opaque value used by the client to maintain state between the request and callback, - * as mentioned in Registration - * Requirements) or {@code null} for none. - */ - @Key - private String state; - - /** - * @param authorizationServerEncodedUrl authorization server encoded URL - * @param clientId client identifier - * @param responseTypes response - * type, which must be {@code "code"} for requesting an authorization code, - * {@code "token"} for requesting an access token (implicit grant), or a list of registered - * extension values to join with a space - * @since 1.15 - */ - public AuthorizationRequestUrl( - String authorizationServerEncodedUrl, String clientId, Collection responseTypes) { - super(authorizationServerEncodedUrl); - Preconditions.checkArgument(getFragment() == null); - setClientId(clientId); - setResponseTypes(responseTypes); - } - - /** - * Returns the Response type, which - * must be {@code "code"} for requesting an authorization code, {@code "token"} for requesting an - * access token (implicit grant), or space-separated registered extension values. - */ - public final String getResponseTypes() { - return responseTypes; - } - - /** - * Sets the response type, which - * must be {@code "code"} for requesting an authorization code, {@code "token"} for requesting an - * access token (implicit grant), or a list of registered extension values to join with a space. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.15 - */ - public AuthorizationRequestUrl setResponseTypes(Collection responseTypes) { - this.responseTypes = Joiner.on(' ').join(responseTypes); - return this; - } - - /** - * Returns the URI that the authorization server directs the resource owner's user-agent back to - * the client after a successful authorization grant (as specified in Redirection Endpoint) or - * {@code null} for none. - */ - public final String getRedirectUri() { - return redirectUri; - } - - /** - * Sets the URI that the authorization server directs the resource owner's user-agent back to the - * client after a successful authorization grant (as specified in Redirection Endpoint) or - * {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public AuthorizationRequestUrl setRedirectUri(String redirectUri) { - this.redirectUri = redirectUri; - return this; - } - - /** - * Returns the space-separated list of scopes (as specified in Access Token Scope) or {@code null} - * for none. - */ - public final String getScopes() { - return scopes; - } - - /** - * Sets the list of scopes (as specified in Access Token Scope) or {@code null} - * for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @param scopes collection of scopes to be joined by a space separator (or a single value - * containing multiple space-separated scopes) or {@code null} for none - * @since 1.15 - */ - public AuthorizationRequestUrl setScopes(Collection scopes) { - this.scopes = - scopes == null || !scopes.iterator().hasNext() ? null : Joiner.on(' ').join(scopes); - return this; - } - - /** Returns the client identifier. */ - public final String getClientId() { - return clientId; - } - - /** - * Sets the client identifier. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public AuthorizationRequestUrl setClientId(String clientId) { - this.clientId = Preconditions.checkNotNull(clientId); - return this; - } - - /** - * Returns the state (an opaque value used by the client to maintain state between the request and - * callback, as mentioned in Registration Requirements) or - * {@code null} for none. - */ - public final String getState() { - return state; - } - - /** - * Sets the state (an opaque value used by the client to maintain state between the request and - * callback, as mentioned in Registration Requirements) or - * {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public AuthorizationRequestUrl setState(String state) { - this.state = state; - return this; - } - - @Override - public AuthorizationRequestUrl set(String fieldName, Object value) { - return (AuthorizationRequestUrl) super.set(fieldName, value); - } - - @Override - public AuthorizationRequestUrl clone() { - return (AuthorizationRequestUrl) super.clone(); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/BearerToken.java b/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/BearerToken.java deleted file mode 100644 index ea09a3b8..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/BearerToken.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.oauth2; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.regex.Pattern; - -import autosaveworld.zlibs.com.google.api.client.http.HttpMethods; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequest; -import autosaveworld.zlibs.com.google.api.client.http.UrlEncodedContent; -import autosaveworld.zlibs.com.google.api.client.util.Data; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * OAuth 2.0 helper for accessing protected resources using the Bearer Token specification. - * - * @since 1.7 - * @author Yaniv Inbar - */ -public class BearerToken { - - /** Query and form-encoded parameter name. */ - static final String PARAM_NAME = "access_token"; - - /** - * In case an abnormal HTTP response is received with {@code WWW-Authenticate} header, and its - * value contains this error pattern, we will try to refresh the token. - */ - static final Pattern INVALID_TOKEN_ERROR = - Pattern.compile("\\s*error\\s*=\\s*\"?invalid_token\"?"); - - /** - * Immutable and thread-safe OAuth 2.0 method for accessing protected resources using the Authorization Request Header Field. - * - *

- * According to the specification, this method MUST be supported by resource servers. - *

- */ - static final class AuthorizationHeaderAccessMethod implements Credential.AccessMethod { - - /** Authorization header prefix. */ - static final String HEADER_PREFIX = "Bearer "; - - AuthorizationHeaderAccessMethod() { - } - - public void intercept(HttpRequest request, String accessToken) throws IOException { - request.getHeaders().setAuthorization(HEADER_PREFIX + accessToken); - } - - public String getAccessTokenFromRequest(HttpRequest request) { - List authorizationAsList = request.getHeaders().getAuthorizationAsList(); - if (authorizationAsList != null) { - for (String header : authorizationAsList) { - if (header.startsWith(HEADER_PREFIX)) { - return header.substring(HEADER_PREFIX.length()); - } - } - } - return null; - } - } - - /** - * Immutable and thread-safe OAuth 2.0 method for accessing protected resources using the Form-Encoded Body Parameter. - */ - static final class FormEncodedBodyAccessMethod implements Credential.AccessMethod { - - FormEncodedBodyAccessMethod() { - } - - public void intercept(HttpRequest request, String accessToken) throws IOException { - Preconditions.checkArgument( - !HttpMethods.GET.equals(request.getRequestMethod()), "HTTP GET method is not supported"); - getData(request).put(PARAM_NAME, accessToken); - } - - public String getAccessTokenFromRequest(HttpRequest request) { - Object bodyParam = getData(request).get(PARAM_NAME); - return bodyParam == null ? null : bodyParam.toString(); - } - - private static Map getData(HttpRequest request) { - return Data.mapOf(UrlEncodedContent.getContent(request).getData()); - } - } - - /** - * Immutable and thread-safe OAuth 2.0 method for accessing protected resources using the URI Query Parameter. - */ - static final class QueryParameterAccessMethod implements Credential.AccessMethod { - - QueryParameterAccessMethod() { - } - - public void intercept(HttpRequest request, String accessToken) throws IOException { - request.getUrl().set(PARAM_NAME, accessToken); - } - - public String getAccessTokenFromRequest(HttpRequest request) { - Object param = request.getUrl().get(PARAM_NAME); - return param == null ? null : param.toString(); - } - } - - /** - * Returns a new instance of an immutable and thread-safe OAuth 2.0 method for accessing protected - * resources using the Authorization - * Request Header Field. - * - *

- * According to the specification, this method MUST be supported by resource servers. - *

- */ - public static Credential.AccessMethod authorizationHeaderAccessMethod() { - return new AuthorizationHeaderAccessMethod(); - } - - /** - * Returns a new instance of an immutable and thread-safe OAuth 2.0 method for accessing protected - * resources using the Form-Encoded Body - * Parameter. - */ - public static Credential.AccessMethod formEncodedBodyAccessMethod() { - return new FormEncodedBodyAccessMethod(); - } - - /** - * Returns a new instance of an immutable and thread-safe OAuth 2.0 method for accessing protected - * resources using the URI Query - * Parameter. - */ - public static Credential.AccessMethod queryParameterAccessMethod() { - return new QueryParameterAccessMethod(); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/BrowserClientRequestUrl.java b/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/BrowserClientRequestUrl.java deleted file mode 100644 index 0a91678a..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/BrowserClientRequestUrl.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.oauth2; - -import java.util.Collection; -import java.util.Collections; - -/** - * OAuth 2.0 URL builder for an authorization web page to allow the end user to authorize the - * application to access their protected resources and that returns the access token to a browser - * client using a scripting language such as JavaScript, as specified in Implicit Grant. - * - *

- * The default for {@link #getResponseTypes()} is {@code "token"}. - *

- * - *

- * Sample usage for a web application: - *

- * - *
-  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
-    String url = new BrowserClientRequestUrl(
-        "https://server.example.com/authorize", "s6BhdRkqt3").setState("xyz")
-        .setRedirectUri("https://client.example.com/cb").build();
-    response.sendRedirect(url);
-  }
- * 
- * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.7 - * @author Yaniv Inbar - */ -public class BrowserClientRequestUrl extends AuthorizationRequestUrl { - - /** - * @param encodedAuthorizationServerUrl encoded authorization server URL - * @param clientId client identifier - */ - public BrowserClientRequestUrl(String encodedAuthorizationServerUrl, String clientId) { - super(encodedAuthorizationServerUrl, clientId, Collections.singleton("token")); - } - - @Override - public BrowserClientRequestUrl setResponseTypes(Collection responseTypes) { - return (BrowserClientRequestUrl) super.setResponseTypes(responseTypes); - } - - @Override - public BrowserClientRequestUrl setRedirectUri(String redirectUri) { - return (BrowserClientRequestUrl) super.setRedirectUri(redirectUri); - } - - @Override - public BrowserClientRequestUrl setScopes(Collection scopes) { - return (BrowserClientRequestUrl) super.setScopes(scopes); - } - - @Override - public BrowserClientRequestUrl setClientId(String clientId) { - return (BrowserClientRequestUrl) super.setClientId(clientId); - } - - @Override - public BrowserClientRequestUrl setState(String state) { - return (BrowserClientRequestUrl) super.setState(state); - } - - @Override - public BrowserClientRequestUrl set(String fieldName, Object value) { - return (BrowserClientRequestUrl) super.set(fieldName, value); - } - - @Override - public BrowserClientRequestUrl clone() { - return (BrowserClientRequestUrl) super.clone(); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/ClientCredentialsTokenRequest.java b/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/ClientCredentialsTokenRequest.java deleted file mode 100644 index cb85e9c6..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/ClientCredentialsTokenRequest.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.oauth2; - -import java.util.Collection; - -import autosaveworld.zlibs.com.google.api.client.http.GenericUrl; -import autosaveworld.zlibs.com.google.api.client.http.HttpExecuteInterceptor; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequestInitializer; -import autosaveworld.zlibs.com.google.api.client.http.HttpTransport; -import autosaveworld.zlibs.com.google.api.client.json.JsonFactory; - -/** - * OAuth 2.0 request for an access token using only its client credentials as specified in Client Credentials Grant. - * - *

- * Use {@link Credential} to access protected resources from the resource server using the - * {@link TokenResponse} returned by {@link #execute()}. On error, it will instead throw - * {@link TokenResponseException}. - *

- * - *

- * Sample usage: - *

- * - *
-  static void requestAccessToken() throws IOException {
-    try {
-      TokenResponse response =
-          new ClientCredentialsTokenRequest(new NetHttpTransport(), new JacksonFactory(),
-              new GenericUrl("https://server.example.com/token"))
-              .setRedirectUri("https://client.example.com/rd")
-              .setClientAuthentication(
-                  new BasicAuthentication("s6BhdRkqt3", "7Fjfp0ZBr1KtDRbnfVdmIw")).execute();
-      System.out.println("Access token: " + response.getAccessToken());
-    } catch (TokenResponseException e) {
-      if (e.getDetails() != null) {
-        System.err.println("Error: " + e.getDetails().getError());
-        if (e.getDetails().getErrorDescription() != null) {
-          System.err.println(e.getDetails().getErrorDescription());
-        }
-        if (e.getDetails().getErrorUri() != null) {
-          System.err.println(e.getDetails().getErrorUri());
-        }
-      } else {
-        System.err.println(e.getMessage());
-      }
-    }
-  }
- * 
- * - *

- * Some OAuth 2.0 providers don't support {@link BasicAuthentication} but instead support - * {@link ClientParametersAuthentication}. In the above sample code, simply replace the class name - * and it will work the same way. - *

- * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.14 - * @author Yaniv Inbar - */ -public class ClientCredentialsTokenRequest extends TokenRequest { - - /** - * @param transport HTTP transport - * @param jsonFactory JSON factory - * @param tokenServerUrl token server URL - */ - public ClientCredentialsTokenRequest( - HttpTransport transport, JsonFactory jsonFactory, GenericUrl tokenServerUrl) { - super(transport, jsonFactory, tokenServerUrl, "client_credentials"); - } - - @Override - public ClientCredentialsTokenRequest setRequestInitializer( - HttpRequestInitializer requestInitializer) { - return (ClientCredentialsTokenRequest) super.setRequestInitializer(requestInitializer); - } - - @Override - public ClientCredentialsTokenRequest setTokenServerUrl(GenericUrl tokenServerUrl) { - return (ClientCredentialsTokenRequest) super.setTokenServerUrl(tokenServerUrl); - } - - @Override - public ClientCredentialsTokenRequest setScopes(Collection scopes) { - return (ClientCredentialsTokenRequest) super.setScopes(scopes); - } - - @Override - public ClientCredentialsTokenRequest setGrantType(String grantType) { - return (ClientCredentialsTokenRequest) super.setGrantType(grantType); - } - - @Override - public ClientCredentialsTokenRequest setClientAuthentication( - HttpExecuteInterceptor clientAuthentication) { - return (ClientCredentialsTokenRequest) super.setClientAuthentication(clientAuthentication); - } - - @Override - public ClientCredentialsTokenRequest set(String fieldName, Object value) { - return (ClientCredentialsTokenRequest) super.set(fieldName, value); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/ClientParametersAuthentication.java b/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/ClientParametersAuthentication.java deleted file mode 100644 index 3e739103..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/ClientParametersAuthentication.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.oauth2; - -import java.io.IOException; -import java.util.Map; - -import autosaveworld.zlibs.com.google.api.client.http.HttpExecuteInterceptor; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequest; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequestInitializer; -import autosaveworld.zlibs.com.google.api.client.http.UrlEncodedContent; -import autosaveworld.zlibs.com.google.api.client.util.Data; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * Client credentials specified as URL-encoded parameters in the HTTP request body as specified in - * Client Password - * - *

- * This implementation assumes that the {@link HttpRequest#getContent()} is {@code null} or an - * instance of {@link UrlEncodedContent}. This is used as the client authentication in - * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}. - *

- * - *

- * Sample usage: - *

- * - *
-  static void requestAccessToken() throws IOException {
-    try {
-      TokenResponse response = new AuthorizationCodeTokenRequest(new NetHttpTransport(),
-          new JacksonFactory(), new GenericUrl("https://server.example.com/token"),
-          "SplxlOBeZQQYbYS6WxSbIA").setRedirectUri("https://client.example.com/rd")
-          .setClientAuthentication(
-              new ClientParametersAuthentication("s6BhdRkqt3", "7Fjfp0ZBr1KtDRbnfVdmIw")).execute();
-      System.out.println("Access token: " + response.getAccessToken());
-    } catch (TokenResponseException e) {
-      if (e.getDetails() != null) {
-        System.err.println("Error: " + e.getDetails().getError());
-        if (e.getDetails().getErrorDescription() != null) {
-          System.err.println(e.getDetails().getErrorDescription());
-        }
-        if (e.getDetails().getErrorUri() != null) {
-          System.err.println(e.getDetails().getErrorUri());
-        }
-      } else {
-        System.err.println(e.getMessage());
-      }
-    }
-  }
- * 
- * - *

- * Implementation is immutable and thread-safe. - *

- * - * @since 1.7 - * @author Yaniv Inbar - */ -public class ClientParametersAuthentication - implements - HttpRequestInitializer, - HttpExecuteInterceptor { - - /** Client identifier issued to the client during the registration process. */ - private final String clientId; - - /** Client secret or {@code null} for none. */ - private final String clientSecret; - - /** - * @param clientId client identifier issued to the client during the registration process - * @param clientSecret client secret or {@code null} for none - */ - public ClientParametersAuthentication(String clientId, String clientSecret) { - this.clientId = Preconditions.checkNotNull(clientId); - this.clientSecret = clientSecret; - } - - public void initialize(HttpRequest request) throws IOException { - request.setInterceptor(this); - } - - public void intercept(HttpRequest request) throws IOException { - Map data = Data.mapOf(UrlEncodedContent.getContent(request).getData()); - data.put("client_id", clientId); - if (clientSecret != null) { - data.put("client_secret", clientSecret); - } - } - - /** Returns the client identifier issued to the client during the registration process. */ - public final String getClientId() { - return clientId; - } - - /** Returns the client secret or {@code null} for none. */ - public final String getClientSecret() { - return clientSecret; - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/Credential.java b/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/Credential.java deleted file mode 100644 index 6df72e54..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/Credential.java +++ /dev/null @@ -1,823 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.oauth2; - -import java.io.IOException; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; -import java.util.logging.Level; -import java.util.logging.Logger; - -import autosaveworld.zlibs.com.google.api.client.http.GenericUrl; -import autosaveworld.zlibs.com.google.api.client.http.HttpExecuteInterceptor; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequest; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequestInitializer; -import autosaveworld.zlibs.com.google.api.client.http.HttpResponse; -import autosaveworld.zlibs.com.google.api.client.http.HttpStatusCodes; -import autosaveworld.zlibs.com.google.api.client.http.HttpTransport; -import autosaveworld.zlibs.com.google.api.client.http.HttpUnsuccessfulResponseHandler; -import autosaveworld.zlibs.com.google.api.client.json.JsonFactory; -import autosaveworld.zlibs.com.google.api.client.util.Clock; -import autosaveworld.zlibs.com.google.api.client.util.Lists; -import autosaveworld.zlibs.com.google.api.client.util.Objects; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.store.DataStoreFactory; - -/** - * Thread-safe OAuth 2.0 helper for accessing protected resources using an access token, as well as - * optionally refreshing the access token when it expires using a refresh token. - * - *

- * Sample usage: - *

- * - *
-  public static Credential createCredentialWithAccessTokenOnly(
-      HttpTransport transport, JsonFactory jsonFactory, TokenResponse tokenResponse) {
-    return new Credential(BearerToken.authorizationHeaderAccessMethod()).setFromTokenResponse(
-        tokenResponse);
-  }
-
-  public static Credential createCredentialWithRefreshToken(
-      HttpTransport transport, JsonFactory jsonFactory, TokenResponse tokenResponse) {
-    return new Credential.Builder(BearerToken.authorizationHeaderAccessMethod()).setTransport(
-        transport)
-        .setJsonFactory(jsonFactory)
-        .setTokenServerUrl(
-            new GenericUrl("https://server.example.com/token"))
-        .setClientAuthentication(new BasicAuthentication("s6BhdRkqt3", "7Fjfp0ZBr1KtDRbnfVdmIw"))
-        .build()
-        .setFromTokenResponse(tokenResponse);
-  }
- * 
- * - *

- * If you need to persist the access token in a data store, use {@link DataStoreFactory} and - * {@link Builder#addRefreshListener(CredentialRefreshListener)} with - * {@link DataStoreCredentialRefreshListener}. - *

- * - *

- * If you have a custom request initializer, request execute interceptor, or unsuccessful response - * handler, take a look at the sample usage for {@link HttpExecuteInterceptor} and - * {@link HttpUnsuccessfulResponseHandler}, which are interfaces that this class also implements. - *

- * - * @since 1.7 - * @author Yaniv Inbar - */ -public class Credential - implements - HttpExecuteInterceptor, - HttpRequestInitializer, - HttpUnsuccessfulResponseHandler { - - static final Logger LOGGER = Logger.getLogger(Credential.class.getName()); - - /** - * Method of presenting the access token to the resource server as specified in Accessing Protected Resources. - */ - public interface AccessMethod { - - /** - * Intercept the HTTP request during {@link Credential#intercept(HttpRequest)} right before the - * HTTP request executes by providing the access token. - * - * @param request HTTP request - * @param accessToken access token - */ - void intercept(HttpRequest request, String accessToken) throws IOException; - - /** - * Retrieve the original access token in the HTTP request, as provided in - * {@link #intercept(HttpRequest, String)}. - * - * @param request HTTP request - * @return original access token or {@code null} for none - */ - String getAccessTokenFromRequest(HttpRequest request); - } - - /** Lock on the token response information. */ - private final Lock lock = new ReentrantLock(); - - /** - * Method of presenting the access token to the resource server (for example - * {@link BearerToken.AuthorizationHeaderAccessMethod}). - */ - private final AccessMethod method; - - /** Clock used to provide the currentMillis. */ - private final Clock clock; - - /** Access token issued by the authorization server. */ - private String accessToken; - - /** - * Expected expiration time in milliseconds based on {@link #setExpiresInSeconds} or {@code null} - * for none. - */ - private Long expirationTimeMilliseconds; - - /** - * Refresh token which can be used to obtain new access tokens using the same authorization grant - * or {@code null} for none. - */ - private String refreshToken; - - /** HTTP transport for executing refresh token request or {@code null} for none. */ - private final HttpTransport transport; - - /** Client authentication or {@code null} for none. */ - private final HttpExecuteInterceptor clientAuthentication; - - /** - * JSON factory to use for parsing response for refresh token request or {@code null} for none. - */ - private final JsonFactory jsonFactory; - - /** Encoded token server URL or {@code null} for none. */ - private final String tokenServerEncodedUrl; - - /** Unmodifiable collection of listeners for refresh token results. */ - private final Collection refreshListeners; - - /** - * HTTP request initializer for refresh token requests to the token server or {@code null} for - * none. - */ - private final HttpRequestInitializer requestInitializer; - - /** - * Constructor with the ability to access protected resources, but not refresh tokens. - * - *

- * To use with the ability to refresh tokens, use {@link Builder}. - *

- * - * @param method method of presenting the access token to the resource server (for example - * {@link BearerToken.AuthorizationHeaderAccessMethod}) - */ - public Credential(AccessMethod method) { - this(new Builder(method)); - } - - /** - * @param builder credential builder - * - * @since 1.14 - */ - protected Credential(Builder builder) { - method = Preconditions.checkNotNull(builder.method); - transport = builder.transport; - jsonFactory = builder.jsonFactory; - tokenServerEncodedUrl = builder.tokenServerUrl == null ? null : builder.tokenServerUrl.build(); - clientAuthentication = builder.clientAuthentication; - requestInitializer = builder.requestInitializer; - refreshListeners = Collections.unmodifiableCollection(builder.refreshListeners); - clock = Preconditions.checkNotNull(builder.clock); - } - - /** - * {@inheritDoc} - *

- * Default implementation is to try to refresh the access token if there is no access token or if - * we are 1 minute away from expiration. If token server is unavailable, it will try to use the - * access token even if has expired. If a 4xx error is encountered while refreshing the token, - * {@link TokenResponseException} is thrown. If successful, it will call {@link #getMethod()} and - * {@link AccessMethod#intercept}. - *

- * - *

- * Subclasses may override. - *

- */ - public void intercept(HttpRequest request) throws IOException { - lock.lock(); - try { - Long expiresIn = getExpiresInSeconds(); - // check if token will expire in a minute - if (accessToken == null || expiresIn != null && expiresIn <= 60) { - refreshToken(); - if (accessToken == null) { - // nothing we can do without an access token - return; - } - } - method.intercept(request, accessToken); - } finally { - lock.unlock(); - } - } - - /** - * {@inheritDoc} - *

- * Default implementation checks if {@code WWW-Authenticate} exists and contains a "Bearer" value - * (see rfc6750 section 3.1 for more - * details). If so, it calls {@link #refreshToken} in case the error code contains - * {@code invalid_token}. If there is no "Bearer" in {@code WWW-Authenticate} and the status code - * is {@link HttpStatusCodes#STATUS_CODE_UNAUTHORIZED} it calls {@link #refreshToken}. If - * {@link #executeRefreshToken()} throws an I/O exception, this implementation will log the - * exception and return {@code false}. Subclasses may override. - *

- */ - public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry) { - boolean refreshToken = false; - boolean bearer = false; - - List authenticateList = response.getHeaders().getAuthenticateAsList(); - - // TODO(peleyal): this logic should be implemented as a pluggable interface, in the same way we - // implement different AccessMethods - - // if authenticate list is not null we will check if one of the entries contains "Bearer" - if (authenticateList != null) { - for (String authenticate : authenticateList) { - if (authenticate.startsWith(BearerToken.AuthorizationHeaderAccessMethod.HEADER_PREFIX)) { - // mark that we found a "Bearer" value, and check if there is a invalid_token error - bearer = true; - refreshToken = BearerToken.INVALID_TOKEN_ERROR.matcher(authenticate).find(); - break; - } - } - } - - // if "Bearer" wasn't found, we will refresh the token, if we got 401 - if (!bearer) { - refreshToken = response.getStatusCode() == HttpStatusCodes.STATUS_CODE_UNAUTHORIZED; - } - - if (refreshToken) { - try { - lock.lock(); - try { - // need to check if another thread has already refreshed the token - return !Objects.equal(accessToken, method.getAccessTokenFromRequest(request)) - || refreshToken(); - } finally { - lock.unlock(); - } - } catch (IOException exception) { - LOGGER.log(Level.SEVERE, "unable to refresh token", exception); - } - } - return false; - } - - public void initialize(HttpRequest request) throws IOException { - request.setInterceptor(this); - request.setUnsuccessfulResponseHandler(this); - } - - /** Returns the access token or {@code null} for none. */ - public final String getAccessToken() { - lock.lock(); - try { - return accessToken; - } finally { - lock.unlock(); - } - } - - /** - * Sets the access token. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @param accessToken access token or {@code null} for none - */ - public Credential setAccessToken(String accessToken) { - lock.lock(); - try { - this.accessToken = accessToken; - } finally { - lock.unlock(); - } - return this; - } - - /** - * Return the method of presenting the access token to the resource server (for example - * {@link BearerToken.AuthorizationHeaderAccessMethod}). - */ - public final AccessMethod getMethod() { - return method; - } - - /** - * Returns the clock used for expiration checks by this Credential. Mostly used for unit-testing. - * @since 1.9 - */ - public final Clock getClock() { - return clock; - } - - /** Return the HTTP transport for executing refresh token request or {@code null} for none. */ - public final HttpTransport getTransport() { - return transport; - } - - /** - * Returns the JSON factory to use for parsing response for refresh token request or {@code null} - * for none. - */ - public final JsonFactory getJsonFactory() { - return jsonFactory; - } - - /** Returns the encoded authorization server URL or {@code null} for none. */ - public final String getTokenServerEncodedUrl() { - return tokenServerEncodedUrl; - } - - /** - * Returns the refresh token associated with the access token to be refreshed or {@code null} for - * none. - */ - public final String getRefreshToken() { - lock.lock(); - try { - return refreshToken; - } finally { - lock.unlock(); - } - } - - /** - * Sets the refresh token. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @param refreshToken refresh token or {@code null} for none - */ - public Credential setRefreshToken(String refreshToken) { - lock.lock(); - try { - if (refreshToken != null) { - Preconditions.checkArgument(jsonFactory != null && transport != null - && clientAuthentication != null && tokenServerEncodedUrl != null, - "Please use the Builder and call setJsonFactory, setTransport, setClientAuthentication" - + " and setTokenServerUrl/setTokenServerEncodedUrl"); - } - this.refreshToken = refreshToken; - } finally { - lock.unlock(); - } - return this; - } - - /** Expected expiration time in milliseconds or {@code null} for none. */ - public final Long getExpirationTimeMilliseconds() { - lock.lock(); - try { - return expirationTimeMilliseconds; - } finally { - lock.unlock(); - } - } - - /** - * Sets the expected expiration time in milliseconds or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Credential setExpirationTimeMilliseconds(Long expirationTimeMilliseconds) { - lock.lock(); - try { - this.expirationTimeMilliseconds = expirationTimeMilliseconds; - } finally { - lock.unlock(); - } - return this; - } - - /** - * Returns the remaining lifetime in seconds of the access token (for example 3600 for an hour, or - * -3600 if expired an hour ago) or {@code null} if unknown. - */ - public final Long getExpiresInSeconds() { - lock.lock(); - try { - if (expirationTimeMilliseconds == null) { - return null; - } - return (expirationTimeMilliseconds - clock.currentTimeMillis()) / 1000; - } finally { - lock.unlock(); - } - } - - /** - * Sets the lifetime in seconds of the access token (for example 3600 for an hour) or {@code null} - * for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @param expiresIn lifetime in seconds of the access token (for example 3600 for an hour) or - * {@code null} for none - */ - public Credential setExpiresInSeconds(Long expiresIn) { - return setExpirationTimeMilliseconds( - expiresIn == null ? null : clock.currentTimeMillis() + expiresIn * 1000); - } - - /** Returns the client authentication or {@code null} for none. */ - public final HttpExecuteInterceptor getClientAuthentication() { - return clientAuthentication; - } - - /** - * Returns the HTTP request initializer for refresh token requests to the token server or - * {@code null} for none. - */ - public final HttpRequestInitializer getRequestInitializer() { - return requestInitializer; - } - - /** - * Request a new access token from the authorization endpoint. - * - *

- * On success, it will call {@link #setFromTokenResponse(TokenResponse)}, call - * {@link CredentialRefreshListener#onTokenResponse} with the token response, and return - * {@code true}. On error, it will call {@link #setAccessToken(String)} and - * {@link #setExpiresInSeconds(Long)} with {@code null}, call - * {@link CredentialRefreshListener#onTokenErrorResponse} with the token error response, and - * return {@code false}. If a 4xx error is encountered while refreshing the token, - * {@link TokenResponseException} is thrown. - *

- * - *

- * If there is no refresh token, it will quietly return {@code false}. - *

- * - * @return whether a new access token was successfully retrieved - */ - public final boolean refreshToken() throws IOException { - lock.lock(); - try { - try { - TokenResponse tokenResponse = executeRefreshToken(); - if (tokenResponse != null) { - setFromTokenResponse(tokenResponse); - for (CredentialRefreshListener refreshListener : refreshListeners) { - refreshListener.onTokenResponse(this, tokenResponse); - } - return true; - } - } catch (TokenResponseException e) { - boolean statusCode4xx = 400 <= e.getStatusCode() && e.getStatusCode() < 500; - // check if it is a normal error response - if (e.getDetails() != null && statusCode4xx) { - // We were unable to get a new access token (e.g. it may have been revoked), we must now - // indicate that our current token is invalid. - setAccessToken(null); - setExpiresInSeconds(null); - } - for (CredentialRefreshListener refreshListener : refreshListeners) { - refreshListener.onTokenErrorResponse(this, e.getDetails()); - } - if (statusCode4xx) { - throw e; - } - } - return false; - } finally { - lock.unlock(); - } - } - - /** - * Sets the {@link #setAccessToken access token}, {@link #setRefreshToken refresh token} (if - * available), and {@link #setExpiresInSeconds expires-in time} based on the values from the token - * response. - * - *

- * It does not call the refresh listeners. - *

- * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @param tokenResponse successful token response - */ - public Credential setFromTokenResponse(TokenResponse tokenResponse) { - setAccessToken(tokenResponse.getAccessToken()); - // handle case of having a refresh token previous, but no refresh token in current - // response - if (tokenResponse.getRefreshToken() != null) { - setRefreshToken(tokenResponse.getRefreshToken()); - } - setExpiresInSeconds(tokenResponse.getExpiresInSeconds()); - return this; - } - - /** - * Executes a request for new credentials from the token server. - * - *

- * The default implementation calls {@link RefreshTokenRequest#execute()} using the - * {@link #getTransport()}, {@link #getJsonFactory()}, {@link #getRequestInitializer()}, - * {@link #getTokenServerEncodedUrl()}, {@link #getRefreshToken()}, and the - * {@link #getClientAuthentication()}. If {@link #getRefreshToken()} is {@code null}, it instead - * returns {@code null}. - *

- * - *

- * Subclasses may override for a different implementation. Implementations can assume proper - * thread synchronization is already taken care of inside {@link #refreshToken()}. - *

- * - * @return successful response from the token server or {@code null} if it is not possible to - * refresh the access token - * @throws TokenResponseException if an error response was received from the token server - */ - protected TokenResponse executeRefreshToken() throws IOException { - if (refreshToken == null) { - return null; - } - return new RefreshTokenRequest(transport, jsonFactory, new GenericUrl(tokenServerEncodedUrl), - refreshToken).setClientAuthentication(clientAuthentication) - .setRequestInitializer(requestInitializer).execute(); - } - - /** Returns the unmodifiable collection of listeners for refresh token results. */ - public final Collection getRefreshListeners() { - return refreshListeners; - } - - /** - * Credential builder. - * - *

- * Implementation is not thread-safe. - *

- */ - public static class Builder { - - /** - * Method of presenting the access token to the resource server (for example - * {@link BearerToken.AuthorizationHeaderAccessMethod}). - */ - final AccessMethod method; - - /** - * HTTP transport for executing refresh token request or {@code null} if not refreshing tokens. - */ - HttpTransport transport; - - /** - * JSON factory to use for parsing response for refresh token request or {@code null} if not - * refreshing tokens. - */ - JsonFactory jsonFactory; - - /** Token server URL or {@code null} if not refreshing tokens. */ - GenericUrl tokenServerUrl; - - /** Clock used for expiration checks. */ - Clock clock = Clock.SYSTEM; - - /** - * Client authentication or {@code null} for none (see - * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}). - */ - HttpExecuteInterceptor clientAuthentication; - - /** - * HTTP request initializer for refresh token requests to the token server or {@code null} for - * none. - */ - HttpRequestInitializer requestInitializer; - - /** Listeners for refresh token results. */ - Collection refreshListeners = Lists.newArrayList(); - - /** - * @param method method of presenting the access token to the resource server (for example - * {@link BearerToken.AuthorizationHeaderAccessMethod}) - */ - public Builder(AccessMethod method) { - this.method = Preconditions.checkNotNull(method); - } - - /** Returns a new credential instance. */ - public Credential build() { - return new Credential(this); - } - - /** - * Returns the method of presenting the access token to the resource server (for example - * {@link BearerToken.AuthorizationHeaderAccessMethod}). - */ - public final AccessMethod getMethod() { - return method; - } - - /** - * Returns the HTTP transport for executing refresh token request or {@code null} if not - * refreshing tokens. - */ - public final HttpTransport getTransport() { - return transport; - } - - /** - * Sets the HTTP transport for executing refresh token request or {@code null} if not refreshing - * tokens. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setTransport(HttpTransport transport) { - this.transport = transport; - return this; - } - - /** - * Returns the clock to use for expiration checks or {@link Clock#SYSTEM} as default. - * @since 1.9 - */ - public final Clock getClock() { - return clock; - } - - /** - * Sets the clock to use for expiration checks. - * - *

- * The default value is Clock.SYSTEM. - *

- * - * @since 1.9 - */ - public Builder setClock(Clock clock) { - this.clock = Preconditions.checkNotNull(clock); - return this; - } - - /** - * Returns the JSON factory to use for parsing response for refresh token request or - * {@code null} if not refreshing tokens. - */ - public final JsonFactory getJsonFactory() { - return jsonFactory; - } - - /** - * Sets the JSON factory to use for parsing response for refresh token request or {@code null} - * if not refreshing tokens. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setJsonFactory(JsonFactory jsonFactory) { - this.jsonFactory = jsonFactory; - return this; - } - - /** Returns the token server URL or {@code null} if not refreshing tokens. */ - public final GenericUrl getTokenServerUrl() { - return tokenServerUrl; - } - - /** - * Sets the token server URL or {@code null} if not refreshing tokens. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setTokenServerUrl(GenericUrl tokenServerUrl) { - this.tokenServerUrl = tokenServerUrl; - return this; - } - - /** - * Sets the encoded token server URL or {@code null} if not refreshing tokens. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setTokenServerEncodedUrl(String tokenServerEncodedUrl) { - this.tokenServerUrl = - tokenServerEncodedUrl == null ? null : new GenericUrl(tokenServerEncodedUrl); - return this; - } - - /** - * Returns the client authentication or {@code null} for none (see - * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}). - */ - public final HttpExecuteInterceptor getClientAuthentication() { - return clientAuthentication; - } - - /** - * Sets the client authentication or {@code null} for none (see - * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}). - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setClientAuthentication(HttpExecuteInterceptor clientAuthentication) { - this.clientAuthentication = clientAuthentication; - return this; - } - - /** - * Returns the HTTP request initializer for refresh token requests to the token server or - * {@code null} for none. - */ - public final HttpRequestInitializer getRequestInitializer() { - return requestInitializer; - } - - /** - * Sets the HTTP request initializer for refresh token requests to the token server or - * {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setRequestInitializer(HttpRequestInitializer requestInitializer) { - this.requestInitializer = requestInitializer; - return this; - } - - /** - * Adds a listener for refresh token results. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @param refreshListener refresh listener - */ - public Builder addRefreshListener(CredentialRefreshListener refreshListener) { - refreshListeners.add(Preconditions.checkNotNull(refreshListener)); - return this; - } - - /** Returns the listeners for refresh token results. */ - public final Collection getRefreshListeners() { - return refreshListeners; - } - - /** - * Sets the listeners for refresh token results. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setRefreshListeners(Collection refreshListeners) { - this.refreshListeners = Preconditions.checkNotNull(refreshListeners); - return this; - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/CredentialRefreshListener.java b/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/CredentialRefreshListener.java deleted file mode 100644 index 72452f5a..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/CredentialRefreshListener.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.oauth2; - -import java.io.IOException; - - -/** - * Listener for refresh token results. - * - *

- * These methods are called from {@link Credential#refreshToken()} after a response has been - * received from refreshing the token. {@link #onTokenResponse} is called on a successful HTTP - * response, and {@link #onTokenErrorResponse} is called on an error HTTP response. - *

- * - * @since 1.7 - * @author Yaniv Inbar - */ -public interface CredentialRefreshListener { - - /** - * Notifies of a successful token response from {@link Credential#refreshToken()}. - * - *

- * Typical use is to provide functionality like persisting the access token in a data store. - * Implementations can assume proper thread synchronization is already taken care of inside - * {@link Credential#refreshToken()}. Implementations can also assume that - * {@link Credential#setAccessToken}, {@link Credential#setRefreshToken}, and - * {@link Credential#setExpiresInSeconds} have already been called previously with the information - * from the {@link TokenResponse}. - *

- * - * @param credential credential on which the token refresh applied - * @param tokenResponse token response - */ - void onTokenResponse(Credential credential, TokenResponse tokenResponse) throws IOException; - - /** - * Notifies of an error token response from {@link Credential#refreshToken()}. - * - *

- * Typical use is to provide functionality like removing persistence of the access token from the - * data store. Implementations can assume proper thread synchronization is already taken care of - * inside {@link Credential#refreshToken()}. Implementations can also assume that - * {@link Credential#setAccessToken}, and {@link Credential#setExpiresInSeconds} have already been - * called previously with {@code null} to clear their values. - *

- * - * @param credential credential on which the token refresh applied - * @param tokenErrorResponse token error response or {@code null} for none supplied - */ - void onTokenErrorResponse(Credential credential, TokenErrorResponse tokenErrorResponse) - throws IOException; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/CredentialStore.java b/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/CredentialStore.java deleted file mode 100644 index a03d6e9f..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/CredentialStore.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.oauth2; - -import java.io.IOException; - -import autosaveworld.zlibs.com.google.api.client.util.Beta; -import autosaveworld.zlibs.com.google.api.client.util.store.DataStoreFactory; - -/** - * {@link Beta}
- * OAuth 2.0 credential persistence store interface to provide a fully pluggable storage mechanism. - * - *

- * The user ID should be used as the primary key for storage, and the rest of the data consists of - * the {@link Credential#getAccessToken access token}, {@link Credential#getRefreshToken refresh - * token}, and {@link Credential#getExpirationTimeMilliseconds expiration time}. - *

- * - *

- * Implementations should be thread safe. - *

- * - * @since 1.7 - * @author Yaniv Inbar - * @deprecated (to be removed in the future) Use {@link DataStoreFactory} with - * {@link StoredCredential} instead. - */ -@Deprecated -@Beta -public interface CredentialStore { - - /** - * Loads the credential for the given user ID. - * - * @param userId user ID whose credential needs to be loaded - * @param credential credential whose {@link Credential#setAccessToken access token}, - * {@link Credential#setRefreshToken refresh token}, and - * {@link Credential#setExpirationTimeMilliseconds expiration time} need to be set if the - * credential already exists in storage - * @return {@code true} if the credential has been successfully found and loaded or {@code false} - * otherwise - */ - boolean load(String userId, Credential credential) throws IOException; - - /** - * Stores the credential of the given user ID. - * - * @param userId user ID whose credential needs to be stored - * @param credential credential whose {@link Credential#getAccessToken access token}, - * {@link Credential#getRefreshToken refresh token}, and - * {@link Credential#getExpirationTimeMilliseconds expiration time} need to be stored - */ - void store(String userId, Credential credential) throws IOException; - - /** - * Deletes the credential of the given user ID. - * - * @param userId user ID whose credential needs to be deleted - * @param credential credential to be deleted - */ - void delete(String userId, Credential credential) throws IOException; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/CredentialStoreRefreshListener.java b/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/CredentialStoreRefreshListener.java deleted file mode 100644 index b147193d..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/CredentialStoreRefreshListener.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.oauth2; - -import java.io.IOException; - -import autosaveworld.zlibs.com.google.api.client.util.Beta; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * {@link Beta}
- * Thread-safe OAuth 2.0 credential refresh listener that stores the refresh token response in the - * credential store. - * - *

- * It needs to be added as a refresh listener using {@link Credential.Builder#addRefreshListener}. - *

- * - * @since 1.7 - * @author Yaniv Inbar - * @deprecated (to be removed in the future) Use {@link DataStoreCredentialRefreshListener} - * instead. - */ -@Deprecated -@Beta -public final class CredentialStoreRefreshListener implements CredentialRefreshListener { - - /** Credential store. */ - private final CredentialStore credentialStore; - - /** User ID whose credential is to be updated. */ - private final String userId; - - /** - * @param userId user ID whose credential is to be updated - * @param credentialStore credential store - */ - public CredentialStoreRefreshListener(String userId, CredentialStore credentialStore) { - this.userId = Preconditions.checkNotNull(userId); - this.credentialStore = Preconditions.checkNotNull(credentialStore); - } - - public void onTokenResponse(Credential credential, TokenResponse tokenResponse) - throws IOException { - makePersistent(credential); - } - - public void onTokenErrorResponse(Credential credential, TokenErrorResponse tokenErrorResponse) - throws IOException { - makePersistent(credential); - } - - /** Returns the credential store. */ - public CredentialStore getCredentialStore() { - return credentialStore; - } - - /** Stores the updated credential in the credential store. */ - public void makePersistent(Credential credential) throws IOException { - credentialStore.store(userId, credential); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/DataStoreCredentialRefreshListener.java b/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/DataStoreCredentialRefreshListener.java deleted file mode 100644 index c250cefa..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/DataStoreCredentialRefreshListener.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.oauth2; - -import java.io.IOException; - -import autosaveworld.zlibs.com.google.api.client.util.Beta; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.store.DataStore; -import autosaveworld.zlibs.com.google.api.client.util.store.DataStoreFactory; - -/** - * {@link Beta}
- * Thread-safe OAuth 2.0 credential refresh listener that stores the refresh token response in the - * credential data store. - * - *

- * It needs to be added as a refresh listener using {@link Credential.Builder#addRefreshListener}. - * Sample usage: - *

- * - *
-  static void addDataStoreCredentialRefreshListener(
-      Credential.Builder credentialBuilder, String userId, DataStoreFactory dataStoreFactory)
-      throws IOException {
-    credentialBuilder.addRefreshListener(
-        new DataStoreCredentialRefreshListener(userId, dataStoreFactory));
-  }
- * 
- * - * @since 1.6 - * @author Yaniv Inbar - */ -@Beta -public final class DataStoreCredentialRefreshListener implements CredentialRefreshListener { - - /** Stored credential data store. */ - private final DataStore credentialDataStore; - - /** User ID whose credential is to be updated. */ - private final String userId; - - /** - * Constructor using {@link StoredCredential#getDefaultDataStore(DataStoreFactory)} for the stored - * credential data store. - * - * @param userId user ID whose credential is to be updated - * @param dataStoreFactory data store factory - */ - public DataStoreCredentialRefreshListener(String userId, DataStoreFactory dataStoreFactory) - throws IOException { - this(userId, StoredCredential.getDefaultDataStore(dataStoreFactory)); - } - - /** - * @param userId user ID whose credential is to be updated - * @param credentialDataStore stored credential data store - */ - public DataStoreCredentialRefreshListener( - String userId, DataStore credentialDataStore) { - this.userId = Preconditions.checkNotNull(userId); - this.credentialDataStore = Preconditions.checkNotNull(credentialDataStore); - } - - public void onTokenResponse(Credential credential, TokenResponse tokenResponse) - throws IOException { - makePersistent(credential); - } - - public void onTokenErrorResponse(Credential credential, TokenErrorResponse tokenErrorResponse) - throws IOException { - makePersistent(credential); - } - - /** Returns the stored credential data store. */ - public DataStore getCredentialDataStore() { - return credentialDataStore; - } - - /** Stores the updated credential in the credential store. */ - public void makePersistent(Credential credential) throws IOException { - credentialDataStore.set(userId, new StoredCredential(credential)); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/PasswordTokenRequest.java b/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/PasswordTokenRequest.java deleted file mode 100644 index e11a52df..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/PasswordTokenRequest.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.oauth2; - -import java.util.Collection; - -import autosaveworld.zlibs.com.google.api.client.http.GenericUrl; -import autosaveworld.zlibs.com.google.api.client.http.HttpExecuteInterceptor; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequestInitializer; -import autosaveworld.zlibs.com.google.api.client.http.HttpTransport; -import autosaveworld.zlibs.com.google.api.client.json.JsonFactory; -import autosaveworld.zlibs.com.google.api.client.util.Key; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * OAuth 2.0 request for an access token using the user's username and password as specified in Resource Owner Password Credentials - * Grant. - * - *

- * Use {@link Credential} to access protected resources from the resource server using the - * {@link TokenResponse} returned by {@link #execute()}. On error, it will instead throw - * {@link TokenResponseException}. - *

- * - *

- * Sample usage: - *

- * - *
-  static void requestAccessToken() throws IOException {
-    try {
-      TokenResponse response =
-          new PasswordTokenRequest(new NetHttpTransport(), new JacksonFactory(),
-              new GenericUrl("https://server.example.com/token"), "johndoe", "A3ddj3w")
-              .setRedirectUri("https://client.example.com/rd")
-              .setClientAuthentication(
-                  new BasicAuthentication("s6BhdRkqt3", "7Fjfp0ZBr1KtDRbnfVdmIw")).execute();
-      System.out.println("Access token: " + response.getAccessToken());
-    } catch (TokenResponseException e) {
-      if (e.getDetails() != null) {
-        System.err.println("Error: " + e.getDetails().getError());
-        if (e.getDetails().getErrorDescription() != null) {
-          System.err.println(e.getDetails().getErrorDescription());
-        }
-        if (e.getDetails().getErrorUri() != null) {
-          System.err.println(e.getDetails().getErrorUri());
-        }
-      } else {
-        System.err.println(e.getMessage());
-      }
-    }
-  }
- * 
- * - *

- * Some OAuth 2.0 providers don't support {@link BasicAuthentication} but instead support - * {@link ClientParametersAuthentication}. In the above sample code, simply replace the class name - * and it will work the same way. - *

- * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.14 - * @author Yaniv Inbar - */ -public class PasswordTokenRequest extends TokenRequest { - - /** Resource owner username. */ - @Key - private String username; - - /** Resource owner password. */ - @Key - private String password; - - /** - * @param transport HTTP transport - * @param jsonFactory JSON factory - * @param tokenServerUrl token server URL - * @param username resource owner username - * @param password resource owner password - */ - public PasswordTokenRequest(HttpTransport transport, JsonFactory jsonFactory, - GenericUrl tokenServerUrl, String username, String password) { - super(transport, jsonFactory, tokenServerUrl, "password"); - setUsername(username); - setPassword(password); - } - - @Override - public PasswordTokenRequest setRequestInitializer(HttpRequestInitializer requestInitializer) { - return (PasswordTokenRequest) super.setRequestInitializer(requestInitializer); - } - - @Override - public PasswordTokenRequest setTokenServerUrl(GenericUrl tokenServerUrl) { - return (PasswordTokenRequest) super.setTokenServerUrl(tokenServerUrl); - } - - @Override - public PasswordTokenRequest setScopes(Collection scopes) { - return (PasswordTokenRequest) super.setScopes(scopes); - } - - @Override - public PasswordTokenRequest setGrantType(String grantType) { - return (PasswordTokenRequest) super.setGrantType(grantType); - } - - @Override - public PasswordTokenRequest setClientAuthentication(HttpExecuteInterceptor clientAuthentication) { - return (PasswordTokenRequest) super.setClientAuthentication(clientAuthentication); - } - - /** Returns the resource owner username. */ - public final String getUsername() { - return username; - } - - /** - * Sets the resource owner username. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public PasswordTokenRequest setUsername(String username) { - this.username = Preconditions.checkNotNull(username); - return this; - } - - /** Returns the resource owner password. */ - public final String getPassword() { - return password; - } - - /** - * Sets the resource owner password. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public PasswordTokenRequest setPassword(String password) { - this.password = Preconditions.checkNotNull(password); - return this; - } - - @Override - public PasswordTokenRequest set(String fieldName, Object value) { - return (PasswordTokenRequest) super.set(fieldName, value); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/RefreshTokenRequest.java b/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/RefreshTokenRequest.java deleted file mode 100644 index dc68f1ec..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/RefreshTokenRequest.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.oauth2; - -import java.util.Collection; - -import autosaveworld.zlibs.com.google.api.client.http.GenericUrl; -import autosaveworld.zlibs.com.google.api.client.http.HttpExecuteInterceptor; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequestInitializer; -import autosaveworld.zlibs.com.google.api.client.http.HttpTransport; -import autosaveworld.zlibs.com.google.api.client.json.JsonFactory; -import autosaveworld.zlibs.com.google.api.client.util.Key; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * OAuth 2.0 request to refresh an access token using a refresh token as specified in Refreshing an Access Token. - * - *

- * Use {@link Credential} to access protected resources from the resource server using the - * {@link TokenResponse} returned by {@link #execute()}. On error, it will instead throw - * {@link TokenResponseException}. - *

- * - *

- * Sample usage: - *

- * - *
-  static void refreshAccessToken() throws IOException {
-    try {
-      TokenResponse response =
-          new RefreshTokenRequest(new NetHttpTransport(), new JacksonFactory(), new GenericUrl(
-              "https://server.example.com/token"), "tGzv3JOkF0XG5Qx2TlKWIA")
-              .setClientAuthentication(
-                  new BasicAuthentication("s6BhdRkqt3", "7Fjfp0ZBr1KtDRbnfVdmIw")).execute();
-      System.out.println("Access token: " + response.getAccessToken());
-    } catch (TokenResponseException e) {
-      if (e.getDetails() != null) {
-        System.err.println("Error: " + e.getDetails().getError());
-        if (e.getDetails().getErrorDescription() != null) {
-          System.err.println(e.getDetails().getErrorDescription());
-        }
-        if (e.getDetails().getErrorUri() != null) {
-          System.err.println(e.getDetails().getErrorUri());
-        }
-      } else {
-        System.err.println(e.getMessage());
-      }
-    }
-  }
- * 
- * - *

- * Some OAuth 2.0 providers don't support {@link BasicAuthentication} but instead support - * {@link ClientParametersAuthentication}. In the above sample code, simply replace the class name - * and it will work the same way. - *

- * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.7 - * @author Yaniv Inbar - */ -public class RefreshTokenRequest extends TokenRequest { - - /** Refresh token issued to the client. */ - @Key("refresh_token") - private String refreshToken; - - /** - * @param transport HTTP transport - * @param jsonFactory JSON factory - * @param tokenServerUrl token server URL - * @param refreshToken refresh token issued to the client - */ - public RefreshTokenRequest(HttpTransport transport, JsonFactory jsonFactory, - GenericUrl tokenServerUrl, String refreshToken) { - super(transport, jsonFactory, tokenServerUrl, "refresh_token"); - setRefreshToken(refreshToken); - } - - @Override - public RefreshTokenRequest setRequestInitializer(HttpRequestInitializer requestInitializer) { - return (RefreshTokenRequest) super.setRequestInitializer(requestInitializer); - } - - @Override - public RefreshTokenRequest setTokenServerUrl(GenericUrl tokenServerUrl) { - return (RefreshTokenRequest) super.setTokenServerUrl(tokenServerUrl); - } - - @Override - public RefreshTokenRequest setScopes(Collection scopes) { - return (RefreshTokenRequest) super.setScopes(scopes); - } - - @Override - public RefreshTokenRequest setGrantType(String grantType) { - return (RefreshTokenRequest) super.setGrantType(grantType); - } - - @Override - public RefreshTokenRequest setClientAuthentication(HttpExecuteInterceptor clientAuthentication) { - return (RefreshTokenRequest) super.setClientAuthentication(clientAuthentication); - } - - /** Returns the refresh token issued to the client. */ - public final String getRefreshToken() { - return refreshToken; - } - - /** - * Sets the refresh token issued to the client. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public RefreshTokenRequest setRefreshToken(String refreshToken) { - this.refreshToken = Preconditions.checkNotNull(refreshToken); - return this; - } - - @Override - public RefreshTokenRequest set(String fieldName, Object value) { - return (RefreshTokenRequest) super.set(fieldName, value); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/StoredCredential.java b/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/StoredCredential.java deleted file mode 100644 index 2244470c..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/StoredCredential.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.oauth2; - -import java.io.IOException; -import java.io.Serializable; -import java.util.Arrays; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import autosaveworld.zlibs.com.google.api.client.util.Beta; -import autosaveworld.zlibs.com.google.api.client.util.Objects; -import autosaveworld.zlibs.com.google.api.client.util.store.DataStore; -import autosaveworld.zlibs.com.google.api.client.util.store.DataStoreFactory; - -/** - * {@link Beta}
- * Credential information to be stored in a {@link DataStoreFactory}. - * - *

- * Implementation is thread safe. - *

- * - * @author Yaniv Inbar - * @since 1.16 - */ -@Beta -public final class StoredCredential implements Serializable { - - /** Default data store ID. */ - public static final String DEFAULT_DATA_STORE_ID = StoredCredential.class.getSimpleName(); - - private static final long serialVersionUID = 1L; - - /** Lock on access to the store. */ - private final Lock lock = new ReentrantLock(); - - /** Access token or {@code null} for none. */ - private String accessToken; - - /** Expected expiration time in milliseconds or {@code null} for none. */ - private Long expirationTimeMilliseconds; - - /** Refresh token or {@code null} for none. */ - private String refreshToken; - - public StoredCredential() { - } - - /** - * @param credential existing credential to copy from - */ - public StoredCredential(Credential credential) { - setAccessToken(credential.getAccessToken()); - setRefreshToken(credential.getRefreshToken()); - setExpirationTimeMilliseconds(credential.getExpirationTimeMilliseconds()); - } - - /** Returns the access token or {@code null} for none. */ - public String getAccessToken() { - lock.lock(); - try { - return accessToken; - } finally { - lock.unlock(); - } - } - - /** Sets the access token or {@code null} for none. */ - public StoredCredential setAccessToken(String accessToken) { - lock.lock(); - try { - this.accessToken = accessToken; - } finally { - lock.unlock(); - } - return this; - } - - /** Returns the expected expiration time in milliseconds or {@code null} for none. */ - public Long getExpirationTimeMilliseconds() { - lock.lock(); - try { - return expirationTimeMilliseconds; - } finally { - lock.unlock(); - } - } - - /** Sets the expected expiration time in milliseconds or {@code null} for none. */ - public StoredCredential setExpirationTimeMilliseconds(Long expirationTimeMilliseconds) { - lock.lock(); - try { - this.expirationTimeMilliseconds = expirationTimeMilliseconds; - } finally { - lock.unlock(); - } - return this; - } - - /** Returns the refresh token or {@code null} for none. */ - public String getRefreshToken() { - lock.lock(); - try { - return refreshToken; - } finally { - lock.unlock(); - } - } - - /** Sets the refresh token or {@code null} for none. */ - public StoredCredential setRefreshToken(String refreshToken) { - lock.lock(); - try { - this.refreshToken = refreshToken; - } finally { - lock.unlock(); - } - return this; - } - - @Override - public String toString() { - return Objects.toStringHelper(StoredCredential.class) - .add("accessToken", getAccessToken()) - .add("refreshToken", getRefreshToken()) - .add("expirationTimeMilliseconds", getExpirationTimeMilliseconds()) - .toString(); - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof StoredCredential)) { - return false; - } - StoredCredential o = (StoredCredential) other; - return Objects.equal(getAccessToken(), o.getAccessToken()) - && Objects.equal(getRefreshToken(), o.getRefreshToken()) - && Objects.equal(getExpirationTimeMilliseconds(), o.getExpirationTimeMilliseconds()); - } - - @Override - public int hashCode() { - return Arrays.hashCode( - new Object[] {getAccessToken(), getRefreshToken(), getExpirationTimeMilliseconds()}); - } - - /** - * Returns the stored credential data store using the ID {@link #DEFAULT_DATA_STORE_ID}. - * - * @param dataStoreFactory data store factory - * @return stored credential data store - */ - public static DataStore getDefaultDataStore(DataStoreFactory dataStoreFactory) - throws IOException { - return dataStoreFactory.getDataStore(DEFAULT_DATA_STORE_ID); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/TokenErrorResponse.java b/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/TokenErrorResponse.java deleted file mode 100644 index 9236d1cd..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/TokenErrorResponse.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.oauth2; - -import autosaveworld.zlibs.com.google.api.client.json.GenericJson; -import autosaveworld.zlibs.com.google.api.client.util.Key; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * OAuth 2.0 parser for an error access token response as specified in Error Response. - * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.7 - * @author Yaniv Inbar - */ -public class TokenErrorResponse extends GenericJson { - - /** - * Error code ({@code "invalid_request"}, {@code "invalid_client"}, {@code "invalid_grant"}, - * {@code "unauthorized_client"}, {@code "unsupported_grant_type"}, {@code "invalid_scope"}, or an - * extension error code as specified in Defining Additional Error Codes). - */ - @Key - private String error; - - /** - * Human-readable text providing additional information, used to assist the client developer in - * understanding the error that occurred or {@code null} for none. - */ - @Key("error_description") - private String errorDescription; - - /** - * URI identifying a human-readable web page with information about the error, used to provide the - * client developer with additional information about the error or {@code null} for none. - */ - @Key("error_uri") - private String errorUri; - - /** - * Returns the error code ({@code "invalid_request"}, {@code "invalid_client"}, - * {@code "invalid_grant"}, {@code "unauthorized_client"}, {@code "unsupported_grant_type"}, - * {@code "invalid_scope"}, or an extension error code as specified in Defining Additional Error Codes). - */ - public final String getError() { - return error; - } - - /** - * Sets the error code ({@code "invalid_request"}, {@code "invalid_client"}, - * {@code "invalid_grant"}, {@code "unauthorized_client"}, {@code "unsupported_grant_type"}, - * {@code "invalid_scope"}, or an extension error code as specified in Defining Additional Error Codes). - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public TokenErrorResponse setError(String error) { - this.error = Preconditions.checkNotNull(error); - return this; - } - - /** - * Returns the human-readable text providing additional information, used to assist the client - * developer in understanding the error that occurred or {@code null} for none. - */ - public final String getErrorDescription() { - return errorDescription; - } - - /** - * Sets the human-readable text providing additional information, used to assist the client - * developer in understanding the error that occurred or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public TokenErrorResponse setErrorDescription(String errorDescription) { - this.errorDescription = errorDescription; - return this; - } - - /** - * Returns the URI identifying a human-readable web page with information about the error, used to - * provide the client developer with additional information about the error or {@code null} for - * none. - */ - public final String getErrorUri() { - return errorUri; - } - - /** - * Sets the URI identifying a human-readable web page with information about the error, used to - * provide the client developer with additional information about the error or {@code null} for - * none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public TokenErrorResponse setErrorUri(String errorUri) { - this.errorUri = errorUri; - return this; - } - - @Override - public TokenErrorResponse set(String fieldName, Object value) { - return (TokenErrorResponse) super.set(fieldName, value); - } - - @Override - public TokenErrorResponse clone() { - return (TokenErrorResponse) super.clone(); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/TokenRequest.java b/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/TokenRequest.java deleted file mode 100644 index ba56cad1..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/TokenRequest.java +++ /dev/null @@ -1,313 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.oauth2; - -import java.io.IOException; -import java.util.Collection; - -import autosaveworld.zlibs.com.google.api.client.http.GenericUrl; -import autosaveworld.zlibs.com.google.api.client.http.HttpExecuteInterceptor; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequest; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequestFactory; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequestInitializer; -import autosaveworld.zlibs.com.google.api.client.http.HttpResponse; -import autosaveworld.zlibs.com.google.api.client.http.HttpTransport; -import autosaveworld.zlibs.com.google.api.client.http.UrlEncodedContent; -import autosaveworld.zlibs.com.google.api.client.json.JsonFactory; -import autosaveworld.zlibs.com.google.api.client.json.JsonObjectParser; -import autosaveworld.zlibs.com.google.api.client.util.GenericData; -import autosaveworld.zlibs.com.google.api.client.util.Joiner; -import autosaveworld.zlibs.com.google.api.client.util.Key; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * OAuth 2.0 request for an access token as specified in Obtaining Authorization. - * - *

- * Call {@link #execute()} to execute the request and use the returned {@link TokenResponse}. On - * error, it will instead throw {@link TokenResponseException}. - *

- * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.7 - * @author Yaniv Inbar - */ -public class TokenRequest extends GenericData { - - /** HTTP request initializer or {@code null} for none. */ - HttpRequestInitializer requestInitializer; - - /** Client authentication or {@code null} for none. */ - HttpExecuteInterceptor clientAuthentication; - - /** HTTP transport. */ - private final HttpTransport transport; - - /** JSON factory. */ - private final JsonFactory jsonFactory; - - /** Token server URL. */ - private GenericUrl tokenServerUrl; - - /** - * Space-separated list of scopes (as specified in Access Token Scope) or {@code null} - * for none. - */ - @Key("scope") - private String scopes; - - /** - * Grant type ({@code "authorization_code"}, {@code "password"}, {@code "client_credentials"}, - * {@code "refresh_token"} or absolute URI of the extension grant type). - */ - @Key("grant_type") - private String grantType; - - /** - * @param transport HTTP transport - * @param jsonFactory JSON factory - * @param tokenServerUrl token server URL - * @param grantType grant type ({@code "authorization_code"}, {@code "password"}, - * {@code "client_credentials"}, {@code "refresh_token"} or absolute URI of the extension - * grant type) - */ - public TokenRequest(HttpTransport transport, JsonFactory jsonFactory, GenericUrl tokenServerUrl, - String grantType) { - this.transport = Preconditions.checkNotNull(transport); - this.jsonFactory = Preconditions.checkNotNull(jsonFactory); - setTokenServerUrl(tokenServerUrl); - setGrantType(grantType); - } - - /** Returns the HTTP transport. */ - public final HttpTransport getTransport() { - return transport; - } - - /** Returns the JSON factory. */ - public final JsonFactory getJsonFactory() { - return jsonFactory; - } - - /** Returns the HTTP request initializer or {@code null} for none. */ - public final HttpRequestInitializer getRequestInitializer() { - return requestInitializer; - } - - /** - * Sets the HTTP request initializer or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public TokenRequest setRequestInitializer(HttpRequestInitializer requestInitializer) { - this.requestInitializer = requestInitializer; - return this; - } - - /** Returns the client authentication or {@code null} for none. */ - public final HttpExecuteInterceptor getClientAuthentication() { - return clientAuthentication; - } - - /** - * Sets the client authentication or {@code null} for none. - * - *

- * The recommended initializer by the specification is {@link BasicAuthentication}. All - * authorization servers must support that. A common alternative is - * {@link ClientParametersAuthentication}. An alternative client authentication method may be - * provided that implements {@link HttpRequestInitializer}. - *

- * - *

- * This HTTP request execute interceptor is guaranteed to be the last execute interceptor before - * the request is executed, and after any execute interceptor set by the - * {@link #getRequestInitializer()}. - *

- * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public TokenRequest setClientAuthentication(HttpExecuteInterceptor clientAuthentication) { - this.clientAuthentication = clientAuthentication; - return this; - } - - /** Returns the token server URL. */ - public final GenericUrl getTokenServerUrl() { - return tokenServerUrl; - } - - /** - * Sets the token server URL. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public TokenRequest setTokenServerUrl(GenericUrl tokenServerUrl) { - this.tokenServerUrl = tokenServerUrl; - Preconditions.checkArgument(tokenServerUrl.getFragment() == null); - return this; - } - - /** - * Returns the space-separated list of scopes (as specified in Access Token Scope) or {@code null} - * for none. - */ - public final String getScopes() { - return scopes; - } - - /** - * Sets the list of scopes (as specified in Access Token Scope) or {@code null} - * for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @param scopes collection of scopes to be joined by a space separator (or a single value - * containing multiple space-separated scopes) - * @since 1.15 - */ - public TokenRequest setScopes(Collection scopes) { - this.scopes = scopes == null ? null : Joiner.on(' ').join(scopes); - return this; - } - - /** - * Returns the grant type ({@code "authorization_code"}, {@code "password"}, - * {@code "client_credentials"}, {@code "refresh_token"} or absolute URI of the extension grant - * type). - */ - public final String getGrantType() { - return grantType; - } - - /** - * Sets the grant type ({@code "authorization_code"}, {@code "password"}, - * {@code "client_credentials"}, {@code "refresh_token"} or absolute URI of the extension grant - * type). - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public TokenRequest setGrantType(String grantType) { - this.grantType = Preconditions.checkNotNull(grantType); - return this; - } - - /** - * Executes request for an access token, and returns the HTTP response. - * - *

- * To execute and parse the response to {@link TokenResponse}, instead use {@link #execute()}. - *

- * - *

- * Callers should call {@link HttpResponse#disconnect} when the returned HTTP response object is - * no longer needed. However, {@link HttpResponse#disconnect} does not have to be called if the - * response stream is properly closed. Example usage: - *

- * - *
-     HttpResponse response = tokenRequest.executeUnparsed();
-     try {
-       // process the HTTP response object
-     } finally {
-       response.disconnect();
-     }
-   * 
- * - * @return successful access token response, which can then be parsed directly using - * {@link HttpResponse#parseAs(Class)} or some other parsing method - * @throws TokenResponseException for an error response - */ - public final HttpResponse executeUnparsed() throws IOException { - // must set clientAuthentication as last execute interceptor in case it needs to sign request - HttpRequestFactory requestFactory = - transport.createRequestFactory(new HttpRequestInitializer() { - - public void initialize(HttpRequest request) throws IOException { - if (requestInitializer != null) { - requestInitializer.initialize(request); - } - final HttpExecuteInterceptor interceptor = request.getInterceptor(); - request.setInterceptor(new HttpExecuteInterceptor() { - public void intercept(HttpRequest request) throws IOException { - if (interceptor != null) { - interceptor.intercept(request); - } - if (clientAuthentication != null) { - clientAuthentication.intercept(request); - } - } - }); - } - }); - // make request - HttpRequest request = - requestFactory.buildPostRequest(tokenServerUrl, new UrlEncodedContent(this)); - request.setParser(new JsonObjectParser(jsonFactory)); - request.setThrowExceptionOnExecuteError(false); - HttpResponse response = request.execute(); - if (response.isSuccessStatusCode()) { - return response; - } - throw TokenResponseException.from(jsonFactory, response); - } - - /** - * Executes request for an access token, and returns the parsed access token response. - * - *

- * To execute but parse the response in an alternate way, use {@link #executeUnparsed()}. - *

- * - *

- * Default implementation calls {@link #executeUnparsed()} and then parses using - * {@link TokenResponse}. Subclasses may override to change the return type, but must still call - * {@link #executeUnparsed()}. - *

- * - * @return parsed successful access token response - * @throws TokenResponseException for an error response - */ - public TokenResponse execute() throws IOException { - return executeUnparsed().parseAs(TokenResponse.class); - } - - @Override - public TokenRequest set(String fieldName, Object value) { - return (TokenRequest) super.set(fieldName, value); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/TokenResponse.java b/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/TokenResponse.java deleted file mode 100644 index d3e763ec..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/TokenResponse.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.oauth2; - -import autosaveworld.zlibs.com.google.api.client.json.GenericJson; -import autosaveworld.zlibs.com.google.api.client.util.Key; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * OAuth 2.0 JSON model for a successful access token response as specified in Successful Response. - * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.7 - * @author Yaniv Inbar - */ -public class TokenResponse extends GenericJson { - - /** Access token issued by the authorization server. */ - @Key("access_token") - private String accessToken; - - /** - * Token type (as specified in Access - * Token Types). - */ - @Key("token_type") - private String tokenType; - - /** - * Lifetime in seconds of the access token (for example 3600 for an hour) or {@code null} for - * none. - */ - @Key("expires_in") - private Long expiresInSeconds; - - /** - * Refresh token which can be used to obtain new access tokens using {@link RefreshTokenRequest} - * or {@code null} for none. - */ - @Key("refresh_token") - private String refreshToken; - - /** - * Scope of the access token as specified in Access Token Scope or {@code null} - * for none. - */ - @Key - private String scope; - - /** Returns the access token issued by the authorization server. */ - public final String getAccessToken() { - return accessToken; - } - - /** - * Sets the access token issued by the authorization server. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public TokenResponse setAccessToken(String accessToken) { - this.accessToken = Preconditions.checkNotNull(accessToken); - return this; - } - - /** - * Returns the token type (as specified in Access Token Types). - */ - public final String getTokenType() { - return tokenType; - } - - /** - * Sets the token type (as specified in Access Token Types). - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public TokenResponse setTokenType(String tokenType) { - this.tokenType = Preconditions.checkNotNull(tokenType); - return this; - } - - /** - * Returns the lifetime in seconds of the access token (for example 3600 for an hour) or - * {@code null} for none. - */ - public final Long getExpiresInSeconds() { - return expiresInSeconds; - } - - /** - * Sets the lifetime in seconds of the access token (for example 3600 for an hour) or {@code null} - * for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public TokenResponse setExpiresInSeconds(Long expiresInSeconds) { - this.expiresInSeconds = expiresInSeconds; - return this; - } - - /** - * Returns the refresh token which can be used to obtain new access tokens using the same - * authorization grant or {@code null} for none. - */ - public final String getRefreshToken() { - return refreshToken; - } - - /** - * Sets the refresh token which can be used to obtain new access tokens using the same - * authorization grant or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public TokenResponse setRefreshToken(String refreshToken) { - this.refreshToken = refreshToken; - return this; - } - - /** - * Returns the scope of the access token or {@code null} for none. - */ - public final String getScope() { - return scope; - } - - /** - * Sets the scope of the access token or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public TokenResponse setScope(String scope) { - this.scope = scope; - return this; - } - - @Override - public TokenResponse set(String fieldName, Object value) { - return (TokenResponse) super.set(fieldName, value); - } - - @Override - public TokenResponse clone() { - return (TokenResponse) super.clone(); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/TokenResponseException.java b/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/TokenResponseException.java deleted file mode 100644 index 1babd769..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/oauth2/TokenResponseException.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.oauth2; - -import java.io.IOException; - -import autosaveworld.zlibs.com.google.api.client.http.HttpMediaType; -import autosaveworld.zlibs.com.google.api.client.http.HttpResponse; -import autosaveworld.zlibs.com.google.api.client.http.HttpResponseException; -import autosaveworld.zlibs.com.google.api.client.json.Json; -import autosaveworld.zlibs.com.google.api.client.json.JsonFactory; -import autosaveworld.zlibs.com.google.api.client.json.JsonObjectParser; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.StringUtils; - -/** - * Exception thrown when receiving an error response from the token server as specified in Error Response - * - *

- * To get the structured details, use {@link #getDetails()}. - *

- * - *

- * Sample usage can be found for {@link AuthorizationCodeTokenRequest}. - *

- * - * @since 1.7 - * @author Yaniv Inbar - */ -public class TokenResponseException extends HttpResponseException { - - private static final long serialVersionUID = 4020689092957439244L; - - /** Token error response details or {@code null} if unable to parse. */ - private final transient TokenErrorResponse details; - - /** - * @param builder builder - * @param details token error response details or {@code null} if unable to parse - */ - TokenResponseException(Builder builder, TokenErrorResponse details) { - super(builder); - this.details = details; - } - - /** Returns the token error response details or {@code null} if unable to parse. */ - public final TokenErrorResponse getDetails() { - return details; - } - - /** - * Returns a new instance of {@link TokenResponseException}. - * - *

- * If there is a JSON error response, it is parsed using {@link TokenErrorResponse}, which can be - * inspected using {@link #getDetails()}. Otherwise, the full response content is read and - * included in the exception message. - *

- * - * @param jsonFactory JSON factory - * @param response HTTP response - * @return new instance of {@link TokenErrorResponse} - */ - public static TokenResponseException from(JsonFactory jsonFactory, HttpResponse response) { - HttpResponseException.Builder builder = new HttpResponseException.Builder( - response.getStatusCode(), response.getStatusMessage(), response.getHeaders()); - // details - Preconditions.checkNotNull(jsonFactory); - TokenErrorResponse details = null; - String detailString = null; - String contentType = response.getContentType(); - try { - if (!response.isSuccessStatusCode() && contentType != null && response.getContent() != null - && HttpMediaType.equalsIgnoreParameters(Json.MEDIA_TYPE, contentType)) { - details = new JsonObjectParser(jsonFactory).parseAndClose( - response.getContent(), response.getContentCharset(), TokenErrorResponse.class); - detailString = details.toPrettyString(); - } else { - detailString = response.parseAsString(); - } - } catch (IOException exception) { - // it would be bad to throw an exception while throwing an exception - exception.printStackTrace(); - } - // message - StringBuilder message = HttpResponseException.computeMessageBuffer(response); - if (!autosaveworld.zlibs.com.google.api.client.util.Strings.isNullOrEmpty(detailString)) { - message.append(StringUtils.LINE_SEPARATOR).append(detailString); - builder.setContent(detailString); - } - builder.setMessage(message.toString()); - return new TokenResponseException(builder, details); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/openidconnect/IdToken.java b/src/autosaveworld/zlibs/com/google/api/client/auth/openidconnect/IdToken.java deleted file mode 100644 index 5d4e84f8..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/openidconnect/IdToken.java +++ /dev/null @@ -1,387 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.openidconnect; - -import java.io.IOException; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import autosaveworld.zlibs.com.google.api.client.json.JsonFactory; -import autosaveworld.zlibs.com.google.api.client.json.webtoken.JsonWebSignature; -import autosaveworld.zlibs.com.google.api.client.json.webtoken.JsonWebToken; -import autosaveworld.zlibs.com.google.api.client.util.Beta; -import autosaveworld.zlibs.com.google.api.client.util.Key; - -/** - * {@link Beta}
- * ID token as described in ID Token. - * - *

- * Use {@link #parse(JsonFactory, String)} to parse an ID token from a string. Then, use the - * {@code verify} methods to verify the ID token as required by the specification. - *

- * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.14 - * @author Yaniv Inbar - */ -@Beta -public class IdToken extends JsonWebSignature { - - /** - * @param header header - * @param payload payload - * @param signatureBytes bytes of the signature - * @param signedContentBytes bytes of the signature content - */ - public IdToken(Header header, Payload payload, byte[] signatureBytes, byte[] signedContentBytes) { - super(header, payload, signatureBytes, signedContentBytes); - } - - @Override - public Payload getPayload() { - return (Payload) super.getPayload(); - } - - /** - * Returns whether the issuer in the payload matches the given expected issuer as specified in - * step 1 of ID Token - * Validation. - * - * @param expectedIssuer expected issuer - */ - public final boolean verifyIssuer(String expectedIssuer) { - return verifyIssuer(Collections.singleton(expectedIssuer)); - } - - /** - * Returns whether the issuer in the payload matches the given expected issuer as specified in - * step 1 of ID Token - * Validation. When an issuer is migrating to a new issuer string the expected issuer has - * multiple aliases, so multiple are permitted here. - * - * @since 1.21.0 - */ - public final boolean verifyIssuer(Collection expectedIssuer) { - return expectedIssuer.contains(getPayload().getIssuer()); - } - - /** - * Returns whether the audience in the payload contains only client IDs that are trusted as - * specified in step 2 of ID Token - * Validation. - * - * @param trustedClientIds list of trusted client IDs - */ - public final boolean verifyAudience(Collection trustedClientIds) { - return trustedClientIds.containsAll(getPayload().getAudienceAsList()); - } - - /** - * Returns whether the {@link Payload#getExpirationTimeSeconds} and - * {@link Payload#getIssuedAtTimeSeconds} are valid relative to the current time, allowing for a - * clock skew as specified in steps 5 and 6 of ID Token - * Validation. - * - * @param currentTimeMillis current time in milliseconds (typically - * {@link System#currentTimeMillis()}) - * @param acceptableTimeSkewSeconds seconds of acceptable clock skew - */ - public final boolean verifyTime(long currentTimeMillis, long acceptableTimeSkewSeconds) { - return verifyExpirationTime(currentTimeMillis, acceptableTimeSkewSeconds) - && verifyIssuedAtTime(currentTimeMillis, acceptableTimeSkewSeconds); - } - - /** - * Returns whether the {@link Payload#getExpirationTimeSeconds} is valid relative to the current - * time, allowing for a clock skew as specified in step 5 of ID Token - * Validation. - * - * @param currentTimeMillis current time in milliseconds (typically - * {@link System#currentTimeMillis()}) - * @param acceptableTimeSkewSeconds seconds of acceptable clock skew - */ - public final boolean verifyExpirationTime( - long currentTimeMillis, long acceptableTimeSkewSeconds) { - return currentTimeMillis - <= (getPayload().getExpirationTimeSeconds() + acceptableTimeSkewSeconds) * 1000; - } - - /** - * Returns whether the {@link Payload#getIssuedAtTimeSeconds} is valid relative to the current - * time, allowing for a clock skew as specified in step 6 of ID Token - * Validation. - * - * @param currentTimeMillis current time in milliseconds (typically - * {@link System#currentTimeMillis()}) - * @param acceptableTimeSkewSeconds seconds of acceptable clock skew - */ - public final boolean verifyIssuedAtTime(long currentTimeMillis, long acceptableTimeSkewSeconds) { - return currentTimeMillis - >= (getPayload().getIssuedAtTimeSeconds() - acceptableTimeSkewSeconds) * 1000; - } - - /** - * Parses the given ID token string and returns the parsed ID token. - * - * @param jsonFactory JSON factory - * @param idTokenString ID token string - * @return parsed ID token - */ - public static IdToken parse(JsonFactory jsonFactory, String idTokenString) throws IOException { - JsonWebSignature jws = - JsonWebSignature.parser(jsonFactory).setPayloadClass(Payload.class).parse(idTokenString); - return new IdToken(jws.getHeader(), (Payload) jws.getPayload(), jws.getSignatureBytes(), - jws.getSignedContentBytes()); - } - - /** - * {@link Beta}
- * ID token payload. - */ - @Beta - public static class Payload extends JsonWebToken.Payload { - - /** Time (in seconds) of end-user authorization or {@code null} for none. */ - @Key("auth_time") - private Long authorizationTimeSeconds; - - /** Authorized party or {@code null} for none. */ - @Key("azp") - private String authorizedParty; - - /** Value used to associate a client session with an ID token or {@code null} for none. */ - @Key - private String nonce; - - /** Access token hash value or {@code null} for none. */ - @Key("at_hash") - private String accessTokenHash; - - /** Authentication context class reference or {@code null} for none. */ - @Key("acr") - private String classReference; - - /** Authentication methods references or {@code null} for none. */ - @Key("amr") - private List methodsReferences; - - /** Returns the time (in seconds) of end-user authorization or {@code null} for none. */ - public final Long getAuthorizationTimeSeconds() { - return authorizationTimeSeconds; - } - - /** - * Sets the time (in seconds) of end-user authorization or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Payload setAuthorizationTimeSeconds(Long authorizationTimeSeconds) { - this.authorizationTimeSeconds = authorizationTimeSeconds; - return this; - } - - /** - * Returns the authorized party or {@code null} for none. - * - *

- * Upgrade warning: in prior version 1.15 this method returned an {@link Object}, but starting - * with version 1.16 it returns a {@link String}. - *

- */ - public final String getAuthorizedParty() { - return authorizedParty; - } - - /** - * Sets the authorized party or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - *

- * Upgrade warning: in prior version 1.15 the parameter was an {@link Object}, but starting with - * version 1.16 the parameter is a {@link String}. - *

- */ - public Payload setAuthorizedParty(String authorizedParty) { - this.authorizedParty = authorizedParty; - return this; - } - - /** - * Returns the value used to associate a client session with an ID token or {@code null} for - * none. - * - * @since 1.16 - */ - public final String getNonce() { - return nonce; - } - - /** - * Sets the value used to associate a client session with an ID token or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.16 - */ - public Payload setNonce(String nonce) { - this.nonce = nonce; - return this; - } - - /** - * Returns the access token hash value or {@code null} for none. - * - * @since 1.16 - */ - public final String getAccessTokenHash() { - return accessTokenHash; - } - - /** - * Sets the access token hash value or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.16 - */ - public Payload setAccessTokenHash(String accessTokenHash) { - this.accessTokenHash = accessTokenHash; - return this; - } - - /** - * Returns the authentication context class reference or {@code null} for none. - * - * @since 1.16 - */ - public final String getClassReference() { - return classReference; - } - - /** - * Sets the authentication context class reference or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.16 - */ - public Payload setClassReference(String classReference) { - this.classReference = classReference; - return this; - } - - /** - * Returns the authentication methods references or {@code null} for none. - * - * @since 1.16 - */ - public final List getMethodsReferences() { - return methodsReferences; - } - - /** - * Sets the authentication methods references or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.16 - */ - public Payload setMethodsReferences(List methodsReferences) { - this.methodsReferences = methodsReferences; - return this; - } - - @Override - public Payload setExpirationTimeSeconds(Long expirationTimeSeconds) { - return (Payload) super.setExpirationTimeSeconds(expirationTimeSeconds); - } - - @Override - public Payload setNotBeforeTimeSeconds(Long notBeforeTimeSeconds) { - return (Payload) super.setNotBeforeTimeSeconds(notBeforeTimeSeconds); - } - - @Override - public Payload setIssuedAtTimeSeconds(Long issuedAtTimeSeconds) { - return (Payload) super.setIssuedAtTimeSeconds(issuedAtTimeSeconds); - } - - @Override - public Payload setIssuer(String issuer) { - return (Payload) super.setIssuer(issuer); - } - - @Override - public Payload setAudience(Object audience) { - return (Payload) super.setAudience(audience); - } - - @Override - public Payload setJwtId(String jwtId) { - return (Payload) super.setJwtId(jwtId); - } - - @Override - public Payload setType(String type) { - return (Payload) super.setType(type); - } - - @Override - public Payload setSubject(String subject) { - return (Payload) super.setSubject(subject); - } - - @Override - public Payload set(String fieldName, Object value) { - return (Payload) super.set(fieldName, value); - } - - @Override - public Payload clone() { - return (Payload) super.clone(); - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/openidconnect/IdTokenResponse.java b/src/autosaveworld/zlibs/com/google/api/client/auth/openidconnect/IdTokenResponse.java deleted file mode 100644 index b04d30f1..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/openidconnect/IdTokenResponse.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.openidconnect; - -import java.io.IOException; - -import autosaveworld.zlibs.com.google.api.client.auth.oauth2.TokenRequest; -import autosaveworld.zlibs.com.google.api.client.auth.oauth2.TokenResponse; -import autosaveworld.zlibs.com.google.api.client.auth.oauth2.TokenResponseException; -import autosaveworld.zlibs.com.google.api.client.json.JsonFactory; -import autosaveworld.zlibs.com.google.api.client.json.webtoken.JsonWebSignature; -import autosaveworld.zlibs.com.google.api.client.util.Beta; -import autosaveworld.zlibs.com.google.api.client.util.Key; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * {@link Beta}
- * OAuth ID Connect JSON model for a successful access token response as specified in OpenID Connect Basic Client - * Profile 1.0 (draft 23). - * - *

- * Implementation is not thread-safe. Sample usage: - *

- * - *
-  static JsonWebSignature executeIdToken(TokenRequest tokenRequest) throws IOException {
-    IdTokenResponse idTokenResponse = IdTokenResponse.execute(tokenRequest);
-    return idTokenResponse.parseIdToken();
-  }
- * 
- * - * @since 1.7 - * @author Yaniv Inbar - */ -@Beta -public class IdTokenResponse extends TokenResponse { - - /** ID token. */ - @Key("id_token") - private String idToken; - - /** Returns the ID token. */ - public final String getIdToken() { - return idToken; - } - - /** - * Sets the ID token. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public IdTokenResponse setIdToken(String idToken) { - this.idToken = Preconditions.checkNotNull(idToken); - return this; - } - - @Override - public IdTokenResponse setAccessToken(String accessToken) { - super.setAccessToken(accessToken); - return this; - } - - @Override - public IdTokenResponse setTokenType(String tokenType) { - super.setTokenType(tokenType); - return this; - } - - @Override - public IdTokenResponse setExpiresInSeconds(Long expiresIn) { - super.setExpiresInSeconds(expiresIn); - return this; - } - - @Override - public IdTokenResponse setRefreshToken(String refreshToken) { - super.setRefreshToken(refreshToken); - return this; - } - - @Override - public IdTokenResponse setScope(String scope) { - super.setScope(scope); - return this; - } - - /** - * Parses using {@link JsonWebSignature#parse(JsonFactory, String)} based on the - * {@link #getFactory() JSON factory} and {@link #getIdToken() ID token}. - */ - @SuppressWarnings("javadoc") - public IdToken parseIdToken() throws IOException { - return IdToken.parse(getFactory(), idToken); - } - - /** - * Executes the given ID token request, and returns the parsed ID token response. - * - * @param tokenRequest token request - * @return parsed successful ID token response - * @throws TokenResponseException for an error response - */ - public static IdTokenResponse execute(TokenRequest tokenRequest) throws IOException { - return tokenRequest.executeUnparsed().parseAs(IdTokenResponse.class); - } - - @Override - public IdTokenResponse set(String fieldName, Object value) { - return (IdTokenResponse) super.set(fieldName, value); - } - - @Override - public IdTokenResponse clone() { - return (IdTokenResponse) super.clone(); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/auth/openidconnect/IdTokenVerifier.java b/src/autosaveworld/zlibs/com/google/api/client/auth/openidconnect/IdTokenVerifier.java deleted file mode 100644 index 59c1fe16..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/auth/openidconnect/IdTokenVerifier.java +++ /dev/null @@ -1,307 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.auth.openidconnect; - -import java.util.Collection; -import java.util.Collections; - -import autosaveworld.zlibs.com.google.api.client.util.Beta; -import autosaveworld.zlibs.com.google.api.client.util.Clock; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * {@link Beta}
- * Thread-safe ID token verifier based on ID Token - * Validation. - * - *

- * Call {@link #verify(IdToken)} to verify a ID token. This is a light-weight object, so you may use - * a new instance for each configuration of expected issuer and trusted client IDs. Sample usage: - *

- * - *
-    IdTokenVerifier verifier = new IdTokenVerifier.Builder()
-        .setIssuer("issuer.example.com")
-        .setAudience(Arrays.asList("myClientId"))
-        .build();
-    ...
-    if (!verifier.verify(idToken)) {...}
- * 
- * - *

- * Note that {@link #verify(IdToken)} only implements a subset of the verification steps, mostly - * just the MUST steps. Please read getAudience() { - return audience; - } - - /** - * Sets the list of trusted audience client IDs or {@code null} to suppress the audience check. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setAudience(Collection audience) { - this.audience = audience; - return this; - } - - /** Returns the seconds of time skew to accept when verifying time. */ - public final long getAcceptableTimeSkewSeconds() { - return acceptableTimeSkewSeconds; - } - - /** - * Sets the seconds of time skew to accept when verifying time (default is - * {@link #DEFAULT_TIME_SKEW_SECONDS}). - * - *

- * It must be greater or equal to zero. - *

- * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setAcceptableTimeSkewSeconds(long acceptableTimeSkewSeconds) { - Preconditions.checkArgument(acceptableTimeSkewSeconds >= 0); - this.acceptableTimeSkewSeconds = acceptableTimeSkewSeconds; - return this; - } - - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/googleapis/MethodOverride.java b/src/autosaveworld/zlibs/com/google/api/client/googleapis/MethodOverride.java deleted file mode 100644 index 80b38c0c..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/googleapis/MethodOverride.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.googleapis; - -import java.io.IOException; - -import autosaveworld.zlibs.com.google.api.client.http.EmptyContent; -import autosaveworld.zlibs.com.google.api.client.http.HttpExecuteInterceptor; -import autosaveworld.zlibs.com.google.api.client.http.HttpMethods; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequest; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequestInitializer; -import autosaveworld.zlibs.com.google.api.client.http.UrlEncodedContent; - -/** - * Thread-safe HTTP request execute interceptor for Google API's that wraps HTTP requests inside of - * a POST request and uses {@link #HEADER} header to specify the actual HTTP method. - * - *

- * Use this for example for an HTTP transport that doesn't support PATCH like - * {@code NetHttpTransport} or {@code UrlFetchTransport}. By default, only the methods not supported - * by the transport will be overridden. When running behind a firewall that does not support certain - * verbs like PATCH, use the {@link MethodOverride.Builder#setOverrideAllMethods(boolean)} - * constructor instead to specify to override all methods. POST is never overridden. - *

- * - *

- * This class also allows GET requests with a long URL (> 2048 chars) to be instead sent using - * method override as a POST request. - *

- * - *

- * Sample usage, taking advantage that this class implements {@link HttpRequestInitializer}: - *

- * - *
-  public static HttpRequestFactory createRequestFactory(HttpTransport transport) {
-    return transport.createRequestFactory(new MethodOverride());
-  }
- * 
- * - *

- * If you have a custom request initializer, take a look at the sample usage for - * {@link HttpExecuteInterceptor}, which this class also implements. - *

- * - * @since 1.4 - * @author Yaniv Inbar - */ -public final class MethodOverride implements HttpExecuteInterceptor, HttpRequestInitializer { - - /** - * Name of the method override header. - * - * @since 1.13 - */ - public static final String HEADER = "X-HTTP-Method-Override"; - - /** Maximum supported URL length. */ - static final int MAX_URL_LENGTH = 2048; - - /** - * Whether to allow all methods (except GET and POST) to be overridden regardless of whether the - * transport supports them. - */ - private final boolean overrideAllMethods; - - /** Only overrides HTTP methods that the HTTP transport does not support. */ - public MethodOverride() { - this(false); - } - - MethodOverride(boolean overrideAllMethods) { - this.overrideAllMethods = overrideAllMethods; - } - - public void initialize(HttpRequest request) { - request.setInterceptor(this); - } - - public void intercept(HttpRequest request) throws IOException { - if (overrideThisMethod(request)) { - String requestMethod = request.getRequestMethod(); - request.setRequestMethod(HttpMethods.POST); - request.getHeaders().set(HEADER, requestMethod); - if (requestMethod.equals(HttpMethods.GET)) { - // take the URI query part and put it into the HTTP body - request.setContent(new UrlEncodedContent(request.getUrl().clone())); - // remove query parameters from URI - request.getUrl().clear(); - } else if (request.getContent() == null) { - // Google servers will fail to process a POST unless the Content-Length header is specified - request.setContent(new EmptyContent()); - } - } - } - - private boolean overrideThisMethod(HttpRequest request) throws IOException { - String requestMethod = request.getRequestMethod(); - if (requestMethod.equals(HttpMethods.POST)) { - return false; - } - if (requestMethod.equals(HttpMethods.GET) - ? request.getUrl().build().length() > MAX_URL_LENGTH : overrideAllMethods) { - return true; - } - return !request.getTransport().supportsMethod(requestMethod); - } - - /** - * Builder for {@link MethodOverride}. - * - * @since 1.12 - * @author Yaniv Inbar - */ - public static final class Builder { - - /** - * Whether to allow all methods (except GET and POST) to be overridden regardless of whether the - * transport supports them. - */ - private boolean overrideAllMethods; - - /** Builds the {@link MethodOverride}. */ - public MethodOverride build() { - return new MethodOverride(overrideAllMethods); - } - - /** - * Returns whether to allow all methods (except GET and POST) to be overridden regardless of - * whether the transport supports them. - */ - public boolean getOverrideAllMethods() { - return overrideAllMethods; - } - - /** - * Sets whether to allow all methods (except GET and POST) to be overridden regardless of - * whether the transport supports them. - * - *

- * Default is {@code false}. - *

- */ - public Builder setOverrideAllMethods(boolean overrideAllMethods) { - this.overrideAllMethods = overrideAllMethods; - return this; - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/googleapis/auth/oauth2/GoogleCredential.java b/src/autosaveworld/zlibs/com/google/api/client/googleapis/auth/oauth2/GoogleCredential.java deleted file mode 100644 index 5c43e6fd..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/googleapis/auth/oauth2/GoogleCredential.java +++ /dev/null @@ -1,742 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.googleapis.auth.oauth2; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.io.StringReader; -import java.security.GeneralSecurityException; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; -import java.util.Collection; -import java.util.Collections; - -import autosaveworld.zlibs.com.google.api.client.auth.oauth2.BearerToken; -import autosaveworld.zlibs.com.google.api.client.auth.oauth2.ClientParametersAuthentication; -import autosaveworld.zlibs.com.google.api.client.auth.oauth2.Credential; -import autosaveworld.zlibs.com.google.api.client.auth.oauth2.CredentialRefreshListener; -import autosaveworld.zlibs.com.google.api.client.auth.oauth2.DataStoreCredentialRefreshListener; -import autosaveworld.zlibs.com.google.api.client.auth.oauth2.TokenRequest; -import autosaveworld.zlibs.com.google.api.client.auth.oauth2.TokenResponse; -import autosaveworld.zlibs.com.google.api.client.googleapis.util.Utils; -import autosaveworld.zlibs.com.google.api.client.http.GenericUrl; -import autosaveworld.zlibs.com.google.api.client.http.HttpExecuteInterceptor; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequestInitializer; -import autosaveworld.zlibs.com.google.api.client.http.HttpTransport; -import autosaveworld.zlibs.com.google.api.client.http.HttpUnsuccessfulResponseHandler; -import autosaveworld.zlibs.com.google.api.client.json.GenericJson; -import autosaveworld.zlibs.com.google.api.client.json.JsonFactory; -import autosaveworld.zlibs.com.google.api.client.json.JsonObjectParser; -import autosaveworld.zlibs.com.google.api.client.json.webtoken.JsonWebSignature; -import autosaveworld.zlibs.com.google.api.client.json.webtoken.JsonWebToken; -import autosaveworld.zlibs.com.google.api.client.util.Beta; -import autosaveworld.zlibs.com.google.api.client.util.Clock; -import autosaveworld.zlibs.com.google.api.client.util.Joiner; -import autosaveworld.zlibs.com.google.api.client.util.PemReader; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.SecurityUtils; -import autosaveworld.zlibs.com.google.api.client.util.PemReader.Section; -import autosaveworld.zlibs.com.google.api.client.util.store.DataStoreFactory; - -/** - * Thread-safe Google-specific implementation of the OAuth 2.0 helper for accessing protected - * resources using an access token, as well as optionally refreshing the access token when it - * expires using a refresh token. - * - *

- * There are three modes supported: access token only, refresh token flow, and service account flow - * (with or without impersonating a user). - *

- * - *

- * If all you have is an access token, you simply pass the {@link TokenResponse} to the credential - * using {@link Builder#setFromTokenResponse(TokenResponse)}. Google credential uses - * {@link BearerToken#authorizationHeaderAccessMethod()} as the access method. Sample usage: - *

- * - *
-  public static GoogleCredential createCredentialWithAccessTokenOnly(TokenResponse tokenResponse) {
-    return new GoogleCredential().setFromTokenResponse(tokenResponse);
-  }
- * 
- * - *

- * If you have a refresh token, it is similar to the case of access token only, but you additionally - * need to pass the credential the client secrets using - * {@link Builder#setClientSecrets(GoogleClientSecrets)} or - * {@link Builder#setClientSecrets(String, String)}. Google credential uses - * {@link GoogleOAuthConstants#TOKEN_SERVER_URL} as the token server URL, and - * {@link ClientParametersAuthentication} with the client ID and secret as the client - * authentication. Sample usage: - *

- * - *
-  public static GoogleCredential createCredentialWithRefreshToken(HttpTransport transport,
-      JsonFactory jsonFactory, GoogleClientSecrets clientSecrets, TokenResponse tokenResponse) {
-    return new GoogleCredential.Builder().setTransport(transport)
-        .setJsonFactory(jsonFactory)
-        .setClientSecrets(clientSecrets)
-        .build()
-        .setFromTokenResponse(tokenResponse);
-  }
- * 
- * - *

- * The service account - * flow is used when you want to access data owned by your client application. You download the - * private key in a {@code .p12} file from the Google APIs Console. Use - * {@link Builder#setServiceAccountId(String)}, - * {@link Builder#setServiceAccountPrivateKeyFromP12File(File)}, and - * {@link Builder#setServiceAccountScopes(Collection)}. Sample usage: - *

- * - *
-  public static GoogleCredential createCredentialForServiceAccount(
-      HttpTransport transport,
-      JsonFactory jsonFactory,
-      String serviceAccountId,
-      Collection<String> serviceAccountScopes,
-      File p12File) throws GeneralSecurityException, IOException {
-    return new GoogleCredential.Builder().setTransport(transport)
-        .setJsonFactory(jsonFactory)
-        .setServiceAccountId(serviceAccountId)
-        .setServiceAccountScopes(serviceAccountScopes)
-        .setServiceAccountPrivateKeyFromP12File(p12File)
-        .build();
-  }
- * 
- * - *

- * You can also use the service account flow to impersonate a user in a domain that you own. This is - * very similar to the service account flow above, but you additionally call - * {@link Builder#setServiceAccountUser(String)}. Sample usage: - *

- * - *
-  public static GoogleCredential createCredentialForServiceAccountImpersonateUser(
-      HttpTransport transport,
-      JsonFactory jsonFactory,
-      String serviceAccountId,
-      Collection<String> serviceAccountScopes,
-      File p12File,
-      String serviceAccountUser) throws GeneralSecurityException, IOException {
-    return new GoogleCredential.Builder().setTransport(transport)
-        .setJsonFactory(jsonFactory)
-        .setServiceAccountId(serviceAccountId)
-        .setServiceAccountScopes(serviceAccountScopes)
-        .setServiceAccountPrivateKeyFromP12File(p12File)
-        .setServiceAccountUser(serviceAccountUser)
-        .build();
-  }
- * 
- * - *

- * If you need to persist the access token in a data store, use {@link DataStoreFactory} and - * {@link Builder#addRefreshListener(CredentialRefreshListener)} with - * {@link DataStoreCredentialRefreshListener}. - *

- * - *

- * If you have a custom request initializer, request execute interceptor, or unsuccessful response - * handler, take a look at the sample usage for {@link HttpExecuteInterceptor} and - * {@link HttpUnsuccessfulResponseHandler}, which are interfaces that this class also implements. - *

- * - * @since 1.7 - * @author Yaniv Inbar - */ -public class GoogleCredential extends Credential { - - static final String SERVICE_ACCOUNT_FILE_TYPE = "service_account"; - - /** - * {@link Beta}
- * Return a credential defined by a Json file. - * - * @param credentialStream the stream with the credential definition. - * @return the credential defined by the credentialStream. - * @throws IOException if the credential cannot be created from the stream. - */ - @Beta - public static GoogleCredential fromStream(InputStream credentialStream) throws IOException { - return fromStream( - credentialStream, - Utils.getDefaultTransport(), - Utils.getDefaultJsonFactory()); - } - - /** - * {@link Beta}
- * Return a credential defined by a Json file. - * - * @param credentialStream the stream with the credential definition. - * @param transport the transport for Http calls. - * @param jsonFactory the factory for Json parsing and formatting. - * @return the credential defined by the credentialStream. - * @throws IOException if the credential cannot be created from the stream. - */ - @Beta - public static GoogleCredential fromStream(InputStream credentialStream, HttpTransport transport, - JsonFactory jsonFactory) throws IOException { - Preconditions.checkNotNull(credentialStream); - Preconditions.checkNotNull(transport); - Preconditions.checkNotNull(jsonFactory); - - JsonObjectParser parser = new JsonObjectParser(jsonFactory); - GenericJson fileContents = parser.parseAndClose( - credentialStream, OAuth2Utils.UTF_8, GenericJson.class); - String fileType = (String) fileContents.get("type"); - if (fileType == null) { - throw new IOException("Error reading credentials from stream, 'type' field not specified."); - } - if (SERVICE_ACCOUNT_FILE_TYPE.equals(fileType)) { - return fromStreamServiceAccount(fileContents, transport, jsonFactory); - } - throw new IOException(String.format( - "Error reading credentials from stream, 'type' value '%s' not recognized." - + " Expecting '%s'.", - fileType, SERVICE_ACCOUNT_FILE_TYPE)); - } - - /** - * Service account ID (typically an e-mail address) or {@code null} if not using the service - * account flow. - */ - private String serviceAccountId; - - /** - * Collection of OAuth scopes to use with the service account flow or {@code null} if not - * using the service account flow. - */ - private Collection serviceAccountScopes; - - /** - * Private key to use with the service account flow or {@code null} if not using the service - * account flow. - */ - private PrivateKey serviceAccountPrivateKey; - - /** - * ID of private key to use with the service account flow or {@code null} if not using the - * service account flow. - */ - private String serviceAccountPrivateKeyId; - - /** - * Email address of the user the application is trying to impersonate in the service account flow - * or {@code null} for none or if not using the service account flow. - */ - private String serviceAccountUser; - - /** - * Constructor with the ability to access protected resources, but not refresh tokens. - * - *

- * To use with the ability to refresh tokens, use {@link Builder}. - *

- */ - public GoogleCredential() { - this(new Builder()); - } - - /** - * @param builder Google credential builder - * - * @since 1.14 - */ - protected GoogleCredential(Builder builder) { - super(builder); - if (builder.serviceAccountPrivateKey == null) { - Preconditions.checkArgument(builder.serviceAccountId == null - && builder.serviceAccountScopes == null && builder.serviceAccountUser == null); - } else { - serviceAccountId = Preconditions.checkNotNull(builder.serviceAccountId); - serviceAccountScopes = Collections.unmodifiableCollection(builder.serviceAccountScopes); - serviceAccountPrivateKey = builder.serviceAccountPrivateKey; - serviceAccountPrivateKeyId = builder.serviceAccountPrivateKeyId; - serviceAccountUser = builder.serviceAccountUser; - } - } - - @Override - public GoogleCredential setAccessToken(String accessToken) { - return (GoogleCredential) super.setAccessToken(accessToken); - } - - @Override - public GoogleCredential setRefreshToken(String refreshToken) { - if (refreshToken != null) { - Preconditions.checkArgument( - getJsonFactory() != null && getTransport() != null && getClientAuthentication() != null, - "Please use the Builder and call setJsonFactory, setTransport and setClientSecrets"); - } - return (GoogleCredential) super.setRefreshToken(refreshToken); - } - - @Override - public GoogleCredential setExpirationTimeMilliseconds(Long expirationTimeMilliseconds) { - return (GoogleCredential) super.setExpirationTimeMilliseconds(expirationTimeMilliseconds); - } - - @Override - public GoogleCredential setExpiresInSeconds(Long expiresIn) { - return (GoogleCredential) super.setExpiresInSeconds(expiresIn); - } - - @Override - public GoogleCredential setFromTokenResponse(TokenResponse tokenResponse) { - return (GoogleCredential) super.setFromTokenResponse(tokenResponse); - } - - @Override - @Beta - protected TokenResponse executeRefreshToken() throws IOException { - if (serviceAccountPrivateKey == null) { - return super.executeRefreshToken(); - } - // service accounts: no refresh token; instead use private key to request new access token - JsonWebSignature.Header header = new JsonWebSignature.Header(); - header.setAlgorithm("RS256"); - header.setType("JWT"); - header.setKeyId(serviceAccountPrivateKeyId); - JsonWebToken.Payload payload = new JsonWebToken.Payload(); - long currentTime = getClock().currentTimeMillis(); - payload.setIssuer(serviceAccountId); - payload.setAudience(getTokenServerEncodedUrl()); - payload.setIssuedAtTimeSeconds(currentTime / 1000); - payload.setExpirationTimeSeconds(currentTime / 1000 + 3600); - payload.setSubject(serviceAccountUser); - payload.put("scope", Joiner.on(' ').join(serviceAccountScopes)); - try { - String assertion = JsonWebSignature.signUsingRsaSha256( - serviceAccountPrivateKey, getJsonFactory(), header, payload); - TokenRequest request = new TokenRequest( - getTransport(), getJsonFactory(), new GenericUrl(getTokenServerEncodedUrl()), - "urn:ietf:params:oauth:grant-type:jwt-bearer"); - request.put("assertion", assertion); - return request.execute(); - } catch (GeneralSecurityException exception) { - IOException e = new IOException(); - e.initCause(exception); - throw e; - } - } - - /** - * Returns the service account ID (typically an e-mail address) or {@code null} if not using the - * service account flow. - */ - public final String getServiceAccountId() { - return serviceAccountId; - } - - /** - * Returns a collection of OAuth scopes to use with the service account flow or {@code null} - * if not using the service account flow. - */ - public final Collection getServiceAccountScopes() { - return serviceAccountScopes; - } - - /** - * Returns the space-separated OAuth scopes to use with the service account flow or - * {@code null} if not using the service account flow. - * - * @since 1.15 - */ - public final String getServiceAccountScopesAsString() { - return serviceAccountScopes == null ? null : Joiner.on(' ').join(serviceAccountScopes); - } - - /** - * Returns the private key to use with the service account flow or {@code null} if not using - * the service account flow. - */ - public final PrivateKey getServiceAccountPrivateKey() { - return serviceAccountPrivateKey; - } - - /** - * {@link Beta}
- * Returns the ID of the private key to use with the service account flow or {@code null} if - * not using the service account flow. - */ - @Beta - public final String getServiceAccountPrivateKeyId() { - return serviceAccountPrivateKeyId; - } - - /** - * Returns the email address of the user the application is trying to impersonate in the service - * account flow or {@code null} for none or if not using the service account flow. - */ - public final String getServiceAccountUser() { - return serviceAccountUser; - } - - /** - * {@link Beta}
- * Indicates whether the credential requires scopes to be specified by calling createScoped - * before use. - */ - @Beta - public boolean createScopedRequired() { - if (serviceAccountPrivateKey == null) { - return false; - } - return (serviceAccountScopes == null || serviceAccountScopes.isEmpty()); - } - - /** - * {@link Beta}
- * For credentials that require scopes, creates a copy of the credential with the specified - * scopes. - */ - @Beta - public GoogleCredential createScoped(Collection scopes) { - if (serviceAccountPrivateKey == null) { - return this; - } - return new GoogleCredential.Builder() - .setServiceAccountPrivateKey(serviceAccountPrivateKey) - .setServiceAccountPrivateKeyId(serviceAccountPrivateKeyId) - .setServiceAccountId(serviceAccountId) - .setServiceAccountUser(serviceAccountUser) - .setServiceAccountScopes(scopes) - .setTokenServerEncodedUrl(getTokenServerEncodedUrl()) - .setTransport(getTransport()) - .setJsonFactory(getJsonFactory()) - .setClock(getClock()) - .build(); - } - - /** - * Google credential builder. - * - *

- * Implementation is not thread-safe. - *

- */ - public static class Builder extends Credential.Builder { - - /** Service account ID (typically an e-mail address) or {@code null} for none. */ - String serviceAccountId; - - /** - * Collection of OAuth scopes to use with the service account flow or {@code null} for none. - */ - Collection serviceAccountScopes; - - /** Private key to use with the service account flow or {@code null} for none. */ - PrivateKey serviceAccountPrivateKey; - - /** Id of the private key to use with the service account flow or {@code null} for none. */ - String serviceAccountPrivateKeyId; - - /** - * Email address of the user the application is trying to impersonate in the service account - * flow or {@code null} for none. - */ - String serviceAccountUser; - - public Builder() { - super(BearerToken.authorizationHeaderAccessMethod()); - setTokenServerEncodedUrl(GoogleOAuthConstants.TOKEN_SERVER_URL); - } - - @Override - public GoogleCredential build() { - return new GoogleCredential(this); - } - - @Override - public Builder setTransport(HttpTransport transport) { - return (Builder) super.setTransport(transport); - } - - @Override - public Builder setJsonFactory(JsonFactory jsonFactory) { - return (Builder) super.setJsonFactory(jsonFactory); - } - - /** - * @since 1.9 - */ - @Override - public Builder setClock(Clock clock) { - return (Builder) super.setClock(clock); - } - - /** - * Sets the client identifier and secret. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setClientSecrets(String clientId, String clientSecret) { - setClientAuthentication(new ClientParametersAuthentication(clientId, clientSecret)); - return this; - } - - /** - * Returns the service account ID (typically an e-mail address) or {@code null} for none. - */ - public final String getServiceAccountId() { - return serviceAccountId; - } - - /** - * Sets the service account ID (typically an e-mail address) or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setServiceAccountId(String serviceAccountId) { - this.serviceAccountId = serviceAccountId; - return this; - } - - /** - * Returns a collection of OAuth scopes to use with the service account flow or {@code null} - * for none. - */ - public final Collection getServiceAccountScopes() { - return serviceAccountScopes; - } - - /** - * Sets the space-separated OAuth scopes to use with the service account flow or - * {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @param serviceAccountScopes collection of scopes to be joined by a space separator (or a - * single value containing multiple space-separated scopes) - * @since 1.15 - */ - public Builder setServiceAccountScopes(Collection serviceAccountScopes) { - this.serviceAccountScopes = serviceAccountScopes; - return this; - } - - /** - * Returns the private key to use with the service account flow or {@code null} for none. - */ - public final PrivateKey getServiceAccountPrivateKey() { - return serviceAccountPrivateKey; - } - - /** - * Sets the private key to use with the service account flow or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setServiceAccountPrivateKey(PrivateKey serviceAccountPrivateKey) { - this.serviceAccountPrivateKey = serviceAccountPrivateKey; - return this; - } - - /** - * {@link Beta}
- * Returns the id of the private key to use with the service account flow or {@code null} - * for none. - */ - @Beta - public final String getServiceAccountPrivateKeyId() { - return serviceAccountPrivateKeyId; - } - - /** - * {@link Beta}
- * Sets the id of the private key to use with the service account flow or {@code null} for - * none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - @Beta - public Builder setServiceAccountPrivateKeyId(String serviceAccountPrivateKeyId) { - this.serviceAccountPrivateKeyId = serviceAccountPrivateKeyId; - return this; - } - - - /** - * Sets the private key to use with the service account flow or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @param p12File input stream to the p12 file (closed at the end of this method in a finally - * block) - */ - public Builder setServiceAccountPrivateKeyFromP12File(File p12File) - throws GeneralSecurityException, IOException { - serviceAccountPrivateKey = SecurityUtils.loadPrivateKeyFromKeyStore( - SecurityUtils.getPkcs12KeyStore(), new FileInputStream(p12File), "notasecret", - "privatekey", "notasecret"); - return this; - } - - /** - * {@link Beta}
- * Sets the private key to use with the service account flow or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @param pemFile input stream to the PEM file (closed at the end of this method in a finally - * block) - * @since 1.13 - */ - @Beta - public Builder setServiceAccountPrivateKeyFromPemFile(File pemFile) - throws GeneralSecurityException, IOException { - byte[] bytes = PemReader.readFirstSectionAndClose(new FileReader(pemFile), "PRIVATE KEY") - .getBase64DecodedBytes(); - serviceAccountPrivateKey = - SecurityUtils.getRsaKeyFactory().generatePrivate(new PKCS8EncodedKeySpec(bytes)); - return this; - } - - /** - * Returns the email address of the user the application is trying to impersonate in the service - * account flow or {@code null} for none. - */ - public final String getServiceAccountUser() { - return serviceAccountUser; - } - - /** - * Sets the email address of the user the application is trying to impersonate in the service - * account flow or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setServiceAccountUser(String serviceAccountUser) { - this.serviceAccountUser = serviceAccountUser; - return this; - } - - @Override - public Builder setRequestInitializer(HttpRequestInitializer requestInitializer) { - return (Builder) super.setRequestInitializer(requestInitializer); - } - - @Override - public Builder addRefreshListener(CredentialRefreshListener refreshListener) { - return (Builder) super.addRefreshListener(refreshListener); - } - - @Override - public Builder setRefreshListeners(Collection refreshListeners) { - return (Builder) super.setRefreshListeners(refreshListeners); - } - - @Override - public Builder setTokenServerUrl(GenericUrl tokenServerUrl) { - return (Builder) super.setTokenServerUrl(tokenServerUrl); - } - - @Override - public Builder setTokenServerEncodedUrl(String tokenServerEncodedUrl) { - return (Builder) super.setTokenServerEncodedUrl(tokenServerEncodedUrl); - } - - @Override - public Builder setClientAuthentication(HttpExecuteInterceptor clientAuthentication) { - return (Builder) super.setClientAuthentication(clientAuthentication); - } - } - - @Beta - private static GoogleCredential fromStreamServiceAccount(GenericJson fileContents, - HttpTransport transport, JsonFactory jsonFactory) throws IOException { - String clientId = (String) fileContents.get("client_id"); - String clientEmail = (String) fileContents.get("client_email"); - String privateKeyPem = (String) fileContents.get("private_key"); - String privateKeyId = (String) fileContents.get("private_key_id"); - if (clientId == null || clientEmail == null || privateKeyPem == null || privateKeyId == null) { - throw new IOException("Error reading service account credential from stream, " - + "expecting 'client_id', 'client_email', 'private_key' and 'private_key_id'."); - } - - PrivateKey privateKey = privateKeyFromPkcs8(privateKeyPem); - - Collection emptyScopes = Collections.emptyList(); - - Builder credentialBuilder = new GoogleCredential.Builder() - .setTransport(transport) - .setJsonFactory(jsonFactory) - .setServiceAccountId(clientEmail) - .setServiceAccountScopes(emptyScopes) - .setServiceAccountPrivateKey(privateKey) - .setServiceAccountPrivateKeyId(privateKeyId); - String tokenUri = (String) fileContents.get("token_uri"); - if (tokenUri != null) { - credentialBuilder.setTokenServerEncodedUrl(tokenUri); - } - // Don't do a refresh at this point, as it will always fail before the scopes are added. - return credentialBuilder.build(); - } - - private static PrivateKey privateKeyFromPkcs8(String privateKeyPem) throws IOException { - Reader reader = new StringReader(privateKeyPem); - Section section = PemReader.readFirstSectionAndClose(reader, "PRIVATE KEY"); - if (section == null) { - throw new IOException("Invalid PKCS8 data."); - } - byte[] bytes = section.getBase64DecodedBytes(); - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes); - Exception unexpectedException = null; - try { - KeyFactory keyFactory = SecurityUtils.getRsaKeyFactory(); - PrivateKey privateKey = keyFactory.generatePrivate(keySpec); - return privateKey; - } catch (NoSuchAlgorithmException exception) { - unexpectedException = exception; - } catch (InvalidKeySpecException exception) { - unexpectedException = exception; - } - throw OAuth2Utils.exceptionWithCause( - new IOException("Unexpected exception reading PKCS data"), unexpectedException); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/googleapis/auth/oauth2/GoogleOAuthConstants.java b/src/autosaveworld/zlibs/com/google/api/client/googleapis/auth/oauth2/GoogleOAuthConstants.java deleted file mode 100644 index fa2bbaeb..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/googleapis/auth/oauth2/GoogleOAuthConstants.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.googleapis.auth.oauth2; - -import autosaveworld.zlibs.com.google.api.client.util.Beta; - -/** - * Constants for Google's OAuth 2.0 implementation. - * - * @since 1.7 - * @author Yaniv Inbar - */ -public class GoogleOAuthConstants { - - /** Encoded URL of Google's end-user authorization server. */ - public static final String AUTHORIZATION_SERVER_URL = "https://accounts.google.com/o/oauth2/auth"; - - /** Encoded URL of Google's token server. */ - public static final String TOKEN_SERVER_URL = "https://accounts.google.com/o/oauth2/token"; - - /** - * {@link Beta}
- * Encoded URL of Google's public certificates. - * - * @since 1.15 - */ - @Beta - public static final String DEFAULT_PUBLIC_CERTS_ENCODED_URL = - "https://www.googleapis.com/oauth2/v1/certs"; - - /** - * Redirect URI to use for an installed application as specified in Using OAuth 2.0 for - * Installed Applications. - */ - public static final String OOB_REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob"; - - private GoogleOAuthConstants() { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/googleapis/auth/oauth2/OAuth2Utils.java b/src/autosaveworld/zlibs/com/google/api/client/googleapis/auth/oauth2/OAuth2Utils.java deleted file mode 100644 index d5ca6bb8..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/googleapis/auth/oauth2/OAuth2Utils.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2014 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.googleapis.auth.oauth2; - -import java.nio.charset.Charset; - -import autosaveworld.zlibs.com.google.api.client.util.Beta; - -/** - * Utilities used by the com.google.api.client.googleapis.auth.oauth2 namespace. - */ -@Beta -public class OAuth2Utils { - - static final Charset UTF_8 = Charset.forName("UTF-8"); - - static T exceptionWithCause(T exception, Throwable cause) { - exception.initCause(cause); - return exception; - } - -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/googleapis/json/GoogleJsonError.java b/src/autosaveworld/zlibs/com/google/api/client/googleapis/json/GoogleJsonError.java deleted file mode 100644 index c702cec4..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/googleapis/json/GoogleJsonError.java +++ /dev/null @@ -1,266 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.googleapis.json; - -import java.io.IOException; -import java.util.Collections; -import java.util.List; - -import autosaveworld.zlibs.com.google.api.client.http.HttpResponse; -import autosaveworld.zlibs.com.google.api.client.json.GenericJson; -import autosaveworld.zlibs.com.google.api.client.json.Json; -import autosaveworld.zlibs.com.google.api.client.json.JsonFactory; -import autosaveworld.zlibs.com.google.api.client.json.JsonObjectParser; -import autosaveworld.zlibs.com.google.api.client.util.Data; -import autosaveworld.zlibs.com.google.api.client.util.Key; - -/** - * Data class representing the Google JSON error response content, as documented for example in Error - * responses. - * - * @since 1.4 - * @author Yaniv Inbar - */ -public class GoogleJsonError extends GenericJson { - - /** - * Parses the given error HTTP response using the given JSON factory. - * - * @param jsonFactory JSON factory - * @param response HTTP response - * @return new instance of the Google JSON error information - * @throws IllegalArgumentException if content type is not {@link Json#MEDIA_TYPE} or if expected - * {@code "data"} or {@code "error"} key is not found - */ - public static GoogleJsonError parse(JsonFactory jsonFactory, HttpResponse response) - throws IOException { - JsonObjectParser jsonObjectParser = new JsonObjectParser.Builder(jsonFactory).setWrapperKeys( - Collections.singleton("error")).build(); - return jsonObjectParser.parseAndClose( - response.getContent(), response.getContentCharset(), GoogleJsonError.class); - } - - static { - // hack to force ProGuard to consider ErrorInfo used, since otherwise it would be stripped out - // see http://code.google.com/p/google-api-java-client/issues/detail?id=527 - Data.nullOf(ErrorInfo.class); - } - - /** Detailed error information. */ - public static class ErrorInfo extends GenericJson { - - /** Error classification or {@code null} for none. */ - @Key - private String domain; - - /** Error reason or {@code null} for none. */ - @Key - private String reason; - - /** Human readable explanation of the error or {@code null} for none. */ - @Key - private String message; - - /** - * Location in the request that caused the error or {@code null} for none or {@code null} for - * none. - */ - @Key - private String location; - - /** Type of location in the request that caused the error or {@code null} for none. */ - @Key - private String locationType; - - /** - * Returns the error classification or {@code null} for none. - * - * @since 1.8 - */ - public final String getDomain() { - return domain; - } - - /** - * Sets the error classification or {@code null} for none. - * - * @since 1.8 - */ - public final void setDomain(String domain) { - this.domain = domain; - } - - /** - * Returns the error reason or {@code null} for none. - * - * @since 1.8 - */ - public final String getReason() { - return reason; - } - - /** - * Sets the error reason or {@code null} for none. - * - * @since 1.8 - */ - public final void setReason(String reason) { - this.reason = reason; - } - - /** - * Returns the human readable explanation of the error or {@code null} for none. - * - * @since 1.8 - */ - public final String getMessage() { - return message; - } - - /** - * Sets the human readable explanation of the error or {@code null} for none. - * - * @since 1.8 - */ - public final void setMessage(String message) { - this.message = message; - } - - /** - * Returns the location in the request that caused the error or {@code null} for none or - * {@code null} for none. - * - * @since 1.8 - */ - public final String getLocation() { - return location; - } - - /** - * Sets the location in the request that caused the error or {@code null} for none or - * {@code null} for none. - * - * @since 1.8 - */ - public final void setLocation(String location) { - this.location = location; - } - - /** - * Returns the type of location in the request that caused the error or {@code null} for none. - * - * @since 1.8 - */ - public final String getLocationType() { - return locationType; - } - - /** - * Sets the type of location in the request that caused the error or {@code null} for none. - * - * @since 1.8 - */ - public final void setLocationType(String locationType) { - this.locationType = locationType; - } - - @Override - public ErrorInfo set(String fieldName, Object value) { - return (ErrorInfo) super.set(fieldName, value); - } - - @Override - public ErrorInfo clone() { - return (ErrorInfo) super.clone(); - } - } - - /** List of detailed errors or {@code null} for none. */ - @Key - private List errors; - - /** HTTP status code of this response or {@code null} for none. */ - @Key - private int code; - - /** Human-readable explanation of the error or {@code null} for none. */ - @Key - private String message; - - /** - * Returns the list of detailed errors or {@code null} for none. - * - * @since 1.8 - */ - public final List getErrors() { - return errors; - } - - /** - * Sets the list of detailed errors or {@code null} for none. - * - * @since 1.8 - */ - public final void setErrors(List errors) { - this.errors = errors; - } - - /** - * Returns the HTTP status code of this response or {@code null} for none. - * - * @since 1.8 - */ - public final int getCode() { - return code; - } - - /** - * Sets the HTTP status code of this response or {@code null} for none. - * - * @since 1.8 - */ - public final void setCode(int code) { - this.code = code; - } - - /** - * Returns the human-readable explanation of the error or {@code null} for none. - * - * @since 1.8 - */ - public final String getMessage() { - return message; - } - - /** - * Sets the human-readable explanation of the error or {@code null} for none. - * - * @since 1.8 - */ - public final void setMessage(String message) { - this.message = message; - } - - @Override - public GoogleJsonError set(String fieldName, Object value) { - return (GoogleJsonError) super.set(fieldName, value); - } - - @Override - public GoogleJsonError clone() { - return (GoogleJsonError) super.clone(); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/googleapis/json/GoogleJsonErrorContainer.java b/src/autosaveworld/zlibs/com/google/api/client/googleapis/json/GoogleJsonErrorContainer.java deleted file mode 100644 index d792d29d..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/googleapis/json/GoogleJsonErrorContainer.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.googleapis.json; - -import autosaveworld.zlibs.com.google.api.client.json.GenericJson; -import autosaveworld.zlibs.com.google.api.client.util.Key; - -/** - * Data class representing a container of {@link GoogleJsonError}. - * - * @since 1.9 - * @author rmistry@google.com (Ravi Mistry) - */ -public class GoogleJsonErrorContainer extends GenericJson { - - @Key - private GoogleJsonError error; - - /** Returns the {@link GoogleJsonError}. */ - public final GoogleJsonError getError() { - return error; - } - - /** Sets the {@link GoogleJsonError}. */ - public final void setError(GoogleJsonError error) { - this.error = error; - } - - @Override - public GoogleJsonErrorContainer set(String fieldName, Object value) { - return (GoogleJsonErrorContainer) super.set(fieldName, value); - } - - @Override - public GoogleJsonErrorContainer clone() { - return (GoogleJsonErrorContainer) super.clone(); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/googleapis/json/GoogleJsonResponseException.java b/src/autosaveworld/zlibs/com/google/api/client/googleapis/json/GoogleJsonResponseException.java deleted file mode 100644 index 61b74676..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/googleapis/json/GoogleJsonResponseException.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.googleapis.json; - -import java.io.IOException; - -import autosaveworld.zlibs.com.google.api.client.http.HttpMediaType; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequest; -import autosaveworld.zlibs.com.google.api.client.http.HttpResponse; -import autosaveworld.zlibs.com.google.api.client.http.HttpResponseException; -import autosaveworld.zlibs.com.google.api.client.json.Json; -import autosaveworld.zlibs.com.google.api.client.json.JsonFactory; -import autosaveworld.zlibs.com.google.api.client.json.JsonParser; -import autosaveworld.zlibs.com.google.api.client.json.JsonToken; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.StringUtils; - -/** - * Exception thrown when an error status code is detected in an HTTP response to a Google API that - * uses the JSON format, using the format specified in Error - * Responses. - * - *

- * To execute a request, call {@link #execute(JsonFactory, HttpRequest)}. This will throw a - * {@link GoogleJsonResponseException} on an error response. To get the structured details, use - * {@link #getDetails()}. - *

- * - *
-  static void executeShowingError(JsonFactory factory, HttpRequest request) throws IOException {
-    try {
-      GoogleJsonResponseException.execute(factory, request);
-    } catch (GoogleJsonResponseException e) {
-      System.err.println(e.getDetails());
-    }
-  }
- * 
- * - * @since 1.6 - * @author Yaniv Inbar - */ -public class GoogleJsonResponseException extends HttpResponseException { - - private static final long serialVersionUID = 409811126989994864L; - - /** Google JSON error details or {@code null} for none (for example if response is not JSON). */ - private final transient GoogleJsonError details; - - /** - * @param builder builder - * @param details Google JSON error details - * @since 1.21.0 - */ - public GoogleJsonResponseException(Builder builder, GoogleJsonError details) { - super(builder); - this.details = details; - } - - /** - * Returns the Google JSON error details or {@code null} for none (for example if response is not - * JSON). - */ - public final GoogleJsonError getDetails() { - return details; - } - - /** - * Returns a new instance of {@link GoogleJsonResponseException}. - * - *

- * If there is a JSON error response, it is parsed using {@link GoogleJsonError}, which can be - * inspected using {@link #getDetails()}. Otherwise, the full response content is read and - * included in the exception message. - *

- * - * @param jsonFactory JSON factory - * @param response HTTP response - * @return new instance of {@link GoogleJsonResponseException} - */ - public static GoogleJsonResponseException from(JsonFactory jsonFactory, HttpResponse response) { - HttpResponseException.Builder builder = new HttpResponseException.Builder( - response.getStatusCode(), response.getStatusMessage(), response.getHeaders()); - // details - Preconditions.checkNotNull(jsonFactory); - GoogleJsonError details = null; - String detailString = null; - try { - if (!response.isSuccessStatusCode() - && HttpMediaType.equalsIgnoreParameters(Json.MEDIA_TYPE, response.getContentType()) - && response.getContent() != null) { - JsonParser parser = null; - try { - parser = jsonFactory.createJsonParser(response.getContent()); - JsonToken currentToken = parser.getCurrentToken(); - // token is null at start, so get next token - if (currentToken == null) { - currentToken = parser.nextToken(); - } - // check for empty content - if (currentToken != null) { - // make sure there is an "error" key - parser.skipToKey("error"); - if (parser.getCurrentToken() != JsonToken.END_OBJECT) { - details = parser.parseAndClose(GoogleJsonError.class); - detailString = details.toPrettyString(); - } - } - } catch (IOException exception) { - // it would be bad to throw an exception while throwing an exception - exception.printStackTrace(); - } finally { - if (parser == null) { - response.ignore(); - } else if (details == null) { - parser.close(); - } - } - } else { - detailString = response.parseAsString(); - } - } catch (IOException exception) { - // it would be bad to throw an exception while throwing an exception - exception.printStackTrace(); - } - // message - StringBuilder message = HttpResponseException.computeMessageBuffer(response); - if (!autosaveworld.zlibs.com.google.api.client.util.Strings.isNullOrEmpty(detailString)) { - message.append(StringUtils.LINE_SEPARATOR).append(detailString); - builder.setContent(detailString); - } - builder.setMessage(message.toString()); - // result - return new GoogleJsonResponseException(builder, details); - } - - /** - * Executes an HTTP request using {@link HttpRequest#execute()}, but throws a - * {@link GoogleJsonResponseException} on error instead of {@link HttpResponseException}. - * - *

- * Callers should call {@link HttpResponse#disconnect} when the returned HTTP response object is - * no longer needed. However, {@link HttpResponse#disconnect} does not have to be called if the - * response stream is properly closed. Example usage: - *

- * - *
-     HttpResponse response = GoogleJsonResponseException.execute(jsonFactory, request);
-     try {
-       // process the HTTP response object
-     } finally {
-       response.disconnect();
-     }
-   * 
- * - * @param jsonFactory JSON factory - * @param request HTTP request - * @return HTTP response for an HTTP success code (or error code if - * {@link HttpRequest#getThrowExceptionOnExecuteError()}) - * @throws GoogleJsonResponseException for an HTTP error code (only if not - * {@link HttpRequest#getThrowExceptionOnExecuteError()}) - * @throws IOException some other kind of I/O exception - * @since 1.7 - */ - public static HttpResponse execute(JsonFactory jsonFactory, HttpRequest request) - throws GoogleJsonResponseException, IOException { - Preconditions.checkNotNull(jsonFactory); - boolean originalThrowExceptionOnExecuteError = request.getThrowExceptionOnExecuteError(); - if (originalThrowExceptionOnExecuteError) { - request.setThrowExceptionOnExecuteError(false); - } - HttpResponse response = request.execute(); - request.setThrowExceptionOnExecuteError(originalThrowExceptionOnExecuteError); - if (!originalThrowExceptionOnExecuteError || response.isSuccessStatusCode()) { - return response; - } - throw GoogleJsonResponseException.from(jsonFactory, response); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/googleapis/media/MediaHttpUploader.java b/src/autosaveworld/zlibs/com/google/api/client/googleapis/media/MediaHttpUploader.java deleted file mode 100644 index eaf43d5e..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/googleapis/media/MediaHttpUploader.java +++ /dev/null @@ -1,941 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.googleapis.media; - -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; - -import autosaveworld.zlibs.com.google.api.client.googleapis.MethodOverride; -import autosaveworld.zlibs.com.google.api.client.http.AbstractInputStreamContent; -import autosaveworld.zlibs.com.google.api.client.http.ByteArrayContent; -import autosaveworld.zlibs.com.google.api.client.http.EmptyContent; -import autosaveworld.zlibs.com.google.api.client.http.GZipEncoding; -import autosaveworld.zlibs.com.google.api.client.http.GenericUrl; -import autosaveworld.zlibs.com.google.api.client.http.HttpBackOffIOExceptionHandler; -import autosaveworld.zlibs.com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; -import autosaveworld.zlibs.com.google.api.client.http.HttpContent; -import autosaveworld.zlibs.com.google.api.client.http.HttpHeaders; -import autosaveworld.zlibs.com.google.api.client.http.HttpMethods; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequest; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequestFactory; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequestInitializer; -import autosaveworld.zlibs.com.google.api.client.http.HttpResponse; -import autosaveworld.zlibs.com.google.api.client.http.HttpTransport; -import autosaveworld.zlibs.com.google.api.client.http.InputStreamContent; -import autosaveworld.zlibs.com.google.api.client.http.MultipartContent; -import autosaveworld.zlibs.com.google.api.client.util.Beta; -import autosaveworld.zlibs.com.google.api.client.util.ByteStreams; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.Sleeper; - -/** - * Media HTTP Uploader, with support for both direct and resumable media uploads. Documentation is - * available here. - * - *

- * For resumable uploads, when the media content length is known, if the provided - * {@link InputStream} has {@link InputStream#markSupported} as {@code false} then it is wrapped in - * an {@link BufferedInputStream} to support the {@link InputStream#mark} and - * {@link InputStream#reset} methods required for handling server errors. If the media content - * length is unknown then each chunk is stored temporarily in memory. This is required to determine - * when the last chunk is reached. - *

- * - *

- * See {@link #setDisableGZipContent(boolean)} for information on when content is gzipped and how to - * control that behavior. - *

- * - *

- * Back-off is disabled by default. To enable it for an abnormal HTTP response and an I/O exception - * you should call {@link HttpRequest#setUnsuccessfulResponseHandler} with a new - * {@link HttpBackOffUnsuccessfulResponseHandler} instance and - * {@link HttpRequest#setIOExceptionHandler} with {@link HttpBackOffIOExceptionHandler}. - *

- * - *

- * Upgrade warning: in prior version 1.14 exponential back-off was enabled by default for an - * abnormal HTTP response and there was a regular retry (without back-off) when I/O exception was - * thrown. Starting with version 1.15 back-off is disabled and there is no retry on I/O exception by - * default. - *

- * - *

- * Upgrade warning: in prior version 1.16 {@link #serverErrorCallback} was public but starting with - * version 1.17 it has been removed from the public API, and changed to be package private. - *

- * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.9 - * - * @author rmistry@google.com (Ravi Mistry) - * @author peleyal@google.com (Eyal Peled) - */ -public final class MediaHttpUploader { - - /** - * Upload content type header. - * - * @since 1.13 - */ - public static final String CONTENT_LENGTH_HEADER = "X-Upload-Content-Length"; - - /** - * Upload content length header. - * - * @since 1.13 - */ - public static final String CONTENT_TYPE_HEADER = "X-Upload-Content-Type"; - - /** - * Upload state associated with the Media HTTP uploader. - */ - public enum UploadState { - /** The upload process has not started yet. */ - NOT_STARTED, - - /** Set before the initiation request is sent. */ - INITIATION_STARTED, - - /** Set after the initiation request completes. */ - INITIATION_COMPLETE, - - /** Set after a media file chunk is uploaded. */ - MEDIA_IN_PROGRESS, - - /** Set after the complete media file is successfully uploaded. */ - MEDIA_COMPLETE - } - - /** The current state of the uploader. */ - private UploadState uploadState = UploadState.NOT_STARTED; - - static final int MB = 0x100000; - private static final int KB = 0x400; - - /** - * Minimum number of bytes that can be uploaded to the server (set to 256KB). - */ - public static final int MINIMUM_CHUNK_SIZE = 256 * KB; - - /** - * Default maximum number of bytes that will be uploaded to the server in any single HTTP request - * (set to 10 MB). - */ - public static final int DEFAULT_CHUNK_SIZE = 10 * MB; - - /** The HTTP content of the media to be uploaded. */ - private final AbstractInputStreamContent mediaContent; - - /** The request factory for connections to the server. */ - private final HttpRequestFactory requestFactory; - - /** The transport to use for requests. */ - private final HttpTransport transport; - - /** HTTP content metadata of the media to be uploaded or {@code null} for none. */ - private HttpContent metadata; - - /** - * The length of the HTTP media content. - * - *

- * {@code 0} before it is lazily initialized in {@link #getMediaContentLength()} after which it - * could still be {@code 0} for empty media content. Will be {@code < 0} if the media content - * length has not been specified. - *

- */ - private long mediaContentLength; - - /** - * Determines if media content length has been calculated yet in {@link #getMediaContentLength()}. - */ - private boolean isMediaContentLengthCalculated; - - /** - * The HTTP method used for the initiation request. - * - *

- * Can only be {@link HttpMethods#POST} (for media upload) or {@link HttpMethods#PUT} (for media - * update). The default value is {@link HttpMethods#POST}. - *

- */ - private String initiationRequestMethod = HttpMethods.POST; - - /** The HTTP headers used in the initiation request. */ - private HttpHeaders initiationHeaders = new HttpHeaders(); - - /** - * The HTTP request object that is currently used to send upload requests or {@code null} before - * {@link #upload}. - */ - private HttpRequest currentRequest; - - /** An Input stream of the HTTP media content or {@code null} before {@link #upload}. */ - private InputStream contentInputStream; - - /** - * Determines whether direct media upload is enabled or disabled. If value is set to {@code true} - * then a direct upload will be done where the whole media content is uploaded in a single request - * If value is set to {@code false} then the upload uses the resumable media upload protocol to - * upload in data chunks. Defaults to {@code false}. - */ - private boolean directUploadEnabled; - - /** - * Progress listener to send progress notifications to or {@code null} for none. - */ - private MediaHttpUploaderProgressListener progressListener; - - /** - * The media content length is used in the "Content-Range" header. If we reached the end of the - * stream, this variable will be set with the length of the stream. This value is used only in - * resumable media upload. - */ - String mediaContentLengthStr = "*"; - - /** - * The number of bytes the server received so far. This value will not be calculated for direct - * uploads when the content length is not known in advance. - */ - // TODO(rmistry): Figure out a way to compute the content length using CountingInputStream. - private long totalBytesServerReceived; - - /** - * Maximum size of individual chunks that will get uploaded by single HTTP requests. The default - * value is {@link #DEFAULT_CHUNK_SIZE}. - */ - private int chunkSize = DEFAULT_CHUNK_SIZE; - - /** - * Used to cache a single byte when the media content length is unknown or {@code null} for none. - */ - private Byte cachedByte; - - /** - * The number of bytes the client had sent to the server so far or {@code 0} for none. It is used - * for resumable media upload when the media content length is not specified. - */ - private long totalBytesClientSent; - - /** - * The number of bytes of the current chunk which was sent to the server or {@code 0} for none. - * This value equals to chunk size for each chunk the client send to the server, except for the - * ending chunk. - */ - private int currentChunkLength; - - /** - * The content buffer of the current request or {@code null} for none. It is used for resumable - * media upload when the media content length is not specified. It is instantiated for every - * request in {@link #setContentAndHeadersOnCurrentRequest} and is set to {@code null} when the - * request is completed in {@link #upload}. - */ - private byte currentRequestContentBuffer[]; - - /** - * Whether to disable GZip compression of HTTP content. - * - *

- * The default value is {@code false}. - *

- */ - private boolean disableGZipContent; - - /** Sleeper. **/ - Sleeper sleeper = Sleeper.DEFAULT; - - /** - * Construct the {@link MediaHttpUploader}. - * - *

- * The input stream received by calling {@link AbstractInputStreamContent#getInputStream} is - * closed when the upload process is successfully completed. For resumable uploads, when the media - * content length is known, if the input stream has {@link InputStream#markSupported} as - * {@code false} then it is wrapped in an {@link BufferedInputStream} to support the - * {@link InputStream#mark} and {@link InputStream#reset} methods required for handling server - * errors. If the media content length is unknown then each chunk is stored temporarily in memory. - * This is required to determine when the last chunk is reached. - *

- * - * @param mediaContent The Input stream content of the media to be uploaded - * @param transport The transport to use for requests - * @param httpRequestInitializer The initializer to use when creating an {@link HttpRequest} or - * {@code null} for none - */ - public MediaHttpUploader(AbstractInputStreamContent mediaContent, HttpTransport transport, - HttpRequestInitializer httpRequestInitializer) { - this.mediaContent = Preconditions.checkNotNull(mediaContent); - this.transport = Preconditions.checkNotNull(transport); - this.requestFactory = httpRequestInitializer == null - ? transport.createRequestFactory() : transport.createRequestFactory(httpRequestInitializer); - } - - /** - * Executes a direct media upload or resumable media upload conforming to the specifications - * listed here. - * - *

- * This method is not reentrant. A new instance of {@link MediaHttpUploader} must be instantiated - * before upload called be called again. - *

- * - *

- * If an error is encountered during the request execution the caller is responsible for parsing - * the response correctly. For example for JSON errors: - *

- * - *
-    if (!response.isSuccessStatusCode()) {
-      throw GoogleJsonResponseException.from(jsonFactory, response);
-    }
-   * 
- * - *

- * Callers should call {@link HttpResponse#disconnect} when the returned HTTP response object is - * no longer needed. However, {@link HttpResponse#disconnect} does not have to be called if the - * response stream is properly closed. Example usage: - *

- * - *
-     HttpResponse response = batch.upload(initiationRequestUrl);
-     try {
-       // process the HTTP response object
-     } finally {
-       response.disconnect();
-     }
-   * 
- * - * @param initiationRequestUrl The request URL where the initiation request will be sent - * @return HTTP response - */ - public HttpResponse upload(GenericUrl initiationRequestUrl) throws IOException { - Preconditions.checkArgument(uploadState == UploadState.NOT_STARTED); - - if (directUploadEnabled) { - return directUpload(initiationRequestUrl); - } - return resumableUpload(initiationRequestUrl); - } - - /** - * Direct Uploads the media. - * - * @param initiationRequestUrl The request URL where the initiation request will be sent - * @return HTTP response - */ - private HttpResponse directUpload(GenericUrl initiationRequestUrl) throws IOException { - updateStateAndNotifyListener(UploadState.MEDIA_IN_PROGRESS); - - HttpContent content = mediaContent; - if (metadata != null) { - content = new MultipartContent().setContentParts(Arrays.asList(metadata, mediaContent)); - initiationRequestUrl.put("uploadType", "multipart"); - } else { - initiationRequestUrl.put("uploadType", "media"); - } - HttpRequest request = - requestFactory.buildRequest(initiationRequestMethod, initiationRequestUrl, content); - request.getHeaders().putAll(initiationHeaders); - // We do not have to do anything special here if media content length is unspecified because - // direct media upload works even when the media content length == -1. - HttpResponse response = executeCurrentRequest(request); - boolean responseProcessed = false; - try { - if (isMediaLengthKnown()) { - totalBytesServerReceived = getMediaContentLength(); - } - updateStateAndNotifyListener(UploadState.MEDIA_COMPLETE); - responseProcessed = true; - } finally { - if (!responseProcessed) { - response.disconnect(); - } - } - return response; - } - - /** - * Uploads the media in a resumable manner. - * - * @param initiationRequestUrl The request URL where the initiation request will be sent - * @return HTTP response - */ - private HttpResponse resumableUpload(GenericUrl initiationRequestUrl) throws IOException { - // Make initial request to get the unique upload URL. - HttpResponse initialResponse = executeUploadInitiation(initiationRequestUrl); - if (!initialResponse.isSuccessStatusCode()) { - // If the initiation request is not successful return it immediately. - return initialResponse; - } - GenericUrl uploadUrl; - try { - uploadUrl = new GenericUrl(initialResponse.getHeaders().getLocation()); - } finally { - initialResponse.disconnect(); - } - - // Convert media content into a byte stream to upload in chunks. - contentInputStream = mediaContent.getInputStream(); - if (!contentInputStream.markSupported() && isMediaLengthKnown()) { - // If we know the media content length then wrap the stream into a Buffered input stream to - // support the {@link InputStream#mark} and {@link InputStream#reset} methods required for - // handling server errors. - contentInputStream = new BufferedInputStream(contentInputStream); - } - - HttpResponse response; - // Upload the media content in chunks. - while (true) { - currentRequest = requestFactory.buildPutRequest(uploadUrl, null); - setContentAndHeadersOnCurrentRequest(); - // set mediaErrorHandler as I/O exception handler and as unsuccessful response handler for - // calling to serverErrorCallback on an I/O exception or an abnormal HTTP response - new MediaUploadErrorHandler(this, currentRequest); - - if (isMediaLengthKnown()) { - // TODO(rmistry): Support gzipping content for the case where media content length is - // known (https://code.google.com/p/google-api-java-client/issues/detail?id=691). - response = executeCurrentRequestWithoutGZip(currentRequest); - } else { - response = executeCurrentRequest(currentRequest); - } - boolean returningResponse = false; - try { - if (response.isSuccessStatusCode()) { - totalBytesServerReceived = getMediaContentLength(); - if (mediaContent.getCloseInputStream()) { - contentInputStream.close(); - } - updateStateAndNotifyListener(UploadState.MEDIA_COMPLETE); - returningResponse = true; - return response; - } - - if (response.getStatusCode() != 308) { - returningResponse = true; - return response; - } - - // Check to see if the upload URL has changed on the server. - String updatedUploadUrl = response.getHeaders().getLocation(); - if (updatedUploadUrl != null) { - uploadUrl = new GenericUrl(updatedUploadUrl); - } - - // we check the amount of bytes the server received so far, because the server may process - // fewer bytes than the amount of bytes the client had sent - long newBytesServerReceived = getNextByteIndex(response.getHeaders().getRange()); - // the server can receive any amount of bytes from 0 to current chunk length - long currentBytesServerReceived = newBytesServerReceived - totalBytesServerReceived; - Preconditions.checkState( - currentBytesServerReceived >= 0 && currentBytesServerReceived <= currentChunkLength); - long copyBytes = currentChunkLength - currentBytesServerReceived; - if (isMediaLengthKnown()) { - if (copyBytes > 0) { - // If the server didn't receive all the bytes the client sent the current position of - // the input stream is incorrect. So we should reset the stream and skip those bytes - // that the server had already received. - // Otherwise (the server got all bytes the client sent), the stream is in its right - // position, and we can continue from there - contentInputStream.reset(); - long actualSkipValue = contentInputStream.skip(currentBytesServerReceived); - Preconditions.checkState(currentBytesServerReceived == actualSkipValue); - } - } else if (copyBytes == 0) { - // server got all the bytes, so we don't need to use this buffer. Otherwise, we have to - // keep the buffer and copy part (or all) of its bytes to the stream we are sending to the - // server - currentRequestContentBuffer = null; - } - totalBytesServerReceived = newBytesServerReceived; - - updateStateAndNotifyListener(UploadState.MEDIA_IN_PROGRESS); - } finally { - if (!returningResponse) { - response.disconnect(); - } - } - } - } - - /** - * @return {@code true} if the media length is known, otherwise {@code false} - */ - private boolean isMediaLengthKnown() throws IOException { - return getMediaContentLength() >= 0; - } - - /** - * Uses lazy initialization to compute the media content length. - * - *

- * This is done to avoid throwing an {@link IOException} in the constructor. - *

- */ - private long getMediaContentLength() throws IOException { - if (!isMediaContentLengthCalculated) { - mediaContentLength = mediaContent.getLength(); - isMediaContentLengthCalculated = true; - } - return mediaContentLength; - } - - /** - * This method sends a POST request with empty content to get the unique upload URL. - * - * @param initiationRequestUrl The request URL where the initiation request will be sent - */ - private HttpResponse executeUploadInitiation(GenericUrl initiationRequestUrl) throws IOException { - updateStateAndNotifyListener(UploadState.INITIATION_STARTED); - - initiationRequestUrl.put("uploadType", "resumable"); - HttpContent content = metadata == null ? new EmptyContent() : metadata; - HttpRequest request = - requestFactory.buildRequest(initiationRequestMethod, initiationRequestUrl, content); - initiationHeaders.set(CONTENT_TYPE_HEADER, mediaContent.getType()); - if (isMediaLengthKnown()) { - initiationHeaders.set(CONTENT_LENGTH_HEADER, getMediaContentLength()); - } - request.getHeaders().putAll(initiationHeaders); - HttpResponse response = executeCurrentRequest(request); - boolean notificationCompleted = false; - - try { - updateStateAndNotifyListener(UploadState.INITIATION_COMPLETE); - notificationCompleted = true; - } finally { - if (!notificationCompleted) { - response.disconnect(); - } - } - return response; - } - - /** - * Executes the current request with some minimal common code. - * - * @param request current request - * @return HTTP response - */ - private HttpResponse executeCurrentRequestWithoutGZip(HttpRequest request) throws IOException { - // method override for non-POST verbs - new MethodOverride().intercept(request); - // don't throw an exception so we can let a custom Google exception be thrown - request.setThrowExceptionOnExecuteError(false); - // execute the request - HttpResponse response = request.execute(); - return response; - } - - /** - * Executes the current request with some common code that includes exponential backoff and GZip - * encoding. - * - * @param request current request - * @return HTTP response - */ - private HttpResponse executeCurrentRequest(HttpRequest request) throws IOException { - // enable GZip encoding if necessary - if (!disableGZipContent && !(request.getContent() instanceof EmptyContent)) { - request.setEncoding(new GZipEncoding()); - } - // execute request - HttpResponse response = executeCurrentRequestWithoutGZip(request); - return response; - } - - /** - * Sets the HTTP media content chunk and the required headers that should be used in the upload - * request. - */ - private void setContentAndHeadersOnCurrentRequest() throws IOException { - int blockSize; - if (isMediaLengthKnown()) { - // We know exactly what the blockSize will be because we know the media content length. - blockSize = (int) Math.min(chunkSize, getMediaContentLength() - totalBytesServerReceived); - } else { - // Use the chunkSize as the blockSize because we do know what what it is yet. - blockSize = chunkSize; - } - - AbstractInputStreamContent contentChunk; - int actualBlockSize = blockSize; - if (isMediaLengthKnown()) { - // Mark the current position in case we need to retry the request. - contentInputStream.mark(blockSize); - - InputStream limitInputStream = ByteStreams.limit(contentInputStream, blockSize); - contentChunk = new InputStreamContent( - mediaContent.getType(), limitInputStream).setRetrySupported(true) - .setLength(blockSize).setCloseInputStream(false); - mediaContentLengthStr = String.valueOf(getMediaContentLength()); - } else { - // If the media content length is not known we implement a custom buffered input stream that - // enables us to detect the length of the media content when the last chunk is sent. We - // accomplish this by always trying to read an extra byte further than the end of the current - // chunk. - int actualBytesRead; - int bytesAllowedToRead; - - // amount of bytes which need to be copied from last chunk buffer - int copyBytes = 0; - if (currentRequestContentBuffer == null) { - bytesAllowedToRead = cachedByte == null ? blockSize + 1 : blockSize; - currentRequestContentBuffer = new byte[blockSize + 1]; - if (cachedByte != null) { - currentRequestContentBuffer[0] = cachedByte; - } - } else { - // currentRequestContentBuffer is not null that means one of the following: - // 1. This is a request to recover from a server error (e.g. 503) - // or - // 2. The server received less bytes than the amount of bytes the client had sent. For - // example, the client sends bytes 100-199, but the server returns back status code 308, - // and its "Range" header is "bytes=0-150". - // In that case, the new request will be constructed from the previous request's byte buffer - // plus new bytes from the stream. - copyBytes = (int) (totalBytesClientSent - totalBytesServerReceived); - // shift copyBytes bytes to the beginning - those are the bytes which weren't received by - // the server in the last chunk. - System.arraycopy(currentRequestContentBuffer, currentChunkLength - copyBytes, - currentRequestContentBuffer, 0, copyBytes); - if (cachedByte != null) { - // add the last cached byte to the buffer - currentRequestContentBuffer[copyBytes] = cachedByte; - } - - bytesAllowedToRead = blockSize - copyBytes; - } - - actualBytesRead = ByteStreams.read( - contentInputStream, currentRequestContentBuffer, blockSize + 1 - bytesAllowedToRead, - bytesAllowedToRead); - - if (actualBytesRead < bytesAllowedToRead) { - actualBlockSize = copyBytes + Math.max(0, actualBytesRead); - if (cachedByte != null) { - actualBlockSize++; - cachedByte = null; - } - - if (mediaContentLengthStr.equals("*")) { - // At this point we know we reached the media content length because we either read less - // than the specified chunk size or there is no more data left to be read. - mediaContentLengthStr = String.valueOf(totalBytesServerReceived + actualBlockSize); - } - } else { - cachedByte = currentRequestContentBuffer[blockSize]; - } - - contentChunk = new ByteArrayContent( - mediaContent.getType(), currentRequestContentBuffer, 0, actualBlockSize); - totalBytesClientSent = totalBytesServerReceived + actualBlockSize; - } - - currentChunkLength = actualBlockSize; - currentRequest.setContent(contentChunk); - if (actualBlockSize == 0) { - // No bytes to upload. Either zero content media being uploaded, or a server failure on the - // last write, even though the write actually succeeded. Either way, - // mediaContentLengthStr will contain the actual media length. - currentRequest.getHeaders().setContentRange("bytes */" + mediaContentLengthStr); - } else { - currentRequest.getHeaders().setContentRange("bytes " + totalBytesServerReceived + "-" - + (totalBytesServerReceived + actualBlockSize - 1) + "/" + mediaContentLengthStr); - } - } - - /** - * {@link Beta}
- * The call back method that will be invoked on a server error or an I/O exception during - * resumable upload inside {@link #upload}. - * - *

- * This method changes the current request to query the current status of the upload to find how - * many bytes were successfully uploaded before the server error occurred. - *

- */ - @Beta - void serverErrorCallback() throws IOException { - Preconditions.checkNotNull(currentRequest, "The current request should not be null"); - - // Query the current status of the upload by issuing an empty PUT request on the upload URI. - currentRequest.setContent(new EmptyContent()); - currentRequest.getHeaders().setContentRange("bytes */" + mediaContentLengthStr); - } - - /** - * Returns the next byte index identifying data that the server has not yet received, obtained - * from the HTTP Range header (E.g a header of "Range: 0-55" would cause 56 to be returned). - * null or malformed headers cause 0 to be returned. - * - * @param rangeHeader in the HTTP response - * @return the byte index beginning where the server has yet to receive data - */ - private long getNextByteIndex(String rangeHeader) { - if (rangeHeader == null) { - return 0L; - } - return Long.parseLong(rangeHeader.substring(rangeHeader.indexOf('-') + 1)) + 1; - } - - /** Returns HTTP content metadata for the media request or {@code null} for none. */ - public HttpContent getMetadata() { - return metadata; - } - - /** Sets HTTP content metadata for the media request or {@code null} for none. */ - public MediaHttpUploader setMetadata(HttpContent metadata) { - this.metadata = metadata; - return this; - } - - /** Returns the HTTP content of the media to be uploaded. */ - public HttpContent getMediaContent() { - return mediaContent; - } - - /** Returns the transport to use for requests. */ - public HttpTransport getTransport() { - return transport; - } - - /** - * Sets whether direct media upload is enabled or disabled. - * - *

- * If value is set to {@code true} then a direct upload will be done where the whole media content - * is uploaded in a single request. If value is set to {@code false} then the upload uses the - * resumable media upload protocol to upload in data chunks. - *

- * - *

- * Direct upload is recommended if the content size falls below a certain minimum limit. This is - * because there's minimum block write size for some Google APIs, so if the resumable request - * fails in the space of that first block, the client will have to restart from the beginning - * anyway. - *

- * - *

- * Defaults to {@code false}. - *

- * - * @since 1.9 - */ - public MediaHttpUploader setDirectUploadEnabled(boolean directUploadEnabled) { - this.directUploadEnabled = directUploadEnabled; - return this; - } - - /** - * Returns whether direct media upload is enabled or disabled. If value is set to {@code true} - * then a direct upload will be done where the whole media content is uploaded in a single - * request. If value is set to {@code false} then the upload uses the resumable media upload - * protocol to upload in data chunks. Defaults to {@code false}. - * - * @since 1.9 - */ - public boolean isDirectUploadEnabled() { - return directUploadEnabled; - } - - /** - * Sets the progress listener to send progress notifications to or {@code null} for none. - */ - public MediaHttpUploader setProgressListener(MediaHttpUploaderProgressListener progressListener) { - this.progressListener = progressListener; - return this; - } - - /** - * Returns the progress listener to send progress notifications to or {@code null} for none. - */ - public MediaHttpUploaderProgressListener getProgressListener() { - return progressListener; - } - - /** - * Sets the maximum size of individual chunks that will get uploaded by single HTTP requests. The - * default value is {@link #DEFAULT_CHUNK_SIZE}. - * - *

- * The minimum allowable value is {@link #MINIMUM_CHUNK_SIZE} and the specified chunk size must be - * a multiple of {@link #MINIMUM_CHUNK_SIZE}. - *

- */ - public MediaHttpUploader setChunkSize(int chunkSize) { - Preconditions.checkArgument(chunkSize > 0 && chunkSize % MINIMUM_CHUNK_SIZE == 0, "chunkSize" - + " must be a positive multiple of " + MINIMUM_CHUNK_SIZE + "."); - this.chunkSize = chunkSize; - return this; - } - - /** - * Returns the maximum size of individual chunks that will get uploaded by single HTTP requests. - * The default value is {@link #DEFAULT_CHUNK_SIZE}. - */ - public int getChunkSize() { - return chunkSize; - } - - /** - * Returns whether to disable GZip compression of HTTP content. - * - * @since 1.13 - */ - public boolean getDisableGZipContent() { - return disableGZipContent; - } - - /** - * Sets whether to disable GZip compression of HTTP content. - * - *

- * By default it is {@code false}. - *

- * - *

- * If {@link #setDisableGZipContent(boolean)} is set to false (the default value) then content is - * gzipped for direct media upload and resumable media uploads when content length is not known. - * Due to a current limitation, content is not gzipped for resumable media uploads when content - * length is known; this limitation will be removed in the future. - *

- * - * @since 1.13 - */ - public MediaHttpUploader setDisableGZipContent(boolean disableGZipContent) { - this.disableGZipContent = disableGZipContent; - return this; - } - - /** - * Returns the sleeper. - * - * @since 1.15 - */ - public Sleeper getSleeper() { - return sleeper; - } - - /** - * Sets the sleeper. The default value is {@link Sleeper#DEFAULT}. - * - * @since 1.15 - */ - public MediaHttpUploader setSleeper(Sleeper sleeper) { - this.sleeper = sleeper; - return this; - } - - /** - * Returns the HTTP method used for the initiation request. - * - *

- * The default value is {@link HttpMethods#POST}. - *

- * - * @since 1.12 - */ - public String getInitiationRequestMethod() { - return initiationRequestMethod; - } - - /** - * Sets the HTTP method used for the initiation request. - * - *

- * Can only be {@link HttpMethods#POST} (for media upload) or {@link HttpMethods#PUT} (for media - * update). The default value is {@link HttpMethods#POST}. - *

- * - * @since 1.12 - */ - public MediaHttpUploader setInitiationRequestMethod(String initiationRequestMethod) { - Preconditions.checkArgument(initiationRequestMethod.equals(HttpMethods.POST) - || initiationRequestMethod.equals(HttpMethods.PUT) - || initiationRequestMethod.equals(HttpMethods.PATCH)); - this.initiationRequestMethod = initiationRequestMethod; - return this; - } - - /** Sets the HTTP headers used for the initiation request. */ - public MediaHttpUploader setInitiationHeaders(HttpHeaders initiationHeaders) { - this.initiationHeaders = initiationHeaders; - return this; - } - - /** Returns the HTTP headers used for the initiation request. */ - public HttpHeaders getInitiationHeaders() { - return initiationHeaders; - } - - /** - * Gets the total number of bytes the server received so far or {@code 0} for direct uploads when - * the content length is not known. - * - * @return the number of bytes the server received so far - */ - public long getNumBytesUploaded() { - return totalBytesServerReceived; - } - - /** - * Sets the upload state and notifies the progress listener. - * - * @param uploadState value to set to - */ - private void updateStateAndNotifyListener(UploadState uploadState) throws IOException { - this.uploadState = uploadState; - if (progressListener != null) { - progressListener.progressChanged(this); - } - } - - /** - * Gets the current upload state of the uploader. - * - * @return the upload state - */ - public UploadState getUploadState() { - return uploadState; - } - - /** - * Gets the upload progress denoting the percentage of bytes that have been uploaded, represented - * between 0.0 (0%) and 1.0 (100%). - * - *

- * Do not use if the specified {@link AbstractInputStreamContent} has no content length specified. - * Instead, consider using {@link #getNumBytesUploaded} to denote progress. - *

- * - * @throws IllegalArgumentException if the specified {@link AbstractInputStreamContent} has no - * content length - * @return the upload progress - */ - public double getProgress() throws IOException { - Preconditions.checkArgument(isMediaLengthKnown(), "Cannot call getProgress() if " - + "the specified AbstractInputStreamContent has no content length. Use " - + " getNumBytesUploaded() to denote progress instead."); - return getMediaContentLength() == 0 ? 0 : (double) totalBytesServerReceived - / getMediaContentLength(); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/googleapis/media/MediaHttpUploaderProgressListener.java b/src/autosaveworld/zlibs/com/google/api/client/googleapis/media/MediaHttpUploaderProgressListener.java deleted file mode 100644 index 2142efc0..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/googleapis/media/MediaHttpUploaderProgressListener.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.googleapis.media; - -import java.io.IOException; - - -/** - * An interface for receiving progress notifications for uploads. - * - *

- * Sample usage (if media content length is provided, else consider using - * {@link MediaHttpUploader#getNumBytesUploaded} instead of {@link MediaHttpUploader#getProgress}: - *

- * - *
-  public static class MyUploadProgressListener implements MediaHttpUploaderProgressListener {
-
-    public void progressChanged(MediaHttpUploader uploader) throws IOException {
-      switch (uploader.getUploadState()) {
-        case INITIATION_STARTED:
-          System.out.println("Initiation Started");
-          break;
-        case INITIATION_COMPLETE:
-          System.out.println("Initiation Completed");
-          break;
-        case MEDIA_IN_PROGRESS:
-          System.out.println("Upload in progress");
-          System.out.println("Upload percentage: " + uploader.getProgress());
-          break;
-        case MEDIA_COMPLETE:
-          System.out.println("Upload Completed!");
-          break;
-      }
-    }
-  }
- * 
- * - * @since 1.9 - * @author rmistry@google.com (Ravi Mistry) - */ -public interface MediaHttpUploaderProgressListener { - - /** - * Called to notify that progress has been changed. - * - *

- * This method is called once before and after the initiation request. For media uploads it is - * called multiple times depending on how many chunks are uploaded. Once the upload completes it - * is called one final time. - *

- * - *

- * The upload state can be queried by calling {@link MediaHttpUploader#getUploadState} and the - * progress by calling {@link MediaHttpUploader#getProgress}. - *

- * - * @param uploader Media HTTP uploader - */ - public void progressChanged(MediaHttpUploader uploader) throws IOException; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/googleapis/media/MediaUploadErrorHandler.java b/src/autosaveworld/zlibs/com/google/api/client/googleapis/media/MediaUploadErrorHandler.java deleted file mode 100644 index 5cd1f058..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/googleapis/media/MediaUploadErrorHandler.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.googleapis.media; - -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; - -import autosaveworld.zlibs.com.google.api.client.http.HttpIOExceptionHandler; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequest; -import autosaveworld.zlibs.com.google.api.client.http.HttpResponse; -import autosaveworld.zlibs.com.google.api.client.http.HttpUnsuccessfulResponseHandler; -import autosaveworld.zlibs.com.google.api.client.util.Beta; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * MediaUpload error handler handles an {@link IOException} and an abnormal HTTP response by calling - * to {@link MediaHttpUploader#serverErrorCallback()}. - * - * @author Eyal Peled - */ -@Beta -class MediaUploadErrorHandler implements HttpUnsuccessfulResponseHandler, HttpIOExceptionHandler { - - static final Logger LOGGER = Logger.getLogger(MediaUploadErrorHandler.class.getName()); - - /** The uploader to callback on if there is a server error. */ - private final MediaHttpUploader uploader; - - /** The original {@link HttpIOExceptionHandler} of the HTTP request. */ - private final HttpIOExceptionHandler originalIOExceptionHandler; - - /** The original {@link HttpUnsuccessfulResponseHandler} of the HTTP request. */ - private final HttpUnsuccessfulResponseHandler originalUnsuccessfulHandler; - - /** - * Constructs a new instance from {@link MediaHttpUploader} and {@link HttpRequest}. - */ - public MediaUploadErrorHandler(MediaHttpUploader uploader, HttpRequest request) { - this.uploader = Preconditions.checkNotNull(uploader); - originalIOExceptionHandler = request.getIOExceptionHandler(); - originalUnsuccessfulHandler = request.getUnsuccessfulResponseHandler(); - - request.setIOExceptionHandler(this); - request.setUnsuccessfulResponseHandler(this); - } - - public boolean handleIOException(HttpRequest request, boolean supportsRetry) throws IOException { - boolean handled = originalIOExceptionHandler != null - && originalIOExceptionHandler.handleIOException(request, supportsRetry); - - // TODO(peleyal): figure out what is best practice - call serverErrorCallback only if I/O - // exception was handled, or call it regardless - if (handled) { - try { - uploader.serverErrorCallback(); - } catch (IOException e) { - LOGGER.log(Level.WARNING, "exception thrown while calling server callback", e); - } - } - return handled; - } - - public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry) - throws IOException { - boolean handled = originalUnsuccessfulHandler != null - && originalUnsuccessfulHandler.handleResponse(request, response, supportsRetry); - - // TODO(peleyal): figure out what is best practice - call serverErrorCallback only if the - // abnormal response was handled, or call it regardless - if (handled && supportsRetry && response.getStatusCode() / 100 == 5) { - try { - uploader.serverErrorCallback(); - } catch (IOException e) { - LOGGER.log(Level.WARNING, "exception thrown while calling server callback", e); - } - } - return handled; - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/googleapis/services/AbstractGoogleClient.java b/src/autosaveworld/zlibs/com/google/api/client/googleapis/services/AbstractGoogleClient.java deleted file mode 100644 index 6e4baee2..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/googleapis/services/AbstractGoogleClient.java +++ /dev/null @@ -1,501 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.googleapis.services; - -import java.io.IOException; -import java.util.logging.Logger; - -import autosaveworld.zlibs.com.google.api.client.http.HttpRequestFactory; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequestInitializer; -import autosaveworld.zlibs.com.google.api.client.http.HttpTransport; -import autosaveworld.zlibs.com.google.api.client.util.ObjectParser; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.Strings; - -/** - * Abstract thread-safe Google client. - * - * @since 1.12 - * @author Yaniv Inbar - */ -public abstract class AbstractGoogleClient { - - static final Logger LOGGER = Logger.getLogger(AbstractGoogleClient.class.getName()); - - /** The request factory for connections to the server. */ - private final HttpRequestFactory requestFactory; - - /** - * Initializer to use when creating an {@link AbstractGoogleClientRequest} or {@code null} for - * none. - */ - private final GoogleClientRequestInitializer googleClientRequestInitializer; - - /** - * Root URL of the service, for example {@code "https://www.googleapis.com/"}. Must be URL-encoded - * and must end with a "/". - */ - private final String rootUrl; - - /** - * Service path, for example {@code "tasks/v1/"}. Must be URL-encoded and must end with a "/". - */ - private final String servicePath; - - /** - * Application name to be sent in the User-Agent header of each request or {@code null} for none. - */ - private final String applicationName; - - /** Object parser or {@code null} for none. */ - private final ObjectParser objectParser; - - /** Whether discovery pattern checks should be suppressed on required parameters. */ - private boolean suppressPatternChecks; - - /** Whether discovery required parameter checks should be suppressed. */ - private boolean suppressRequiredParameterChecks; - - /** - * @param builder builder - * - * @since 1.14 - */ - protected AbstractGoogleClient(Builder builder) { - googleClientRequestInitializer = builder.googleClientRequestInitializer; - rootUrl = normalizeRootUrl(builder.rootUrl); - servicePath = normalizeServicePath(builder.servicePath); - if (Strings.isNullOrEmpty(builder.applicationName)) { - LOGGER.warning("Application name is not set. Call Builder#setApplicationName."); - } - applicationName = builder.applicationName; - requestFactory = builder.httpRequestInitializer == null - ? builder.transport.createRequestFactory() - : builder.transport.createRequestFactory(builder.httpRequestInitializer); - objectParser = builder.objectParser; - suppressPatternChecks = builder.suppressPatternChecks; - suppressRequiredParameterChecks = builder.suppressRequiredParameterChecks; - } - - /** - * Returns the URL-encoded root URL of the service, for example - * {@code "https://www.googleapis.com/"}. - * - *

- * Must end with a "/". - *

- */ - public final String getRootUrl() { - return rootUrl; - } - - /** - * Returns the URL-encoded service path of the service, for example {@code "tasks/v1/"}. - * - *

- * Must end with a "/" and not begin with a "/". It is allowed to be an empty string {@code ""} or - * a forward slash {@code "/"}, if it is a forward slash then it is treated as an empty string - *

- */ - public final String getServicePath() { - return servicePath; - } - - /** - * Returns the URL-encoded base URL of the service, for example - * {@code "https://www.googleapis.com/tasks/v1/"}. - * - *

- * Must end with a "/". It is guaranteed to be equal to {@code getRootUrl() + getServicePath()}. - *

- */ - public final String getBaseUrl() { - return rootUrl + servicePath; - } - - /** - * Returns the application name to be sent in the User-Agent header of each request or - * {@code null} for none. - */ - public final String getApplicationName() { - return applicationName; - } - - /** Returns the HTTP request factory. */ - public final HttpRequestFactory getRequestFactory() { - return requestFactory; - } - - /** Returns the Google client request initializer or {@code null} for none. */ - public final GoogleClientRequestInitializer getGoogleClientRequestInitializer() { - return googleClientRequestInitializer; - } - - /** - * Returns the object parser or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public ObjectParser getObjectParser() { - return objectParser; - } - - /** - * Initializes a {@link AbstractGoogleClientRequest} using a - * {@link GoogleClientRequestInitializer}. - * - *

- * Must be called before the Google client request is executed, preferably right after the request - * is instantiated. Sample usage: - *

- * - *
-    public class Get extends HttpClientRequest {
-      ...
-    }
-
-    public Get get(String userId) throws IOException {
-      Get result = new Get(userId);
-      initialize(result);
-      return result;
-    }
-   * 
- * - *

- * Subclasses may override by calling the super implementation. - *

- * - * @param httpClientRequest Google client request type - */ - protected void initialize(AbstractGoogleClientRequest httpClientRequest) throws IOException { - if (getGoogleClientRequestInitializer() != null) { - getGoogleClientRequestInitializer().initialize(httpClientRequest); - } - } - - /** Returns whether discovery pattern checks should be suppressed on required parameters. */ - public final boolean getSuppressPatternChecks() { - return suppressPatternChecks; - } - - /** - * Returns whether discovery required parameter checks should be suppressed. - * - * @since 1.14 - */ - public final boolean getSuppressRequiredParameterChecks() { - return suppressRequiredParameterChecks; - } - - /** If the specified root URL does not end with a "/" then a "/" is added to the end. */ - static String normalizeRootUrl(String rootUrl) { - Preconditions.checkNotNull(rootUrl, "root URL cannot be null."); - if (!rootUrl.endsWith("/")) { - rootUrl += "/"; - } - return rootUrl; - } - - /** - * If the specified service path does not end with a "/" then a "/" is added to the end. If the - * specified service path begins with a "/" then the "/" is removed. - */ - static String normalizeServicePath(String servicePath) { - Preconditions.checkNotNull(servicePath, "service path cannot be null"); - if (servicePath.length() == 1) { - Preconditions.checkArgument( - "/".equals(servicePath), "service path must equal \"/\" if it is of length 1."); - servicePath = ""; - } else if (servicePath.length() > 0) { - if (!servicePath.endsWith("/")) { - servicePath += "/"; - } - if (servicePath.startsWith("/")) { - servicePath = servicePath.substring(1); - } - } - return servicePath; - } - - /** - * Builder for {@link AbstractGoogleClient}. - * - *

- * Implementation is not thread-safe. - *

- */ - public abstract static class Builder { - - /** HTTP transport. */ - final HttpTransport transport; - - /** - * Initializer to use when creating an {@link AbstractGoogleClientRequest} or {@code null} for - * none. - */ - GoogleClientRequestInitializer googleClientRequestInitializer; - - /** HTTP request initializer or {@code null} for none. */ - HttpRequestInitializer httpRequestInitializer; - - /** Object parser to use for parsing responses. */ - final ObjectParser objectParser; - - /** The root URL of the service, for example {@code "https://www.googleapis.com/"}. */ - String rootUrl; - - /** The service path of the service, for example {@code "tasks/v1/"}. */ - String servicePath; - - /** - * Application name to be sent in the User-Agent header of each request or {@code null} for - * none. - */ - String applicationName; - - /** Whether discovery pattern checks should be suppressed on required parameters. */ - boolean suppressPatternChecks; - - /** Whether discovery required parameter checks should be suppressed. */ - boolean suppressRequiredParameterChecks; - - /** - * Returns an instance of a new builder. - * - * @param transport The transport to use for requests - * @param rootUrl root URL of the service. Must end with a "/" - * @param servicePath service path - * @param objectParser object parser or {@code null} for none - * @param httpRequestInitializer HTTP request initializer or {@code null} for none - */ - protected Builder(HttpTransport transport, String rootUrl, String servicePath, - ObjectParser objectParser, HttpRequestInitializer httpRequestInitializer) { - this.transport = Preconditions.checkNotNull(transport); - this.objectParser = objectParser; - setRootUrl(rootUrl); - setServicePath(servicePath); - this.httpRequestInitializer = httpRequestInitializer; - } - - /** Builds a new instance of {@link AbstractGoogleClient}. */ - public abstract AbstractGoogleClient build(); - - /** Returns the HTTP transport. */ - public final HttpTransport getTransport() { - return transport; - } - - /** - * Returns the object parser or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public ObjectParser getObjectParser() { - return objectParser; - } - - /** - * Returns the URL-encoded root URL of the service, for example - * {@code https://www.googleapis.com/}. - * - *

- * Must be URL-encoded and must end with a "/". - *

- */ - public final String getRootUrl() { - return rootUrl; - } - - /** - * Sets the URL-encoded root URL of the service, for example {@code https://www.googleapis.com/} - * . - *

- * If the specified root URL does not end with a "/" then a "/" is added to the end. - *

- * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setRootUrl(String rootUrl) { - this.rootUrl = normalizeRootUrl(rootUrl); - return this; - } - - /** - * Returns the URL-encoded service path of the service, for example {@code "tasks/v1/"}. - * - *

- * Must be URL-encoded and must end with a "/" and not begin with a "/". It is allowed to be an - * empty string {@code ""}. - *

- */ - public final String getServicePath() { - return servicePath; - } - - /** - * Sets the URL-encoded service path of the service, for example {@code "tasks/v1/"}. - * - *

- * It is allowed to be an empty string {@code ""} or a forward slash {@code "/"}, if it is a - * forward slash then it is treated as an empty string. This is determined when the library is - * generated and normally should not be changed. - *

- * - *

- * If the specified service path does not end with a "/" then a "/" is added to the end. If the - * specified service path begins with a "/" then the "/" is removed. - *

- * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setServicePath(String servicePath) { - this.servicePath = normalizeServicePath(servicePath); - return this; - } - - /** Returns the Google client request initializer or {@code null} for none. */ - public final GoogleClientRequestInitializer getGoogleClientRequestInitializer() { - return googleClientRequestInitializer; - } - - /** - * Sets the Google client request initializer or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setGoogleClientRequestInitializer( - GoogleClientRequestInitializer googleClientRequestInitializer) { - this.googleClientRequestInitializer = googleClientRequestInitializer; - return this; - } - - /** Returns the HTTP request initializer or {@code null} for none. */ - public final HttpRequestInitializer getHttpRequestInitializer() { - return httpRequestInitializer; - } - - /** - * Sets the HTTP request initializer or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setHttpRequestInitializer(HttpRequestInitializer httpRequestInitializer) { - this.httpRequestInitializer = httpRequestInitializer; - return this; - } - - /** - * Returns the application name to be used in the UserAgent header of each request or - * {@code null} for none. - */ - public final String getApplicationName() { - return applicationName; - } - - /** - * Sets the application name to be used in the UserAgent header of each request or {@code null} - * for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setApplicationName(String applicationName) { - this.applicationName = applicationName; - return this; - } - - /** Returns whether discovery pattern checks should be suppressed on required parameters. */ - public final boolean getSuppressPatternChecks() { - return suppressPatternChecks; - } - - /** - * Sets whether discovery pattern checks should be suppressed on required parameters. - * - *

- * Default value is {@code false}. - *

- * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { - this.suppressPatternChecks = suppressPatternChecks; - return this; - } - - /** - * Returns whether discovery required parameter checks should be suppressed. - * - * @since 1.14 - */ - public final boolean getSuppressRequiredParameterChecks() { - return suppressRequiredParameterChecks; - } - - /** - * Sets whether discovery required parameter checks should be suppressed. - * - *

- * Default value is {@code false}. - *

- * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.14 - */ - public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { - this.suppressRequiredParameterChecks = suppressRequiredParameterChecks; - return this; - } - - /** - * Suppresses all discovery pattern and required parameter checks. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.14 - */ - public Builder setSuppressAllChecks(boolean suppressAllChecks) { - return setSuppressPatternChecks(true).setSuppressRequiredParameterChecks(true); - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/googleapis/services/AbstractGoogleClientRequest.java b/src/autosaveworld/zlibs/com/google/api/client/googleapis/services/AbstractGoogleClientRequest.java deleted file mode 100644 index b276f564..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/googleapis/services/AbstractGoogleClientRequest.java +++ /dev/null @@ -1,551 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.googleapis.services; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import autosaveworld.zlibs.com.google.api.client.googleapis.MethodOverride; -import autosaveworld.zlibs.com.google.api.client.googleapis.media.MediaHttpUploader; -import autosaveworld.zlibs.com.google.api.client.http.AbstractInputStreamContent; -import autosaveworld.zlibs.com.google.api.client.http.EmptyContent; -import autosaveworld.zlibs.com.google.api.client.http.GZipEncoding; -import autosaveworld.zlibs.com.google.api.client.http.GenericUrl; -import autosaveworld.zlibs.com.google.api.client.http.HttpContent; -import autosaveworld.zlibs.com.google.api.client.http.HttpHeaders; -import autosaveworld.zlibs.com.google.api.client.http.HttpMethods; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequest; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequestFactory; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequestInitializer; -import autosaveworld.zlibs.com.google.api.client.http.HttpResponse; -import autosaveworld.zlibs.com.google.api.client.http.HttpResponseException; -import autosaveworld.zlibs.com.google.api.client.http.HttpResponseInterceptor; -import autosaveworld.zlibs.com.google.api.client.http.UriTemplate; -import autosaveworld.zlibs.com.google.api.client.util.GenericData; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * Abstract Google client request for a {@link AbstractGoogleClient}. - * - *

- * Implementation is not thread-safe. - *

- * - * @param type of the response - * - * @since 1.12 - * @author Yaniv Inbar - */ -public abstract class AbstractGoogleClientRequest extends GenericData { - - /** - * User agent suffix for all requests. - * - * @since 1.20 - */ - public static final String USER_AGENT_SUFFIX = "Google-API-Java-Client"; - - /** Google client. */ - private final AbstractGoogleClient abstractGoogleClient; - - /** HTTP method. */ - private final String requestMethod; - - /** URI template for the path relative to the base URL. */ - private final String uriTemplate; - - /** HTTP content or {@code null} for none. */ - private final HttpContent httpContent; - - /** HTTP headers used for the Google client request. */ - private HttpHeaders requestHeaders = new HttpHeaders(); - - /** HTTP headers of the last response or {@code null} before request has been executed. */ - private HttpHeaders lastResponseHeaders; - - /** Status code of the last response or {@code -1} before request has been executed. */ - private int lastStatusCode = -1; - - /** Status message of the last response or {@code null} before request has been executed. */ - private String lastStatusMessage; - - /** Whether to disable GZip compression of HTTP content. */ - private boolean disableGZipContent; - - /** Response class to parse into. */ - private Class responseClass; - - /** Media HTTP uploader or {@code null} for none. */ - private MediaHttpUploader uploader; - - /** - * @param abstractGoogleClient Google client - * @param requestMethod HTTP Method - * @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/" - * the base path from the base URL will be stripped out. The URI template can also be a - * full URL. URI template expansion is done using - * {@link UriTemplate#expand(String, String, Object, boolean)} - * @param httpContent HTTP content or {@code null} for none - * @param responseClass response class to parse into - */ - protected AbstractGoogleClientRequest(AbstractGoogleClient abstractGoogleClient, - String requestMethod, String uriTemplate, HttpContent httpContent, Class responseClass) { - this.responseClass = Preconditions.checkNotNull(responseClass); - this.abstractGoogleClient = Preconditions.checkNotNull(abstractGoogleClient); - this.requestMethod = Preconditions.checkNotNull(requestMethod); - this.uriTemplate = Preconditions.checkNotNull(uriTemplate); - this.httpContent = httpContent; - // application name - String applicationName = abstractGoogleClient.getApplicationName(); - if (applicationName != null) { - requestHeaders.setUserAgent(applicationName + " " + USER_AGENT_SUFFIX); - } else { - requestHeaders.setUserAgent(USER_AGENT_SUFFIX); - } - } - - /** Returns whether to disable GZip compression of HTTP content. */ - public final boolean getDisableGZipContent() { - return disableGZipContent; - } - - /** - * Sets whether to disable GZip compression of HTTP content. - * - *

- * By default it is {@code false}. - *

- * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public AbstractGoogleClientRequest setDisableGZipContent(boolean disableGZipContent) { - this.disableGZipContent = disableGZipContent; - return this; - } - - /** Returns the HTTP method. */ - public final String getRequestMethod() { - return requestMethod; - } - - /** Returns the URI template for the path relative to the base URL. */ - public final String getUriTemplate() { - return uriTemplate; - } - - /** Returns the HTTP content or {@code null} for none. */ - public final HttpContent getHttpContent() { - return httpContent; - } - - /** - * Returns the Google client. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public AbstractGoogleClient getAbstractGoogleClient() { - return abstractGoogleClient; - } - - /** Returns the HTTP headers used for the Google client request. */ - public final HttpHeaders getRequestHeaders() { - return requestHeaders; - } - - /** - * Sets the HTTP headers used for the Google client request. - * - *

- * These headers are set on the request after {@link #buildHttpRequest} is called, this means that - * {@link HttpRequestInitializer#initialize} is called first. - *

- * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public AbstractGoogleClientRequest setRequestHeaders(HttpHeaders headers) { - this.requestHeaders = headers; - return this; - } - - /** - * Returns the HTTP headers of the last response or {@code null} before request has been executed. - */ - public final HttpHeaders getLastResponseHeaders() { - return lastResponseHeaders; - } - - /** - * Returns the status code of the last response or {@code -1} before request has been executed. - */ - public final int getLastStatusCode() { - return lastStatusCode; - } - - /** - * Returns the status message of the last response or {@code null} before request has been - * executed. - */ - public final String getLastStatusMessage() { - return lastStatusMessage; - } - - /** Returns the response class to parse into. */ - public final Class getResponseClass() { - return responseClass; - } - - /** Returns the media HTTP Uploader or {@code null} for none. */ - public final MediaHttpUploader getMediaHttpUploader() { - return uploader; - } - - /** - * Initializes the media HTTP uploader based on the media content. - * - * @param mediaContent media content - */ - protected final void initializeMediaUpload(AbstractInputStreamContent mediaContent) { - HttpRequestFactory requestFactory = abstractGoogleClient.getRequestFactory(); - this.uploader = new MediaHttpUploader( - mediaContent, requestFactory.getTransport(), requestFactory.getInitializer()); - this.uploader.setInitiationRequestMethod(requestMethod); - if (httpContent != null) { - this.uploader.setMetadata(httpContent); - } - } - - /** - * Creates a new instance of {@link GenericUrl} suitable for use against this service. - * - *

- * Subclasses may override by calling the super implementation. - *

- * - * @return newly created {@link GenericUrl} - */ - public GenericUrl buildHttpRequestUrl() { - return new GenericUrl( - UriTemplate.expand(abstractGoogleClient.getBaseUrl(), uriTemplate, this, true)); - } - - /** - * Create a request suitable for use against this service. - * - *

- * Subclasses may override by calling the super implementation. - *

- */ - public HttpRequest buildHttpRequest() throws IOException { - return buildHttpRequest(false); - } - - /** - * Create a request suitable for use against this service, but using HEAD instead of GET. - * - *

- * Only supported when the original request method is GET. - *

- * - *

- * Subclasses may override by calling the super implementation. - *

- */ - protected HttpRequest buildHttpRequestUsingHead() throws IOException { - return buildHttpRequest(true); - } - - /** Create a request suitable for use against this service. */ - private HttpRequest buildHttpRequest(boolean usingHead) throws IOException { - Preconditions.checkArgument(uploader == null); - Preconditions.checkArgument(!usingHead || requestMethod.equals(HttpMethods.GET)); - String requestMethodToUse = usingHead ? HttpMethods.HEAD : requestMethod; - final HttpRequest httpRequest = getAbstractGoogleClient() - .getRequestFactory().buildRequest(requestMethodToUse, buildHttpRequestUrl(), httpContent); - new MethodOverride().intercept(httpRequest); - httpRequest.setParser(getAbstractGoogleClient().getObjectParser()); - // custom methods may use POST with no content but require a Content-Length header - if (httpContent == null && (requestMethod.equals(HttpMethods.POST) - || requestMethod.equals(HttpMethods.PUT) || requestMethod.equals(HttpMethods.PATCH))) { - httpRequest.setContent(new EmptyContent()); - } - httpRequest.getHeaders().putAll(requestHeaders); - if (!disableGZipContent) { - httpRequest.setEncoding(new GZipEncoding()); - } - final HttpResponseInterceptor responseInterceptor = httpRequest.getResponseInterceptor(); - httpRequest.setResponseInterceptor(new HttpResponseInterceptor() { - - public void interceptResponse(HttpResponse response) throws IOException { - if (responseInterceptor != null) { - responseInterceptor.interceptResponse(response); - } - if (!response.isSuccessStatusCode() && httpRequest.getThrowExceptionOnExecuteError()) { - throw newExceptionOnError(response); - } - } - }); - return httpRequest; - } - - /** - * Sends the metadata request to the server and returns the raw metadata {@link HttpResponse}. - * - *

- * Callers are responsible for disconnecting the HTTP response by calling - * {@link HttpResponse#disconnect}. Example usage: - *

- * - *
-     HttpResponse response = request.executeUnparsed();
-     try {
-       // process response..
-     } finally {
-       response.disconnect();
-     }
-   * 
- * - *

- * Subclasses may override by calling the super implementation. - *

- * - * @return the {@link HttpResponse} - */ - public HttpResponse executeUnparsed() throws IOException { - return executeUnparsed(false); - } - - /** - * Sends the media request to the server and returns the raw media {@link HttpResponse}. - * - *

- * Callers are responsible for disconnecting the HTTP response by calling - * {@link HttpResponse#disconnect}. Example usage: - *

- * - *
-     HttpResponse response = request.executeMedia();
-     try {
-       // process response..
-     } finally {
-       response.disconnect();
-     }
-   * 
- * - *

- * Subclasses may override by calling the super implementation. - *

- * - * @return the {@link HttpResponse} - */ - protected HttpResponse executeMedia() throws IOException { - set("alt", "media"); - return executeUnparsed(); - } - - /** - * Sends the metadata request using HEAD to the server and returns the raw metadata - * {@link HttpResponse} for the response headers. - * - *

- * Only supported when the original request method is GET. The response content is assumed to be - * empty and ignored. Calls {@link HttpResponse#ignore()} so there is no need to disconnect the - * response. Example usage: - *

- * - *
-     HttpResponse response = request.executeUsingHead();
-     // look at response.getHeaders()
-   * 
- * - *

- * Subclasses may override by calling the super implementation. - *

- * - * @return the {@link HttpResponse} - */ - protected HttpResponse executeUsingHead() throws IOException { - Preconditions.checkArgument(uploader == null); - HttpResponse response = executeUnparsed(true); - response.ignore(); - return response; - } - - /** - * Sends the metadata request using the given request method to the server and returns the raw - * metadata {@link HttpResponse}. - */ - private HttpResponse executeUnparsed(boolean usingHead) throws IOException { - HttpResponse response; - if (uploader == null) { - // normal request (not upload) - response = buildHttpRequest(usingHead).execute(); - } else { - // upload request - GenericUrl httpRequestUrl = buildHttpRequestUrl(); - HttpRequest httpRequest = getAbstractGoogleClient() - .getRequestFactory().buildRequest(requestMethod, httpRequestUrl, httpContent); - boolean throwExceptionOnExecuteError = httpRequest.getThrowExceptionOnExecuteError(); - - response = uploader.setInitiationHeaders(requestHeaders) - .setDisableGZipContent(disableGZipContent).upload(httpRequestUrl); - response.getRequest().setParser(getAbstractGoogleClient().getObjectParser()); - // process any error - if (throwExceptionOnExecuteError && !response.isSuccessStatusCode()) { - throw newExceptionOnError(response); - } - } - // process response - lastResponseHeaders = response.getHeaders(); - lastStatusCode = response.getStatusCode(); - lastStatusMessage = response.getStatusMessage(); - return response; - } - - /** - * Returns the exception to throw on an HTTP error response as defined by - * {@link HttpResponse#isSuccessStatusCode()}. - * - *

- * It is guaranteed that {@link HttpResponse#isSuccessStatusCode()} is {@code false}. Default - * implementation is to call {@link HttpResponseException#HttpResponseException(HttpResponse)}, - * but subclasses may override. - *

- * - * @param response HTTP response - * @return exception to throw - */ - protected IOException newExceptionOnError(HttpResponse response) { - return new HttpResponseException(response); - } - - /** - * Sends the metadata request to the server and returns the parsed metadata response. - * - *

- * Subclasses may override by calling the super implementation. - *

- * - * @return parsed HTTP response - */ - public T execute() throws IOException { - return executeUnparsed().parseAs(responseClass); - } - - /** - * Sends the metadata request to the server and returns the metadata content input stream of - * {@link HttpResponse}. - * - *

- * Callers are responsible for closing the input stream after it is processed. Example sample: - *

- * - *
-     InputStream is = request.executeAsInputStream();
-     try {
-       // Process input stream..
-     } finally {
-       is.close();
-     }
-   * 
- * - *

- * Subclasses may override by calling the super implementation. - *

- * - * @return input stream of the response content - */ - public InputStream executeAsInputStream() throws IOException { - return executeUnparsed().getContent(); - } - - /** - * Sends the media request to the server and returns the media content input stream of - * {@link HttpResponse}. - * - *

- * Callers are responsible for closing the input stream after it is processed. Example sample: - *

- * - *
-     InputStream is = request.executeMediaAsInputStream();
-     try {
-       // Process input stream..
-     } finally {
-       is.close();
-     }
-   * 
- * - *

- * Subclasses may override by calling the super implementation. - *

- * - * @return input stream of the response content - */ - protected InputStream executeMediaAsInputStream() throws IOException { - return executeMedia().getContent(); - } - - /** - * Sends the metadata request to the server and writes the metadata content input stream of - * {@link HttpResponse} into the given destination output stream. - * - *

- * This method closes the content of the HTTP response from {@link HttpResponse#getContent()}. - *

- * - *

- * Subclasses may override by calling the super implementation. - *

- * - * @param outputStream destination output stream - */ - public void executeAndDownloadTo(OutputStream outputStream) throws IOException { - executeUnparsed().download(outputStream); - } - - // @SuppressWarnings was added here because this is generic class. - // see: http://stackoverflow.com/questions/4169806/java-casting-object-to-a-generic-type and - // http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html#Type%20Erasure - // for more details - @SuppressWarnings("unchecked") - @Override - public AbstractGoogleClientRequest set(String fieldName, Object value) { - return (AbstractGoogleClientRequest) super.set(fieldName, value); - } - - /** - * Ensures that the specified required parameter is not null or - * {@link AbstractGoogleClient#getSuppressRequiredParameterChecks()} is true. - * - * @param value the value of the required parameter - * @param name the name of the required parameter - * @throws IllegalArgumentException if the specified required parameter is null and - * {@link AbstractGoogleClient#getSuppressRequiredParameterChecks()} is false - * @since 1.14 - */ - protected final void checkRequiredParameter(Object value, String name) { - Preconditions.checkArgument( - abstractGoogleClient.getSuppressRequiredParameterChecks() || value != null, - "Required parameter %s must be specified", name); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/googleapis/services/CommonGoogleClientRequestInitializer.java b/src/autosaveworld/zlibs/com/google/api/client/googleapis/services/CommonGoogleClientRequestInitializer.java deleted file mode 100644 index 9301116a..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/googleapis/services/CommonGoogleClientRequestInitializer.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.googleapis.services; - -import java.io.IOException; - - -/** - * Google common client request initializer implementation for setting properties like key and - * userIp. - * - *

- * The simplest usage is to use it to set the key parameter: - *

- * - *
-  public static final GoogleClientRequestInitializer KEY_INITIALIZER =
-      new CommonGoogleClientRequestInitializer(KEY);
- * 
- * - *

- * There is also a constructor to set both the key and userIp parameters: - *

- * - *
-  public static final GoogleClientRequestInitializer INITIALIZER =
-      new CommonGoogleClientRequestInitializer(KEY, USER_IP);
- * 
- * - *

- * If you want to implement custom logic, extend it like this: - *

- * - *
-  public static class MyRequestInitializer extends CommonGoogleClientRequestInitializer {
-
-    {@literal @}Override
-    public void initialize(AbstractGoogleClientRequest{@literal <}?{@literal >} request)
-        throws IOException {
-      // custom logic
-    }
-  }
- * 
- * - *

- * Finally, to set the key and userIp parameters and insert custom logic, extend it like this: - *

- * - *
-  public static class MyRequestInitializer2 extends CommonGoogleClientRequestInitializer {
-
-    public MyRequestInitializer2() {
-      super(KEY, USER_IP);
-    }
-
-    {@literal @}Override
-    public void initialize(AbstractGoogleClientRequest{@literal <}?{@literal >} request)
-        throws IOException {
-      super.initialize(request); // must be called to set the key and userIp parameters
-      // insert some additional logic
-    }
-  }
- * 
- * - *

- * Subclasses should be thread-safe. - *

- * - * @since 1.12 - * @author Yaniv Inbar - */ -public class CommonGoogleClientRequestInitializer implements GoogleClientRequestInitializer { - - /** API key or {@code null} to leave it unchanged. */ - private final String key; - - /** User IP or {@code null} to leave it unchanged. */ - private final String userIp; - - public CommonGoogleClientRequestInitializer() { - this(null); - } - - /** - * @param key API key or {@code null} to leave it unchanged - */ - public CommonGoogleClientRequestInitializer(String key) { - this(key, null); - } - - /** - * @param key API key or {@code null} to leave it unchanged - * @param userIp user IP or {@code null} to leave it unchanged - */ - public CommonGoogleClientRequestInitializer(String key, String userIp) { - this.key = key; - this.userIp = userIp; - } - - /** - * Subclasses should call super implementation in order to set the key and userIp. - * - * @throws IOException I/O exception - */ - public void initialize(AbstractGoogleClientRequest request) throws IOException { - if (key != null) { - request.put("key", key); - } - if (userIp != null) { - request.put("userIp", userIp); - } - } - - /** Returns the API key or {@code null} to leave it unchanged. */ - public final String getKey() { - return key; - } - - /** Returns the user IP or {@code null} to leave it unchanged. */ - public final String getUserIp() { - return userIp; - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/googleapis/services/GoogleClientRequestInitializer.java b/src/autosaveworld/zlibs/com/google/api/client/googleapis/services/GoogleClientRequestInitializer.java deleted file mode 100644 index c68c0295..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/googleapis/services/GoogleClientRequestInitializer.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.googleapis.services; - -import java.io.IOException; - -/** - * Google client request initializer. - * - *

- * For example, this might be used to set a key URL query parameter on all requests: - *

- * - *
-  public class KeyRequestInitializer implements GoogleClientRequestInitializer {
-    public void initialize(GoogleClientRequest request) {
-      request.put("key", KEY);
-    }
-  }
- * 
- * - *

- * Implementations should be thread-safe. - *

- * - * @since 1.12 - * @author Yaniv Inbar - */ -public interface GoogleClientRequestInitializer { - - /** Initializes a Google client request. */ - void initialize(AbstractGoogleClientRequest request) throws IOException; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/googleapis/services/json/AbstractGoogleJsonClient.java b/src/autosaveworld/zlibs/com/google/api/client/googleapis/services/json/AbstractGoogleJsonClient.java deleted file mode 100644 index eb5f7b6c..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/googleapis/services/json/AbstractGoogleJsonClient.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.googleapis.services.json; - -import java.util.Arrays; -import java.util.Collections; - -import autosaveworld.zlibs.com.google.api.client.googleapis.services.AbstractGoogleClient; -import autosaveworld.zlibs.com.google.api.client.googleapis.services.GoogleClientRequestInitializer; -import autosaveworld.zlibs.com.google.api.client.http.HttpRequestInitializer; -import autosaveworld.zlibs.com.google.api.client.http.HttpTransport; -import autosaveworld.zlibs.com.google.api.client.json.JsonFactory; -import autosaveworld.zlibs.com.google.api.client.json.JsonObjectParser; - -/** - * Thread-safe Google JSON client. - * - * @since 1.12 - * @author Yaniv Inbar - */ -public abstract class AbstractGoogleJsonClient extends AbstractGoogleClient { - - /** - * @param builder builder - * - * @since 1.14 - */ - protected AbstractGoogleJsonClient(Builder builder) { - super(builder); - } - - @Override - public JsonObjectParser getObjectParser() { - return (JsonObjectParser) super.getObjectParser(); - } - - /** Returns the JSON Factory. */ - public final JsonFactory getJsonFactory() { - return getObjectParser().getJsonFactory(); - } - - /** - * Builder for {@link AbstractGoogleJsonClient}. - * - *

- * Implementation is not thread-safe. - *

- */ - public abstract static class Builder extends AbstractGoogleClient.Builder { - - /** - * @param transport HTTP transport - * @param jsonFactory JSON factory - * @param rootUrl root URL of the service - * @param servicePath service path - * @param httpRequestInitializer HTTP request initializer or {@code null} for none - * @param legacyDataWrapper whether using the legacy data wrapper in responses - */ - protected Builder(HttpTransport transport, JsonFactory jsonFactory, String rootUrl, - String servicePath, HttpRequestInitializer httpRequestInitializer, - boolean legacyDataWrapper) { - super(transport, rootUrl, servicePath, new JsonObjectParser.Builder( - jsonFactory).setWrapperKeys( - legacyDataWrapper ? Arrays.asList("data", "error") : Collections.emptySet()) - .build(), httpRequestInitializer); - } - - @Override - public final JsonObjectParser getObjectParser() { - return (JsonObjectParser) super.getObjectParser(); - } - - /** Returns the JSON Factory. */ - public final JsonFactory getJsonFactory() { - return getObjectParser().getJsonFactory(); - } - - @Override - public abstract AbstractGoogleJsonClient build(); - - @Override - public Builder setRootUrl(String rootUrl) { - return (Builder) super.setRootUrl(rootUrl); - } - - @Override - public Builder setServicePath(String servicePath) { - return (Builder) super.setServicePath(servicePath); - } - - @Override - public Builder setGoogleClientRequestInitializer( - GoogleClientRequestInitializer googleClientRequestInitializer) { - return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); - } - - @Override - public Builder setHttpRequestInitializer(HttpRequestInitializer httpRequestInitializer) { - return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); - } - - @Override - public Builder setApplicationName(String applicationName) { - return (Builder) super.setApplicationName(applicationName); - } - - @Override - public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { - return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); - } - - @Override - public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { - return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); - } - - @Override - public Builder setSuppressAllChecks(boolean suppressAllChecks) { - return (Builder) super.setSuppressAllChecks(suppressAllChecks); - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/googleapis/services/json/AbstractGoogleJsonClientRequest.java b/src/autosaveworld/zlibs/com/google/api/client/googleapis/services/json/AbstractGoogleJsonClientRequest.java deleted file mode 100644 index 5daf4491..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/googleapis/services/json/AbstractGoogleJsonClientRequest.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.googleapis.services.json; - -import autosaveworld.zlibs.com.google.api.client.googleapis.json.GoogleJsonResponseException; -import autosaveworld.zlibs.com.google.api.client.googleapis.services.AbstractGoogleClientRequest; -import autosaveworld.zlibs.com.google.api.client.http.HttpHeaders; -import autosaveworld.zlibs.com.google.api.client.http.HttpResponse; -import autosaveworld.zlibs.com.google.api.client.http.UriTemplate; -import autosaveworld.zlibs.com.google.api.client.http.json.JsonHttpContent; - -/** - * Google JSON request for a {@link AbstractGoogleJsonClient}. - * - *

- * Implementation is not thread-safe. - *

- * - * @param type of the response - * @since 1.12 - * @author Yaniv Inbar - */ -public abstract class AbstractGoogleJsonClientRequest extends AbstractGoogleClientRequest { - - /** POJO that can be serialized into JSON content or {@code null} for none. */ - private final Object jsonContent; - - /** - * @param abstractGoogleJsonClient Google JSON client - * @param requestMethod HTTP Method - * @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/" - * the base path from the base URL will be stripped out. The URI template can also be a - * full URL. URI template expansion is done using - * {@link UriTemplate#expand(String, String, Object, boolean)} - * @param jsonContent POJO that can be serialized into JSON content or {@code null} for none - * @param responseClass response class to parse into - */ - protected AbstractGoogleJsonClientRequest(AbstractGoogleJsonClient abstractGoogleJsonClient, - String requestMethod, String uriTemplate, Object jsonContent, Class responseClass) { - super(abstractGoogleJsonClient, requestMethod, uriTemplate, jsonContent == null ? null - : new JsonHttpContent(abstractGoogleJsonClient.getJsonFactory(), jsonContent) - .setWrapperKey(abstractGoogleJsonClient.getObjectParser().getWrapperKeys().isEmpty() - ? null : "data"), responseClass); - this.jsonContent = jsonContent; - } - - @Override - public AbstractGoogleJsonClient getAbstractGoogleClient() { - return (AbstractGoogleJsonClient) super.getAbstractGoogleClient(); - } - - @Override - public AbstractGoogleJsonClientRequest setDisableGZipContent(boolean disableGZipContent) { - return (AbstractGoogleJsonClientRequest) super.setDisableGZipContent(disableGZipContent); - } - - @Override - public AbstractGoogleJsonClientRequest setRequestHeaders(HttpHeaders headers) { - return (AbstractGoogleJsonClientRequest) super.setRequestHeaders(headers); - } - - @Override - protected GoogleJsonResponseException newExceptionOnError(HttpResponse response) { - return GoogleJsonResponseException.from(getAbstractGoogleClient().getJsonFactory(), response); - } - - /** Returns POJO that can be serialized into JSON content or {@code null} for none. */ - public Object getJsonContent() { - return jsonContent; - } - - @Override - public AbstractGoogleJsonClientRequest set(String fieldName, Object value) { - return (AbstractGoogleJsonClientRequest) super.set(fieldName, value); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/googleapis/services/json/CommonGoogleJsonClientRequestInitializer.java b/src/autosaveworld/zlibs/com/google/api/client/googleapis/services/json/CommonGoogleJsonClientRequestInitializer.java deleted file mode 100644 index 4266e275..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/googleapis/services/json/CommonGoogleJsonClientRequestInitializer.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.googleapis.services.json; - -import java.io.IOException; - -import autosaveworld.zlibs.com.google.api.client.googleapis.services.AbstractGoogleClientRequest; -import autosaveworld.zlibs.com.google.api.client.googleapis.services.CommonGoogleClientRequestInitializer; - -/** - * Google JSON client request initializer implementation for setting properties like key and userIp. - * - *

- * The simplest usage is to use it to set the key parameter: - *

- * - *
-  public static final GoogleClientRequestInitializer KEY_INITIALIZER =
-      new CommonGoogleJsonClientRequestInitializer(KEY);
- * 
- * - *

- * There is also a constructor to set both the key and userIp parameters: - *

- * - *
-  public static final GoogleClientRequestInitializer INITIALIZER =
-      new CommonGoogleJsonClientRequestInitializer(KEY, USER_IP);
- * 
- * - *

- * If you want to implement custom logic, extend it like this: - *

- * - *
-  public static class MyRequestInitializer extends CommonGoogleJsonClientRequestInitializer {
-
-    {@literal @}Override
-    public void initialize(AbstractGoogleJsonClientRequest{@literal <}?{@literal >} request)
-        throws IOException {
-      // custom logic
-    }
-  }
- * 
- * - *

- * Finally, to set the key and userIp parameters and insert custom logic, extend it like this: - *

- * - *
-  public static class MyKeyRequestInitializer extends CommonGoogleJsonClientRequestInitializer {
-
-    public MyKeyRequestInitializer() {
-      super(KEY, USER_IP);
-    }
-
-    {@literal @}Override
-    public void initializeJsonRequest(
-        AbstractGoogleJsonClientRequest{@literal <}?{@literal >} request) throws IOException {
-      // custom logic
-    }
-  }
- * 
- * - *

- * Subclasses should be thread-safe. - *

- * - * @since 1.12 - * @author Yaniv Inbar - */ -public class CommonGoogleJsonClientRequestInitializer extends CommonGoogleClientRequestInitializer { - - public CommonGoogleJsonClientRequestInitializer() { - super(); - } - - /** - * @param key API key or {@code null} to leave it unchanged - */ - public CommonGoogleJsonClientRequestInitializer(String key) { - super(key); - } - - /** - * @param key API key or {@code null} to leave it unchanged - * @param userIp user IP or {@code null} to leave it unchanged - */ - public CommonGoogleJsonClientRequestInitializer(String key, String userIp) { - super(key, userIp); - } - - @Override - public final void initialize(AbstractGoogleClientRequest request) throws IOException { - super.initialize(request); - initializeJsonRequest((AbstractGoogleJsonClientRequest) request); - } - - /** - * Initializes a Google JSON client request. - * - *

- * Default implementation does nothing. Called from - * {@link #initialize(AbstractGoogleClientRequest)}. - *

- * - * @throws IOException I/O exception - */ - protected void initializeJsonRequest(AbstractGoogleJsonClientRequest request) - throws IOException { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/googleapis/util/Utils.java b/src/autosaveworld/zlibs/com/google/api/client/googleapis/util/Utils.java deleted file mode 100644 index e1fced97..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/googleapis/util/Utils.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.googleapis.util; - -import autosaveworld.zlibs.com.google.api.client.http.HttpTransport; -import autosaveworld.zlibs.com.google.api.client.http.javanet.NetHttpTransport; -import autosaveworld.zlibs.com.google.api.client.json.JsonFactory; -import autosaveworld.zlibs.com.google.api.client.json.jackson2.JacksonFactory; -import autosaveworld.zlibs.com.google.api.client.util.Beta; - -/** - * {@link Beta}
- * Utility class for the Google API Client Library. - * - * @since 1.19 - */ -@Beta -public final class Utils { - - /** - * Returns a cached default implementation of the JsonFactory interface. - */ - public static JsonFactory getDefaultJsonFactory() { - return JsonFactoryInstanceHolder.INSTANCE; - } - - private static class JsonFactoryInstanceHolder { - // The jackson2.JacksonFactory was introduced as a product dependency in 1.19 to enable - // other APIs to not require one of these for input. This was the most commonly used - // implementation in public samples. This is a compile-time dependency to help detect the - // dependency as early as possible. - static final JsonFactory INSTANCE = new JacksonFactory(); - } - - /** - * Returns a cached default implementation of the HttpTransport interface. - */ - public static HttpTransport getDefaultTransport() { - return TransportInstanceHolder.INSTANCE; - } - - private static class TransportInstanceHolder { - static final HttpTransport INSTANCE = new NetHttpTransport(); - } - - private Utils() { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/AbstractHttpContent.java b/src/autosaveworld/zlibs/com/google/api/client/http/AbstractHttpContent.java deleted file mode 100644 index cfca7e2c..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/AbstractHttpContent.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.IOException; -import java.nio.charset.Charset; - -import autosaveworld.zlibs.com.google.api.client.util.Charsets; -import autosaveworld.zlibs.com.google.api.client.util.IOUtils; -import autosaveworld.zlibs.com.google.api.client.util.StreamingContent; - -/** - * Abstract implementation of an HTTP content with typical options. - * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.5 - * @author Yaniv Inbar - */ -public abstract class AbstractHttpContent implements HttpContent { - - /** Media type used for the Content-Type header or {@code null} for none. */ - private HttpMediaType mediaType; - - /** Cached value for the computed length from {@link #computeLength()}. */ - private long computedLength = -1; - - /** - * @param mediaType Media type string (for example "type/subtype") this content represents or - * {@code null} to leave out. Can also contain parameters like {@code "charset=utf-8"} - * @since 1.10 - */ - protected AbstractHttpContent(String mediaType) { - this(mediaType == null ? null : new HttpMediaType(mediaType)); - } - - /** - * @param mediaType Media type this content represents or {@code null} to leave out - * @since 1.10 - */ - protected AbstractHttpContent(HttpMediaType mediaType) { - this.mediaType = mediaType; - } - - /** - * Default implementation calls {@link #computeLength()} once and caches it for future - * invocations, but subclasses may override. - */ - public long getLength() throws IOException { - if (computedLength == -1) { - computedLength = computeLength(); - } - return computedLength; - } - - /** - * Returns the media type to use for the Content-Type header, or {@code null} if unspecified. - * - * @since 1.10 - */ - public final HttpMediaType getMediaType() { - return mediaType; - } - - /** - * Sets the media type to use for the Content-Type header, or {@code null} if unspecified. - * - *

- * This will also overwrite any previously set parameter of the media type (for example - * {@code "charset"}), and therefore might change other properties as well. - *

- * - * @since 1.10 - */ - public AbstractHttpContent setMediaType(HttpMediaType mediaType) { - this.mediaType = mediaType; - return this; - } - - /** - * Returns the charset specified in the media type or {@code Charsets#UTF_8} if not specified. - * - * @since 1.10 - */ - protected final Charset getCharset() { - return mediaType == null || mediaType.getCharsetParameter() == null - ? Charsets.UTF_8 : mediaType.getCharsetParameter(); - } - - public String getType() { - return mediaType == null ? null : mediaType.build(); - } - - /** - * Computes and returns the content length or less than zero if not known. - * - *

- * Subclasses may override, but by default this computes the length by calling - * {@link #computeLength(HttpContent)}. - *

- */ - protected long computeLength() throws IOException { - return computeLength(this); - } - - /** Default implementation returns {@code true}, but subclasses may override. */ - public boolean retrySupported() { - return true; - } - - /** - * Returns the computed content length based using {@link IOUtils#computeLength(StreamingContent)} - * or instead {@code -1} if {@link HttpContent#retrySupported()} is {@code false} because the - * stream must not be read twice. - * - * @param content HTTP content - * @return computed content length or {@code -1} if retry is not supported - * - * @since 1.14 - */ - public static long computeLength(HttpContent content) throws IOException { - if (!content.retrySupported()) { - return -1; - } - return IOUtils.computeLength(content); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/AbstractInputStreamContent.java b/src/autosaveworld/zlibs/com/google/api/client/http/AbstractInputStreamContent.java deleted file mode 100644 index feb29604..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/AbstractInputStreamContent.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import autosaveworld.zlibs.com.google.api.client.util.ByteStreams; -import autosaveworld.zlibs.com.google.api.client.util.IOUtils; - -/** - * Serializes HTTP request content from an input stream into an output stream. - * - *

- * The {@link #type} field is required. Subclasses should implement the {@link #getLength()}, - * {@link #getInputStream()}, and {@link #retrySupported()} for their specific type of input stream. - * By default, all content is read from the input stream. If instead you want to limit the maximum - * amount of content read from the input stream, you may use - * {@link ByteStreams#limit(InputStream, long)}. - *

- * - *

- * Implementations don't need to be thread-safe. - *

- * - * @since 1.4 - * @author moshenko@google.com (Jacob Moshenko) - */ -public abstract class AbstractInputStreamContent implements HttpContent { - - /** Content type or {@code null} for none. */ - private String type; - - /** - * Whether the input stream should be closed at the end of {@link #writeTo}. Default is - * {@code true}. - */ - private boolean closeInputStream = true; - - /** - * @param type Content type or {@code null} for none - * @since 1.5 - */ - public AbstractInputStreamContent(String type) { - setType(type); - } - - /** - * Return an input stream for the specific implementation type of - * {@link AbstractInputStreamContent}. If the specific implementation will return {@code true} for - * {@link #retrySupported()} this should be a factory function which will create a new - * {@link InputStream} from the source data whenever invoked. - * - * @since 1.7 - */ - public abstract InputStream getInputStream() throws IOException; - - public void writeTo(OutputStream out) throws IOException { - IOUtils.copy(getInputStream(), out, closeInputStream); - out.flush(); - } - - public String getType() { - return type; - } - - /** - * Returns whether the input stream should be closed at the end of {@link #writeTo}. Default is - * {@code true}. - * - * @since 1.7 - */ - public final boolean getCloseInputStream() { - return closeInputStream; - } - - /** - * Sets the content type or {@code null} for none. Subclasses should override by calling super. - * - * @since 1.5 - */ - public AbstractInputStreamContent setType(String type) { - this.type = type; - return this; - } - - /** - * Sets whether the input stream should be closed at the end of {@link #writeTo}. Default is - * {@code true}. Subclasses should override by calling super. - * - * @since 1.7 - */ - public AbstractInputStreamContent setCloseInputStream(boolean closeInputStream) { - this.closeInputStream = closeInputStream; - return this; - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/BackOffPolicy.java b/src/autosaveworld/zlibs/com/google/api/client/http/BackOffPolicy.java deleted file mode 100644 index 1043a0c5..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/BackOffPolicy.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.IOException; - -import autosaveworld.zlibs.com.google.api.client.util.Beta; - -/** - * {@link Beta}
- * Strategy interface to control back off between retry attempts. - * - * @since 1.7 - * @author Ravi Mistry - * @deprecated (scheduled to be removed in 1.18) Use {@link HttpBackOffUnsuccessfulResponseHandler} - * instead. - */ -@Deprecated -@Beta -public interface BackOffPolicy { - - /** - * Value indicating that no more retries should be made, see {@link #getNextBackOffMillis()}. - */ - public static final long STOP = -1L; - - /** - * Determines if back off is required based on the specified status code. - * - *

- * Implementations may want to back off on server or product-specific errors. - *

- * - * @param statusCode HTTP status code - */ - public boolean isBackOffRequired(int statusCode); - - /** - * Reset Back off counters (if any) in an implementation-specific fashion. - */ - public void reset(); - - /** - * Gets the number of milliseconds to wait before retrying an HTTP request. If {@link #STOP} is - * returned, no retries should be made. - * - * This method should be used as follows: - * - *
-   *  long backoffTime = backoffPolicy.getNextBackoffMs();
-   *  if (backoffTime == BackoffPolicy.STOP) {
-   *    // Stop retrying.
-   *  } else {
-   *    // Retry after backoffTime.
-   *  }
-   *
- * - * @return the number of milliseconds to wait when backing off requests, or {@link #STOP} if no - * more retries should be made - */ - public long getNextBackOffMillis() throws IOException; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/ByteArrayContent.java b/src/autosaveworld/zlibs/com/google/api/client/http/ByteArrayContent.java deleted file mode 100644 index 20781234..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/ByteArrayContent.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; - -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.StringUtils; - -/** - * Concrete implementation of {@link AbstractInputStreamContent} that generates repeatable input - * streams based on the contents of byte array. - * - *

- * Sample use: - *

- * - *
- * 
-  static void setJsonContent(HttpRequest request, byte[] json) {
-    request.setContent(new ByteArrayContent("application/json", json));
-  }
- * 
- * 
- * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.4 - * @author moshenko@google.com (Jacob Moshenko) - */ -public final class ByteArrayContent extends AbstractInputStreamContent { - - /** Byte array content. */ - private final byte[] byteArray; - - /** Starting offset into the byte array. */ - private final int offset; - - /** Length of bytes to read from byte array. */ - private final int length; - - /** - * Constructor from byte array content that has already been encoded. - * - * @param type content type or {@code null} for none - * @param array byte array content - * @since 1.5 - */ - public ByteArrayContent(String type, byte[] array) { - this(type, array, 0, array.length); - } - - /** - * Constructor from byte array content that has already been encoded, specifying a range of bytes - * to read from the input byte array. - * - * @param type content type or {@code null} for none - * @param array byte array content - * @param offset starting offset into the byte array - * @param length of bytes to read from byte array - * @since 1.7 - */ - public ByteArrayContent(String type, byte[] array, int offset, int length) { - super(type); - this.byteArray = Preconditions.checkNotNull(array); - Preconditions.checkArgument(offset >= 0 && length >= 0 && offset + length <= array.length, - "offset %s, length %s, array length %s", offset, length, array.length); - this.offset = offset; - this.length = length; - } - - /** - * Returns a new instance with the UTF-8 encoding (using {@link StringUtils#getBytesUtf8(String)}) - * of the given content string. - *

- * Sample use: - *

- * - *
-   * 
-  static void setJsonContent(HttpRequest request, String json) {
-    request.setContent(ByteArrayContent.fromString("application/json", json));
-  }
-   * 
-   * 
- * - * @param type content type or {@code null} for none - * @param contentString content string - * @since 1.5 - */ - public static ByteArrayContent fromString(String type, String contentString) { - return new ByteArrayContent(type, StringUtils.getBytesUtf8(contentString)); - } - - public long getLength() { - return length; - } - - public boolean retrySupported() { - return true; - } - - @Override - public InputStream getInputStream() { - return new ByteArrayInputStream(byteArray, offset, length); - } - - @Override - public ByteArrayContent setType(String type) { - return (ByteArrayContent) super.setType(type); - } - - @Override - public ByteArrayContent setCloseInputStream(boolean closeInputStream) { - return (ByteArrayContent) super.setCloseInputStream(closeInputStream); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/EmptyContent.java b/src/autosaveworld/zlibs/com/google/api/client/http/EmptyContent.java deleted file mode 100644 index cfd92dd9..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/EmptyContent.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * Empty HTTP content of length zero just to force {@link HttpRequest#execute()} to add the header - * {@code Content-Length: 0}. - * - *

- * Note that there is no {@code Content-Length} header if the HTTP request content is {@code null} . - * However, when making a request like PUT or POST without a {@code Content-Length} header, some - * servers may respond with a {@code 411 Length Required} error. Specifying the - * {@code Content-Length: 0} header may work around that problem. - *

- * - * @since 1.11 - * @author Yaniv Inbar - */ -public class EmptyContent implements HttpContent { - - public long getLength() throws IOException { - return 0; - } - - public String getType() { - return null; - } - - public void writeTo(OutputStream out) throws IOException { - out.flush(); - } - - public boolean retrySupported() { - return true; - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/FileContent.java b/src/autosaveworld/zlibs/com/google/api/client/http/FileContent.java deleted file mode 100644 index 19d0b1ce..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/FileContent.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; - -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * Concrete implementation of {@link AbstractInputStreamContent} that generates repeatable input - * streams based on the contents of a file. - * - *

- * Sample use: - *

- * - *
- * 
-  private static void setRequestJpegContent(HttpRequest request, File jpegFile) {
-    request.setContent(new FileContent("image/jpeg", jpegFile));
-  }
- * 
- * 
- * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.4 - * @author moshenko@google.com (Jacob Moshenko) - */ -public final class FileContent extends AbstractInputStreamContent { - - private final File file; - - /** - * @param type Content type or {@code null} for none - * @param file file - * @since 1.5 - */ - public FileContent(String type, File file) { - super(type); - this.file = Preconditions.checkNotNull(file); - } - - public long getLength() { - return file.length(); - } - - public boolean retrySupported() { - return true; - } - - @Override - public InputStream getInputStream() throws FileNotFoundException { - return new FileInputStream(file); - } - - /** - * Returns the file. - * - * @since 1.5 - */ - public File getFile() { - return file; - } - - @Override - public FileContent setType(String type) { - return (FileContent) super.setType(type); - } - - @Override - public FileContent setCloseInputStream(boolean closeInputStream) { - return (FileContent) super.setCloseInputStream(closeInputStream); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/GZipEncoding.java b/src/autosaveworld/zlibs/com/google/api/client/http/GZipEncoding.java deleted file mode 100644 index 8dafd9d3..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/GZipEncoding.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.BufferedOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.zip.GZIPOutputStream; - -import autosaveworld.zlibs.com.google.api.client.util.StreamingContent; - -/** - * GZip HTTP content encoding. - * - * @since 1.14 - * @author Yaniv Inbar - */ -public class GZipEncoding implements HttpEncoding { - - public String getName() { - return "gzip"; - } - - public void encode(StreamingContent content, OutputStream out) throws IOException { - // must not close the underlying output stream - OutputStream out2 = new BufferedOutputStream(out) { - @Override - public void close() throws IOException { - // copy implementation of super.close(), except do not close the underlying output stream - try { - flush(); - } catch (IOException ignored) { - } - } - }; - GZIPOutputStream zipper = new GZIPOutputStream(out2); - content.writeTo(zipper); - // cannot call just zipper.finish() because that would cause a severe memory leak - zipper.close(); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/GenericUrl.java b/src/autosaveworld/zlibs/com/google/api/client/http/GenericUrl.java deleted file mode 100644 index dbfb2e12..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/GenericUrl.java +++ /dev/null @@ -1,641 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import autosaveworld.zlibs.com.google.api.client.util.GenericData; -import autosaveworld.zlibs.com.google.api.client.util.Key; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.escape.CharEscapers; -import autosaveworld.zlibs.com.google.api.client.util.escape.Escaper; -import autosaveworld.zlibs.com.google.api.client.util.escape.PercentEscaper; - -/** - * URL builder in which the query parameters are specified as generic data key/value pairs, based on - * the specification RFC 3986: Uniform Resource - * Identifier (URI). - * - *

- * The query parameters are specified with the data key name as the parameter name, and the data - * value as the parameter value. Subclasses can declare fields for known query parameters using the - * {@link Key} annotation. {@code null} parameter names are not allowed, but {@code null} query - * values are allowed. - *

- * - *

- * Query parameter values are parsed using {@link UrlEncodedParser#parse(String, Object)}. - *

- * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.0 - * @author Yaniv Inbar - */ -public class GenericUrl extends GenericData { - - private static final Escaper URI_FRAGMENT_ESCAPER = - new PercentEscaper("=&-_.!~*'()@:$,;/?:", false); - - /** Scheme (lowercase), for example {@code "https"}. */ - private String scheme; - - /** Host, for example {@code "www.google.com"}. */ - private String host; - - /** User info or {@code null} for none, for example {@code "username:password"}. */ - private String userInfo; - - /** Port number or {@code -1} if undefined, for example {@code 443}. */ - private int port = -1; - - /** - * Decoded path component by parts with each part separated by a {@code '/'} or {@code null} for - * none, for example {@code "/m8/feeds/contacts/default/full"} is represented by {@code "", "m8", - *"feeds", "contacts", "default", "full"}. - *

- * Use {@link #appendRawPath(String)} to append to the path, which ensures that no extra slash is - * added. - *

- */ - private List pathParts; - - /** Fragment component or {@code null} for none. */ - private String fragment; - - public GenericUrl() { - } - - /** - * Constructs from an encoded URL. - * - *

- * Any known query parameters with pre-defined fields as data keys will be parsed based on their - * data type. Any unrecognized query parameter will always be parsed as a string. - *

- * - *

- * Any {@link MalformedURLException} is wrapped in an {@link IllegalArgumentException}. - *

- * - *

Upgrade warning: starting in version 1.18 this parses the encodedUrl using - * new URL(encodedUrl). In previous versions it used new URI(encodedUrl). - * In particular, this means that only a limited set of schemes are allowed such as "http" and - * "https", but that parsing is compliant with, at least, RFC 3986.

- * - * @param encodedUrl encoded URL, including any existing query parameters that should be parsed - * @throws IllegalArgumentException if URL has a syntax error - */ - public GenericUrl(String encodedUrl) { - this(parseURL(encodedUrl)); - } - - /** - * Constructs from a URI. - * - * @param uri URI - * - * @since 1.14 - */ - public GenericUrl(URI uri) { - this(uri.getScheme(), - uri.getHost(), - uri.getPort(), - uri.getRawPath(), - uri.getRawFragment(), - uri.getRawQuery(), - uri.getRawUserInfo()); - } - - /** - * Constructs from a URL. - * - * @param url URL - * - * @since 1.14 - */ - public GenericUrl(URL url) { - this(url.getProtocol(), - url.getHost(), - url.getPort(), - url.getPath(), - url.getRef(), - url.getQuery(), - url.getUserInfo()); - } - - private GenericUrl(String scheme, - String host, - int port, - String path, - String fragment, - String query, - String userInfo) { - this.scheme = scheme.toLowerCase(); - this.host = host; - this.port = port; - this.pathParts = toPathParts(path); - this.fragment = fragment != null ? CharEscapers.decodeUri(fragment) : null; - if (query != null) { - UrlEncodedParser.parse(query, this); - } - this.userInfo = userInfo != null ? CharEscapers.decodeUri(userInfo) : null; - } - - @Override - public int hashCode() { - // TODO(yanivi): optimize? - return build().hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!super.equals(obj) || !(obj instanceof GenericUrl)) { - return false; - } - GenericUrl other = (GenericUrl) obj; - // TODO(yanivi): optimize? - return build().equals(other.toString()); - } - - @Override - public String toString() { - return build(); - } - - @Override - public GenericUrl clone() { - GenericUrl result = (GenericUrl) super.clone(); - if (pathParts != null) { - result.pathParts = new ArrayList(pathParts); - } - return result; - } - - @Override - public GenericUrl set(String fieldName, Object value) { - return (GenericUrl) super.set(fieldName, value); - } - - /** - * Returns the scheme (lowercase), for example {@code "https"}. - * - * @since 1.5 - */ - public final String getScheme() { - return scheme; - } - - /** - * Sets the scheme (lowercase), for example {@code "https"}. - * - * @since 1.5 - */ - public final void setScheme(String scheme) { - this.scheme = Preconditions.checkNotNull(scheme); - } - - /** - * Returns the host, for example {@code "www.google.com"}. - * - * @since 1.5 - */ - public String getHost() { - return host; - } - - /** - * Sets the host, for example {@code "www.google.com"}. - * - * @since 1.5 - */ - public final void setHost(String host) { - this.host = Preconditions.checkNotNull(host); - } - - /** - * Returns the user info or {@code null} for none, for example {@code "username:password"}. - * - * @since 1.15 - */ - public final String getUserInfo() { - return userInfo; - } - - /** - * Sets the user info or {@code null} for none, for example {@code "username:password"}. - * - * @since 1.15 - */ - public final void setUserInfo(String userInfo) { - this.userInfo = userInfo; - } - - /** - * Returns the port number or {@code -1} if undefined, for example {@code 443}. - * - * @since 1.5 - */ - public int getPort() { - return port; - } - - /** - * Sets the port number, for example {@code 443}. - * - * @since 1.5 - */ - public final void setPort(int port) { - Preconditions.checkArgument(port >= -1, "expected port >= -1"); - this.port = port; - } - - /** - * Returns the decoded path component by parts with each part separated by a {@code '/'} or - * {@code null} for none. - * - * @since 1.5 - */ - public List getPathParts() { - return pathParts; - } - - /** - * Sets the decoded path component by parts with each part separated by a {@code '/'} or - * {@code null} for none. - * - *

- * For example {@code "/m8/feeds/contacts/default/full"} is represented by {@code "", "m8", - *"feeds", "contacts", "default", "full"}. - *

- * - *

- * Use {@link #appendRawPath(String)} to append to the path, which ensures that no extra slash is - * added. - *

- * - * @since 1.5 - */ - public void setPathParts(List pathParts) { - this.pathParts = pathParts; - } - - /** - * Returns the fragment component or {@code null} for none. - * - * @since 1.5 - */ - public String getFragment() { - return fragment; - } - - /** - * Sets the fragment component or {@code null} for none. - * - * @since 1.5 - */ - public final void setFragment(String fragment) { - this.fragment = fragment; - } - - /** - * Constructs the string representation of the URL, including the path specified by - * {@link #pathParts} and the query parameters specified by this generic URL. - */ - public final String build() { - return buildAuthority() + buildRelativeUrl(); - } - - /** - * Constructs the portion of the URL containing the scheme, host and port. - * - *

- * For the URL {@code "http://example.com/something?action=add"} this method would return - * {@code "http://example.com"}. - *

- * - * @return scheme://[user-info@]host[:port] - * @since 1.9 - */ - public final String buildAuthority() { - // scheme, [user info], host, [port] - StringBuilder buf = new StringBuilder(); - buf.append(Preconditions.checkNotNull(scheme)); - buf.append("://"); - if (userInfo != null) { - buf.append(CharEscapers.escapeUriUserInfo(userInfo)).append('@'); - } - buf.append(Preconditions.checkNotNull(host)); - int port = this.port; - if (port != -1) { - buf.append(':').append(port); - } - return buf.toString(); - } - - /** - * Constructs the portion of the URL beginning at the rooted path. - * - *

- * For the URL {@code "http://example.com/something?action=add"} this method would return - * {@code "/something?action=add"}. - *

- * - * @return path with with leading '/' if the path is non-empty, query parameters and fragment - * @since 1.9 - */ - public final String buildRelativeUrl() { - StringBuilder buf = new StringBuilder(); - if (pathParts != null) { - appendRawPathFromParts(buf); - } - addQueryParams(entrySet(), buf); - - // URL fragment - String fragment = this.fragment; - if (fragment != null) { - buf.append('#').append(URI_FRAGMENT_ESCAPER.escape(fragment)); - } - return buf.toString(); - } - - /** - * Constructs the URI based on the string representation of the URL from {@link #build()}. - * - *

- * Any {@link URISyntaxException} is wrapped in an {@link IllegalArgumentException}. - *

- * - * @return new URI instance - * - * @since 1.14 - */ - public final URI toURI() { - return toURI(build()); - } - - /** - * Constructs the URL based on the string representation of the URL from {@link #build()}. - * - *

- * Any {@link MalformedURLException} is wrapped in an {@link IllegalArgumentException}. - *

- * - * @return new URL instance - * - * @since 1.14 - */ - public final URL toURL() { - return parseURL(build()); - } - - /** - * Constructs the URL based on {@link URL#URL(URL, String)} with this URL representation from - * {@link #toURL()} and a relative url. - * - *

- * Any {@link MalformedURLException} is wrapped in an {@link IllegalArgumentException}. - *

- * - * @return new URL instance - * - * @since 1.14 - */ - public final URL toURL(String relativeUrl) { - try { - URL url = toURL(); - return new URL(url, relativeUrl); - } catch (MalformedURLException e) { - throw new IllegalArgumentException(e); - } - } - - /** - * Returns the first query parameter value for the given query parameter name. - * - * @param name query parameter name - * @return first query parameter value - */ - public Object getFirst(String name) { - Object value = get(name); - if (value instanceof Collection) { - @SuppressWarnings("unchecked") - Collection collectionValue = (Collection) value; - Iterator iterator = collectionValue.iterator(); - return iterator.hasNext() ? iterator.next() : null; - } - return value; - } - - /** - * Returns all query parameter values for the given query parameter name. - * - * @param name query parameter name - * @return unmodifiable collection of query parameter values (possibly empty) - */ - public Collection getAll(String name) { - Object value = get(name); - if (value == null) { - return Collections.emptySet(); - } - if (value instanceof Collection) { - @SuppressWarnings("unchecked") - Collection collectionValue = (Collection) value; - return Collections.unmodifiableCollection(collectionValue); - } - return Collections.singleton(value); - } - - /** - * Returns the raw encoded path computed from the {@link #pathParts}. - * - * @return raw encoded path computed from the {@link #pathParts} or {@code null} if - * {@link #pathParts} is {@code null} - */ - public String getRawPath() { - List pathParts = this.pathParts; - if (pathParts == null) { - return null; - } - StringBuilder buf = new StringBuilder(); - appendRawPathFromParts(buf); - return buf.toString(); - } - - /** - * Sets the {@link #pathParts} from the given raw encoded path. - * - * @param encodedPath raw encoded path or {@code null} to set {@link #pathParts} to {@code null} - */ - public void setRawPath(String encodedPath) { - pathParts = toPathParts(encodedPath); - } - - /** - * Appends the given raw encoded path to the current {@link #pathParts}, setting field only if it - * is {@code null} or empty. - *

- * The last part of the {@link #pathParts} is merged with the first part of the path parts - * computed from the given encoded path. Thus, if the current raw encoded path is {@code "a"}, and - * the given encoded path is {@code "b"}, then the resulting raw encoded path is {@code "ab"}. - *

- * - * @param encodedPath raw encoded path or {@code null} to ignore - */ - public void appendRawPath(String encodedPath) { - if (encodedPath != null && encodedPath.length() != 0) { - List appendedPathParts = toPathParts(encodedPath); - if (pathParts == null || pathParts.isEmpty()) { - this.pathParts = appendedPathParts; - } else { - int size = pathParts.size(); - pathParts.set(size - 1, pathParts.get(size - 1) + appendedPathParts.get(0)); - pathParts.addAll(appendedPathParts.subList(1, appendedPathParts.size())); - } - } - } - - /** - * Returns the decoded path parts for the given encoded path. - * - * @param encodedPath slash-prefixed encoded path, for example - * {@code "/m8/feeds/contacts/default/full"} - * @return decoded path parts, with each part assumed to be preceded by a {@code '/'}, for example - * {@code "", "m8", "feeds", "contacts", "default", "full"}, or {@code null} for - * {@code null} or {@code ""} input - */ - public static List toPathParts(String encodedPath) { - if (encodedPath == null || encodedPath.length() == 0) { - return null; - } - List result = new ArrayList(); - int cur = 0; - boolean notDone = true; - while (notDone) { - int slash = encodedPath.indexOf('/', cur); - notDone = slash != -1; - String sub; - if (notDone) { - sub = encodedPath.substring(cur, slash); - } else { - sub = encodedPath.substring(cur); - } - result.add(CharEscapers.decodeUri(sub)); - cur = slash + 1; - } - return result; - } - - private void appendRawPathFromParts(StringBuilder buf) { - int size = pathParts.size(); - for (int i = 0; i < size; i++) { - String pathPart = pathParts.get(i); - if (i != 0) { - buf.append('/'); - } - if (pathPart.length() != 0) { - buf.append(CharEscapers.escapeUriPath(pathPart)); - } - } - } - - /** - * Adds query parameters from the provided entrySet into the buffer. - */ - static void addQueryParams(Set> entrySet, StringBuilder buf) { - // (similar to UrlEncodedContent) - boolean first = true; - for (Map.Entry nameValueEntry : entrySet) { - Object value = nameValueEntry.getValue(); - if (value != null) { - String name = CharEscapers.escapeUriQuery(nameValueEntry.getKey()); - if (value instanceof Collection) { - Collection collectionValue = (Collection) value; - for (Object repeatedValue : collectionValue) { - first = appendParam(first, buf, name, repeatedValue); - } - } else { - first = appendParam(first, buf, name, value); - } - } - } - } - - private static boolean appendParam(boolean first, StringBuilder buf, String name, Object value) { - if (first) { - first = false; - buf.append('?'); - } else { - buf.append('&'); - } - buf.append(name); - String stringValue = CharEscapers.escapeUriQuery(value.toString()); - if (stringValue.length() != 0) { - buf.append('=').append(stringValue); - } - return first; - } - - /** - * Returns the URI for the given encoded URL. - * - *

- * Any {@link URISyntaxException} is wrapped in an {@link IllegalArgumentException}. - *

- * - * @param encodedUrl encoded URL - * @return URI - */ - private static URI toURI(String encodedUrl) { - try { - return new URI(encodedUrl); - } catch (URISyntaxException e) { - throw new IllegalArgumentException(e); - } - } - - /** - * Returns the URI for the given encoded URL. - * - *

- * Any {@link MalformedURLException} is wrapped in an {@link IllegalArgumentException}. - *

- * - * @param encodedUrl encoded URL - * @return URL - */ - private static URL parseURL(String encodedUrl) { - try { - return new URL(encodedUrl); - } catch (MalformedURLException e) { - throw new IllegalArgumentException(e); - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/HttpBackOffIOExceptionHandler.java b/src/autosaveworld/zlibs/com/google/api/client/http/HttpBackOffIOExceptionHandler.java deleted file mode 100644 index 578bf9fb..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/HttpBackOffIOExceptionHandler.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.IOException; - -import autosaveworld.zlibs.com.google.api.client.util.BackOff; -import autosaveworld.zlibs.com.google.api.client.util.BackOffUtils; -import autosaveworld.zlibs.com.google.api.client.util.Beta; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.Sleeper; - -/** - * {@link Beta}
- * {@link HttpIOExceptionHandler} implementation with {@link BackOff}. - * - *

- * It is designed to work with only one {@link HttpRequest} at a time. As a result you MUST create a - * new instance of {@link HttpBackOffIOExceptionHandler} with a new instance of {@link BackOff} for - * each instance of {@link HttpRequest}. - *

- * - *

- * Sample usage: - *

- * - *
-  request.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(new ExponentialBackOff());
- * 
- * - *

- * Note: Implementation doesn't call {@link BackOff#reset} at all, since it expects a new - * {@link BackOff} instance. - *

- * - *

- * Implementation is not thread-safe - *

- * - * @author Eyal Peled - * @since 1.15 - */ -@Beta -public class HttpBackOffIOExceptionHandler implements HttpIOExceptionHandler { - - /** Back-off policy. */ - private final BackOff backOff; - - /** Sleeper. */ - private Sleeper sleeper = Sleeper.DEFAULT; - - /** - * Constructs a new instance from a {@link BackOff}. - * - * @param backOff back-off policy - */ - public HttpBackOffIOExceptionHandler(BackOff backOff) { - this.backOff = Preconditions.checkNotNull(backOff); - } - - /** Returns the back-off. */ - public final BackOff getBackOff() { - return backOff; - } - - /** Returns the sleeper. */ - public final Sleeper getSleeper() { - return sleeper; - } - - /** - * Sets the sleeper. - * - *

- * The default value is {@link Sleeper#DEFAULT}. - *

- * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public HttpBackOffIOExceptionHandler setSleeper(Sleeper sleeper) { - this.sleeper = Preconditions.checkNotNull(sleeper); - return this; - } - - /** - * {@inheritDoc} - * - *

- * Handles the request with {@link BackOff}. That means that if back-off is required a call to - * {@link Sleeper#sleep(long)} will be made. - *

- */ - public boolean handleIOException(HttpRequest request, boolean supportsRetry) throws IOException { - if (!supportsRetry) { - return false; - } - try { - return BackOffUtils.next(sleeper, backOff); - } catch (InterruptedException exception) { - return false; - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/HttpBackOffUnsuccessfulResponseHandler.java b/src/autosaveworld/zlibs/com/google/api/client/http/HttpBackOffUnsuccessfulResponseHandler.java deleted file mode 100644 index 42b5abe9..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/HttpBackOffUnsuccessfulResponseHandler.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.IOException; - -import autosaveworld.zlibs.com.google.api.client.util.BackOff; -import autosaveworld.zlibs.com.google.api.client.util.BackOffUtils; -import autosaveworld.zlibs.com.google.api.client.util.Beta; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.Sleeper; - -/** - * {@link Beta}
- * Back-off handler which handles an abnormal HTTP response with {@link BackOff}. - * - *

- * It is designed to work with only one {@link HttpRequest} at a time. As a result you MUST create a - * new instance of {@link HttpBackOffUnsuccessfulResponseHandler} with a new instance of - * {@link BackOff} for each instance of {@link HttpRequest}. - *

- * - *

- * Sample usage: - *

- * - *
-  request.setUnsuccessfulResponseHandler(
-    new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()));
- * 
- * - *

- * Note: Implementation doesn't call {@link BackOff#reset} at all, since it expects a new - * {@link BackOff} instance. - *

- * - *

- * Implementation is not thread-safe - *

- * - * @author Eyal Peled - * @since 1.15 - */ -@Beta -public class HttpBackOffUnsuccessfulResponseHandler implements HttpUnsuccessfulResponseHandler { - - /** Back-off policy. */ - private final BackOff backOff; - - /** Defines if back-off is required based on an abnormal HTTP response. */ - private BackOffRequired backOffRequired = BackOffRequired.ON_SERVER_ERROR; - - /** Sleeper. */ - private Sleeper sleeper = Sleeper.DEFAULT; - - /** - * Constructs a new instance from a {@link BackOff}. - * - * @param backOff back-off policy - */ - public HttpBackOffUnsuccessfulResponseHandler(BackOff backOff) { - this.backOff = Preconditions.checkNotNull(backOff); - } - - /** Returns the back-off. */ - public final BackOff getBackOff() { - return backOff; - } - - /** - * Returns the {@link BackOffRequired} instance which determines if back-off is required based on - * an abnormal HTTP response. - */ - public final BackOffRequired getBackOffRequired() { - return backOffRequired; - } - - /** - * Sets the {@link BackOffRequired} instance which determines if back-off is required based on an - * abnormal HTTP response. - * - *

- * The default value is {@link BackOffRequired#ON_SERVER_ERROR}. - *

- * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public HttpBackOffUnsuccessfulResponseHandler setBackOffRequired( - BackOffRequired backOffRequired) { - this.backOffRequired = Preconditions.checkNotNull(backOffRequired); - return this; - } - - /** Returns the sleeper. */ - public final Sleeper getSleeper() { - return sleeper; - } - - /** - * Sets the sleeper. - * - *

- * The default value is {@link Sleeper#DEFAULT}. - *

- * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public HttpBackOffUnsuccessfulResponseHandler setSleeper(Sleeper sleeper) { - this.sleeper = Preconditions.checkNotNull(sleeper); - return this; - } - - /** - * {@inheritDoc} - * - *

- * Handles the request with {@link BackOff}. That means that if back-off is required a call to - * {@link Sleeper#sleep(long)} will be made. - *

- */ - public final boolean handleResponse( - HttpRequest request, HttpResponse response, boolean supportsRetry) throws IOException { - if (!supportsRetry) { - return false; - } - // check if back-off is required for this response - if (backOffRequired.isRequired(response)) { - try { - return BackOffUtils.next(sleeper, backOff); - } catch (InterruptedException exception) { - // ignore - } - } - return false; - } - - /** - * {@link Beta}
- * Interface which defines if back-off is required based on an abnormal {@link HttpResponse}. - * - * @author Eyal Peled - */ - @Beta - public interface BackOffRequired { - - /** Invoked when an abnormal response is received and determines if back-off is required. */ - boolean isRequired(HttpResponse response); - - /** - * Back-off required implementation which returns {@code true} to every - * {@link #isRequired(HttpResponse)} call. - */ - BackOffRequired ALWAYS = new BackOffRequired() { - public boolean isRequired(HttpResponse response) { - return true; - } - }; - - /** - * Back-off required implementation which its {@link #isRequired(HttpResponse)} returns - * {@code true} if a server error occurred (5xx). - */ - BackOffRequired ON_SERVER_ERROR = new BackOffRequired() { - public boolean isRequired(HttpResponse response) { - return response.getStatusCode() / 100 == 5; - } - }; - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/HttpContent.java b/src/autosaveworld/zlibs/com/google/api/client/http/HttpContent.java deleted file mode 100644 index f6bc0033..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/HttpContent.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.IOException; -import java.io.OutputStream; - -import autosaveworld.zlibs.com.google.api.client.util.StreamingContent; - -/** - * Serializes HTTP request content into an output stream. - * - *

- * Implementations don't need to be thread-safe. - *

- * - * @since 1.0 - * @author Yaniv Inbar - */ -public interface HttpContent extends StreamingContent { - - /** Returns the content length or less than zero if not known. */ - long getLength() throws IOException; - - /** Returns the content type or {@code null} for none. */ - String getType(); - - /** - * Returns whether or not retry is supported on this content type. - * - * @since 1.4 - */ - boolean retrySupported(); - - void writeTo(OutputStream out) throws IOException; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/HttpEncoding.java b/src/autosaveworld/zlibs/com/google/api/client/http/HttpEncoding.java deleted file mode 100644 index bd22f113..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/HttpEncoding.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.IOException; -import java.io.OutputStream; - -import autosaveworld.zlibs.com.google.api.client.util.StreamingContent; - -/** - * HTTP content encoding. - * - *

- * Implementations don't need to be thread-safe. - *

- * - * @since 1.14 - * @author Yaniv Inbar - */ -public interface HttpEncoding { - - /** Returns the content encoding name (for example {@code "gzip"}) or {@code null} for none. */ - String getName(); - - /** - * Encodes the streaming content into the output stream. - * - *

- * Implementations must not close the output stream, and instead should flush the output stream. - * Some callers may assume that the the output stream has not been closed, and will fail to work - * if it has been closed. - *

- * - * @param content streaming content - * @param out output stream - */ - void encode(StreamingContent content, OutputStream out) throws IOException; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/HttpEncodingStreamingContent.java b/src/autosaveworld/zlibs/com/google/api/client/http/HttpEncodingStreamingContent.java deleted file mode 100644 index 4f9cf498..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/HttpEncodingStreamingContent.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.IOException; -import java.io.OutputStream; - -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.StreamingContent; - -/** - * Streaming content based on an HTTP encoding. - * - *

- * Implementation is thread-safe only if the streaming content and HTTP encoding are thread-safe. - *

- * - * @since 1.14 - * @author Yaniv Inbar - */ -public final class HttpEncodingStreamingContent implements StreamingContent { - - /** Streaming content. */ - private final StreamingContent content; - - /** HTTP encoding. */ - private final HttpEncoding encoding; - - /** - * @param content streaming content - * @param encoding HTTP encoding - */ - public HttpEncodingStreamingContent(StreamingContent content, HttpEncoding encoding) { - this.content = Preconditions.checkNotNull(content); - this.encoding = Preconditions.checkNotNull(encoding); - } - - public void writeTo(OutputStream out) throws IOException { - encoding.encode(content, out); - } - - /** Returns the streaming content. */ - public StreamingContent getContent() { - return content; - } - - /** Returns the HTTP encoding. */ - public HttpEncoding getEncoding() { - return encoding; - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/HttpExecuteInterceptor.java b/src/autosaveworld/zlibs/com/google/api/client/http/HttpExecuteInterceptor.java deleted file mode 100644 index 62e737bf..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/HttpExecuteInterceptor.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.IOException; - -/** - * HTTP request execute interceptor to intercept the start of {@link HttpRequest#execute()} before - * executing the HTTP request. - * - *

- * For example, this might be used to sign a request for OAuth: - *

- * - *
-  public class OAuthSigner implements HttpExecuteInterceptor {
-    public void intercept(HttpRequest request) throws IOException {
-      // sign request...
-    }
-  }
- * 
- * - *

- * Sample usage with a request factory: - *

- * - *
-  public static HttpRequestFactory createRequestFactory(HttpTransport transport) {
-    final OAuthSigner signer = new OAuthSigner(...);
-    return transport.createRequestFactory(new HttpRequestInitializer() {
-      public void initialize(HttpRequest request) {
-        request.setInterceptor(signer);
-      }
-    });
-  }
- * 
- * - *

- * More complex usage example: - *

- * - *
-  public static HttpRequestFactory createRequestFactory2(HttpTransport transport) {
-    final OAuthSigner signer = new OAuthSigner(...);
-    return transport.createRequestFactory(new HttpRequestInitializer() {
-      public void initialize(HttpRequest request) {
-        request.setInterceptor(new HttpExecuteInterceptor() {
-          public void intercept(HttpRequest request) throws IOException {
-            signer.intercept(request);
-          }
-        });
-      }
-    });
-  }
- * 
- * - *

- * Implementations should normally be thread-safe. - *

- * - * @since 1.0 - * @author Yaniv Inbar - */ -public interface HttpExecuteInterceptor { - - /** Invoked at the start of {@link HttpRequest#execute()} before executing the HTTP request. */ - void intercept(HttpRequest request) throws IOException; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/HttpHeaders.java b/src/autosaveworld/zlibs/com/google/api/client/http/HttpHeaders.java deleted file mode 100644 index caa67cff..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/HttpHeaders.java +++ /dev/null @@ -1,1182 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.IOException; -import java.io.Writer; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -import autosaveworld.zlibs.com.google.api.client.util.ArrayValueMap; -import autosaveworld.zlibs.com.google.api.client.util.Base64; -import autosaveworld.zlibs.com.google.api.client.util.ClassInfo; -import autosaveworld.zlibs.com.google.api.client.util.Data; -import autosaveworld.zlibs.com.google.api.client.util.FieldInfo; -import autosaveworld.zlibs.com.google.api.client.util.GenericData; -import autosaveworld.zlibs.com.google.api.client.util.Key; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.StringUtils; -import autosaveworld.zlibs.com.google.api.client.util.Throwables; -import autosaveworld.zlibs.com.google.api.client.util.Types; - -/** - * Stores HTTP headers used in an HTTP request or response, as defined in Header Field Definitions. - * - *

- * {@code null} is not allowed as a name or value of a header. Names are case-insensitive. - *

- * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.0 - * @author Yaniv Inbar - */ -public class HttpHeaders extends GenericData { - - public HttpHeaders() { - super(EnumSet.of(Flags.IGNORE_CASE)); - } - - /** {@code "Accept"} header. */ - @Key("Accept") - private List accept; - - /** {@code "Accept-Encoding"} header. */ - @Key("Accept-Encoding") - private List acceptEncoding = new ArrayList(Collections.singleton("gzip")); - - /** {@code "Authorization"} header. */ - @Key("Authorization") - private List authorization; - - /** {@code "Cache-Control"} header. */ - @Key("Cache-Control") - private List cacheControl; - - /** {@code "Content-Encoding"} header. */ - @Key("Content-Encoding") - private List contentEncoding; - - /** {@code "Content-Length"} header. */ - @Key("Content-Length") - private List contentLength; - - /** {@code "Content-MD5"} header. */ - @Key("Content-MD5") - private List contentMD5; - - /** {@code "Content-Range"} header. */ - @Key("Content-Range") - private List contentRange; - - /** {@code "Content-Type"} header. */ - @Key("Content-Type") - private List contentType; - - /** {@code "Cookie"} header. */ - @Key("Cookie") - private List cookie; - - /** {@code "Date"} header. */ - @Key("Date") - private List date; - - /** {@code "ETag"} header. */ - @Key("ETag") - private List etag; - - /** {@code "Expires"} header. */ - @Key("Expires") - private List expires; - - /** {@code "If-Modified-Since"} header. */ - @Key("If-Modified-Since") - private List ifModifiedSince; - - /** {@code "If-Match"} header. */ - @Key("If-Match") - private List ifMatch; - - /** {@code "If-None-Match"} header. */ - @Key("If-None-Match") - private List ifNoneMatch; - - /** {@code "If-Unmodified-Since"} header. */ - @Key("If-Unmodified-Since") - private List ifUnmodifiedSince; - - /** {@code "If-Range"} header. */ - @Key("If-Range") - private List ifRange; - - /** {@code "Last-Modified"} header. */ - @Key("Last-Modified") - private List lastModified; - - /** {@code "Location"} header. */ - @Key("Location") - private List location; - - /** {@code "MIME-Version"} header. */ - @Key("MIME-Version") - private List mimeVersion; - - /** {@code "Range"} header. */ - @Key("Range") - private List range; - - /** {@code "Retry-After"} header. */ - @Key("Retry-After") - private List retryAfter; - - /** {@code "User-Agent"} header. */ - @Key("User-Agent") - private List userAgent; - - /** {@code "WWW-Authenticate"} header. */ - @Key("WWW-Authenticate") - private List authenticate; - - /** {@code "Age"} header. */ - @Key("Age") - private List age; - - @Override - public HttpHeaders clone() { - return (HttpHeaders) super.clone(); - } - - @Override - public HttpHeaders set(String fieldName, Object value) { - return (HttpHeaders) super.set(fieldName, value); - } - - /** - * Returns the first {@code "Accept"} header or {@code null} for none. - * - * @since 1.5 - */ - public final String getAccept() { - return getFirstHeaderValue(accept); - } - - /** - * Sets the {@code "Accept"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public HttpHeaders setAccept(String accept) { - this.accept = getAsList(accept); - return this; - } - - /** - * Returns the first {@code "Accept-Encoding"} header or {@code null} for none. - * - * @since 1.5 - */ - public final String getAcceptEncoding() { - return getFirstHeaderValue(acceptEncoding); - } - - /** - * Sets the {@code "Accept-Encoding"} header or {@code null} for none. - * - *

- * By default, this is {@code "gzip"}. - *

- * - * @since 1.5 - */ - public HttpHeaders setAcceptEncoding(String acceptEncoding) { - this.acceptEncoding = getAsList(acceptEncoding); - return this; - } - - /** - * Returns the first {@code "Authorization"} header or {@code null} for none. - * - * @since 1.5 - */ - public final String getAuthorization() { - return getFirstHeaderValue(authorization); - } - - /** - * Returns all {@code "Authorization"} headers or {@code null} for none. - * - * @since 1.13 - */ - public final List getAuthorizationAsList() { - return authorization; - } - - /** - * Sets the {@code "Authorization"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public HttpHeaders setAuthorization(String authorization) { - return setAuthorization(getAsList(authorization)); - } - - /** - * Sets the {@code "Authorization"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.13 - */ - public HttpHeaders setAuthorization(List authorization) { - this.authorization = authorization; - return this; - } - - /** - * Returns the first {@code "Cache-Control"} header or {@code null} for none. - * - * @since 1.5 - */ - public final String getCacheControl() { - return getFirstHeaderValue(cacheControl); - } - - /** - * Sets the {@code "Cache-Control"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public HttpHeaders setCacheControl(String cacheControl) { - this.cacheControl = getAsList(cacheControl); - return this; - } - - /** - * Returns the first {@code "Content-Encoding"} header or {@code null} for none. - * - * @since 1.5 - */ - public final String getContentEncoding() { - return getFirstHeaderValue(contentEncoding); - } - - /** - * Sets the {@code "Content-Encoding"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public HttpHeaders setContentEncoding(String contentEncoding) { - this.contentEncoding = getAsList(contentEncoding); - return this; - } - - /** - * Returns the first {@code "Content-Length"} header or {@code null} for none. - * - * @since 1.5 - */ - public final Long getContentLength() { - return getFirstHeaderValue(contentLength); - } - - /** - * Sets the {@code "Content-Length"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public HttpHeaders setContentLength(Long contentLength) { - this.contentLength = getAsList(contentLength); - return this; - } - - /** - * Returns the first {@code "Content-MD5"} header or {@code null} for none. - * - * @since 1.5 - */ - public final String getContentMD5() { - return getFirstHeaderValue(contentMD5); - } - - /** - * Sets the {@code "Content-MD5"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public HttpHeaders setContentMD5(String contentMD5) { - this.contentMD5 = getAsList(contentMD5); - return this; - } - - /** - * Returns the first {@code "Content-Range"} header or {@code null} for none. - * - * @since 1.5 - */ - public final String getContentRange() { - return getFirstHeaderValue(contentRange); - } - - /** - * Sets the {@code "Content-Range"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public HttpHeaders setContentRange(String contentRange) { - this.contentRange = getAsList(contentRange); - return this; - } - - /** - * Returns the first {@code "Content-Type"} header or {@code null} for none. - * - * @since 1.5 - */ - public final String getContentType() { - return getFirstHeaderValue(contentType); - } - - /** - * Sets the {@code "Content-Type"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public HttpHeaders setContentType(String contentType) { - this.contentType = getAsList(contentType); - return this; - } - - /** - * Returns the first {@code "Cookie"} header or {@code null} for none. - * - *

- * See Cookie Specification. - *

- * - * @since 1.6 - */ - public final String getCookie() { - return getFirstHeaderValue(cookie); - } - - /** - * Sets the {@code "Cookie"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.6 - */ - public HttpHeaders setCookie(String cookie) { - this.cookie = getAsList(cookie); - return this; - } - - /** - * Returns the first {@code "Date"} header or {@code null} for none. - * - * @since 1.5 - */ - public final String getDate() { - return getFirstHeaderValue(date); - } - - /** - * Sets the {@code "Date"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public HttpHeaders setDate(String date) { - this.date = getAsList(date); - return this; - } - - /** - * Returns the first {@code "ETag"} header or {@code null} for none. - * - * @since 1.5 - */ - public final String getETag() { - return getFirstHeaderValue(etag); - } - - /** - * Sets the {@code "ETag"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public HttpHeaders setETag(String etag) { - this.etag = getAsList(etag); - return this; - } - - /** - * Returns the first {@code "Expires"} header or {@code null} for none. - * - * @since 1.5 - */ - public final String getExpires() { - return getFirstHeaderValue(expires); - } - - /** - * Sets the {@code "Expires"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public HttpHeaders setExpires(String expires) { - this.expires = getAsList(expires); - return this; - } - - /** - * Returns the first {@code "If-Modified-Since"} header or {@code null} for none. - * - * @since 1.5 - */ - public final String getIfModifiedSince() { - return getFirstHeaderValue(ifModifiedSince); - } - - /** - * Sets the {@code "If-Modified-Since"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public HttpHeaders setIfModifiedSince(String ifModifiedSince) { - this.ifModifiedSince = getAsList(ifModifiedSince); - return this; - } - - /** - * Returns the first {@code "If-Match"} header or {@code null} for none. - * - * @since 1.5 - */ - public final String getIfMatch() { - return getFirstHeaderValue(ifMatch); - } - - /** - * Sets the {@code "If-Match"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public HttpHeaders setIfMatch(String ifMatch) { - this.ifMatch = getAsList(ifMatch); - return this; - } - - /** - * Returns the first {@code "If-None-Match"} header or {@code null} for none. - * - * @since 1.5 - */ - public final String getIfNoneMatch() { - return getFirstHeaderValue(ifNoneMatch); - } - - /** - * Sets the {@code "If-None-Match"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public HttpHeaders setIfNoneMatch(String ifNoneMatch) { - this.ifNoneMatch = getAsList(ifNoneMatch); - return this; - } - - /** - * Returns the first {@code "If-Unmodified-Since"} header or {@code null} for none. - * - * @since 1.5 - */ - public final String getIfUnmodifiedSince() { - return getFirstHeaderValue(ifUnmodifiedSince); - } - - /** - * Sets the {@code "If-Unmodified-Since"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public HttpHeaders setIfUnmodifiedSince(String ifUnmodifiedSince) { - this.ifUnmodifiedSince = getAsList(ifUnmodifiedSince); - return this; - } - - /** - * Returns the first {@code "If-Range"} header or {@code null} for none. - * - * @since 1.14 - */ - public final String getIfRange() { - return getFirstHeaderValue(ifRange); - } - - /** - * Sets the {@code "If-Range"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.14 - */ - public HttpHeaders setIfRange(String ifRange) { - this.ifRange = getAsList(ifRange); - return this; - } - - /** - * Returns the first {@code "Last-Modified"} header or {@code null} for none. - * - * @since 1.5 - */ - public final String getLastModified() { - return getFirstHeaderValue(lastModified); - } - - /** - * Sets the {@code "Last-Modified"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public HttpHeaders setLastModified(String lastModified) { - this.lastModified = getAsList(lastModified); - return this; - } - - /** - * Returns the first {@code "Location"} header or {@code null} for none. - * - * @since 1.5 - */ - public final String getLocation() { - return getFirstHeaderValue(location); - } - - /** - * Sets the {@code "Location"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public HttpHeaders setLocation(String location) { - this.location = getAsList(location); - return this; - } - - /** - * Returns the first {@code "MIME-Version"} header or {@code null} for none. - * - * @since 1.5 - */ - public final String getMimeVersion() { - return getFirstHeaderValue(mimeVersion); - } - - /** - * Sets the {@code "MIME-Version"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public HttpHeaders setMimeVersion(String mimeVersion) { - this.mimeVersion = getAsList(mimeVersion); - return this; - } - - /** - * Returns the first {@code "Range"} header or {@code null} for none. - * - * @since 1.5 - */ - public final String getRange() { - return getFirstHeaderValue(range); - } - - /** - * Sets the {@code "Range"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public HttpHeaders setRange(String range) { - this.range = getAsList(range); - return this; - } - - /** - * Returns the first {@code "Retry-After"} header or {@code null} for none. - * - * @since 1.5 - */ - public final String getRetryAfter() { - return getFirstHeaderValue(retryAfter); - } - - /** - * Sets the {@code "Retry-After"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public HttpHeaders setRetryAfter(String retryAfter) { - this.retryAfter = getAsList(retryAfter); - return this; - } - - /** - * Returns the first {@code "User-Agent"} header or {@code null} for none. - * - * @since 1.5 - */ - public final String getUserAgent() { - return getFirstHeaderValue(userAgent); - } - - /** - * Sets the {@code "User-Agent"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public HttpHeaders setUserAgent(String userAgent) { - this.userAgent = getAsList(userAgent); - return this; - } - - /** - * Returns the first {@code "WWW-Authenticate"} header or {@code null} for none. - * - * @since 1.5 - */ - public final String getAuthenticate() { - return getFirstHeaderValue(authenticate); - } - - /** - * Returns all {@code "WWW-Authenticate"} headers or {@code null} for none. - * - * @since 1.16 - */ - public final List getAuthenticateAsList() { - return authenticate; - } - - /** - * Sets the {@code "WWW-Authenticate"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public HttpHeaders setAuthenticate(String authenticate) { - this.authenticate = getAsList(authenticate); - return this; - } - - /** - * Returns the first {@code "Age"} header or {@code null} for none. - * - * @since 1.14 - */ - public final Long getAge() { - return getFirstHeaderValue(age); - } - - /** - * Sets the {@code "Age"} header or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.14 - */ - public HttpHeaders setAge(Long age) { - this.age = getAsList(age); - return this; - } - - /** - * Sets the {@link #authorization} header as specified in Basic Authentication Scheme. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.2 - */ - public HttpHeaders setBasicAuthentication(String username, String password) { - String userPass = - Preconditions.checkNotNull(username) + ":" + Preconditions.checkNotNull(password); - String encoded = Base64.encodeBase64String(StringUtils.getBytesUtf8(userPass)); - return setAuthorization("Basic " + encoded); - } - - private static void addHeader(Logger logger, - StringBuilder logbuf, - StringBuilder curlbuf, - LowLevelHttpRequest lowLevelHttpRequest, - String name, - Object value, - Writer writer) throws IOException { - // ignore nulls - if (value == null || Data.isNull(value)) { - return; - } - // compute value - String stringValue = toStringValue(value); - // log header - String loggedStringValue = stringValue; - if (("Authorization".equalsIgnoreCase(name) || "Cookie".equalsIgnoreCase(name)) - && (logger == null || !logger.isLoggable(Level.ALL))) { - loggedStringValue = ""; - } - if (logbuf != null) { - logbuf.append(name).append(": "); - logbuf.append(loggedStringValue); - logbuf.append(StringUtils.LINE_SEPARATOR); - } - if (curlbuf != null) { - curlbuf.append(" -H '").append(name).append(": ").append(loggedStringValue).append("'"); - } - // add header to lowLevelHttpRequest - if (lowLevelHttpRequest != null) { - lowLevelHttpRequest.addHeader(name, stringValue); - } - // add header to the writer - if (writer != null) { - writer.write(name); - writer.write(": "); - writer.write(stringValue); - writer.write("\r\n"); - } - } - - /** - * Returns the string header value for the given header value as an object. - */ - private static String toStringValue(Object headerValue) { - return headerValue instanceof Enum - ? FieldInfo.of((Enum) headerValue).getName() : headerValue.toString(); - } - - /** - * Serializes headers to an {@link LowLevelHttpRequest}. - * - * @param headers HTTP headers - * @param logbuf log buffer or {@code null} for none - * @param curlbuf log buffer for logging curl requests or {@code null} for none - * @param logger logger or {@code null} for none. Logger must be specified if log buffer is - * specified - * @param lowLevelHttpRequest low level HTTP request where HTTP headers will be serialized to or - * {@code null} for none - */ - static void serializeHeaders(HttpHeaders headers, StringBuilder logbuf, StringBuilder curlbuf, - Logger logger, LowLevelHttpRequest lowLevelHttpRequest) throws IOException { - serializeHeaders(headers, logbuf, curlbuf, logger, lowLevelHttpRequest, null); - } - - /** - * Serializes headers to an {@link Writer} for Multi-part requests. - * - * @param headers HTTP headers - * @param logbuf log buffer or {@code null} for none - * @param logger logger or {@code null} for none. Logger must be specified if log buffer is - * specified - * @param writer Writer where HTTP headers will be serialized to or {@code null} for none - * - * @since 1.9 - */ - public static void serializeHeadersForMultipartRequests( - HttpHeaders headers, StringBuilder logbuf, Logger logger, Writer writer) throws IOException { - serializeHeaders(headers, logbuf, null, logger, null, writer); - } - - static void serializeHeaders(HttpHeaders headers, - StringBuilder logbuf, - StringBuilder curlbuf, - Logger logger, - LowLevelHttpRequest lowLevelHttpRequest, - Writer writer) throws IOException { - HashSet headerNames = new HashSet(); - for (Map.Entry headerEntry : headers.entrySet()) { - String name = headerEntry.getKey(); - Preconditions.checkArgument(headerNames.add(name), - "multiple headers of the same name (headers are case insensitive): %s", name); - Object value = headerEntry.getValue(); - if (value != null) { - // compute the display name from the declared field name to fix capitalization - String displayName = name; - FieldInfo fieldInfo = headers.getClassInfo().getFieldInfo(name); - if (fieldInfo != null) { - displayName = fieldInfo.getName(); - } - Class valueClass = value.getClass(); - if (value instanceof Iterable || valueClass.isArray()) { - for (Object repeatedValue : Types.iterableOf(value)) { - addHeader(logger, - logbuf, - curlbuf, - lowLevelHttpRequest, - displayName, - repeatedValue, - writer); - } - } else { - addHeader(logger, logbuf, curlbuf, lowLevelHttpRequest, displayName, value, writer); - } - } - } - if (writer != null) { - writer.flush(); - } - } - - /** - * Puts all headers of the {@link LowLevelHttpResponse} into this {@link HttpHeaders} object. - * - * @param response Response from which the headers are copied - * @param logger {@link StringBuilder} to which logging output is added or {@code null} to disable - * logging - * @since 1.10 - */ - public final void fromHttpResponse(LowLevelHttpResponse response, StringBuilder logger) - throws IOException { - clear(); - ParseHeaderState state = new ParseHeaderState(this, logger); - int headerCount = response.getHeaderCount(); - for (int i = 0; i < headerCount; i++) { - parseHeader(response.getHeaderName(i), response.getHeaderValue(i), state); - } - state.finish(); - } - - /** LowLevelHttpRequest which will call the .parseHeader() method for every header added. */ - private static class HeaderParsingFakeLevelHttpRequest extends LowLevelHttpRequest { - private final HttpHeaders target; - private final ParseHeaderState state; - - HeaderParsingFakeLevelHttpRequest(HttpHeaders target, ParseHeaderState state) { - this.target = target; - this.state = state; - } - - @Override - public void addHeader(String name, String value) { - target.parseHeader(name, value, state); - } - - @Override - public LowLevelHttpResponse execute() throws IOException { - throw new UnsupportedOperationException(); - } - } - - /** Returns the first header value based on the given internal list value. */ - private T getFirstHeaderValue(List internalValue) { - return internalValue == null ? null : internalValue.get(0); - } - - /** Returns the list value to use for the given parameter passed to the setter method. */ - private List getAsList(T passedValue) { - if (passedValue == null) { - return null; - } - List result = new ArrayList(); - result.add(passedValue); - return result; - } - - /** - * Returns the first header string value for the given header name. - * - * @param name header name (may be any case) - * @return first header string value or {@code null} if not found - * @since 1.13 - */ - public String getFirstHeaderStringValue(String name) { - Object value = get(name.toLowerCase()); - if (value == null) { - return null; - } - Class valueClass = value.getClass(); - if (value instanceof Iterable || valueClass.isArray()) { - for (Object repeatedValue : Types.iterableOf(value)) { - return toStringValue(repeatedValue); - } - } - return toStringValue(value); - } - - /** - * Returns an unmodifiable list of the header string values for the given header name. - * - * @param name header name (may be any case) - * @return header string values or empty if not found - * @since 1.13 - */ - public List getHeaderStringValues(String name) { - Object value = get(name.toLowerCase()); - if (value == null) { - return Collections.emptyList(); - } - Class valueClass = value.getClass(); - if (value instanceof Iterable || valueClass.isArray()) { - List values = new ArrayList(); - for (Object repeatedValue : Types.iterableOf(value)) { - values.add(toStringValue(repeatedValue)); - } - return Collections.unmodifiableList(values); - } - return Collections.singletonList(toStringValue(value)); - } - - /** - * Puts all headers of the {@link HttpHeaders} object into this {@link HttpHeaders} object. - * - * @param headers {@link HttpHeaders} from where the headers are taken - * @since 1.10 - */ - public final void fromHttpHeaders(HttpHeaders headers) { - try { - ParseHeaderState state = new ParseHeaderState(this, null); - serializeHeaders( - headers, null, null, null, new HeaderParsingFakeLevelHttpRequest(this, state)); - state.finish(); - } catch (IOException ex) { - // Should never occur as we are dealing with a FakeLowLevelHttpRequest - throw Throwables.propagate(ex); - } - } - - /** State container for {@link #parseHeader(String, String, ParseHeaderState)}. */ - private static final class ParseHeaderState { - /** Target map where parsed values are stored. */ - final ArrayValueMap arrayValueMap; - - /** Logger if logging is enabled or {@code null} otherwise. */ - final StringBuilder logger; - - /** ClassInfo of the HttpHeaders. */ - final ClassInfo classInfo; - - /** List of types in the header context. */ - final List context; - - /** - * Initializes a new ParseHeaderState. - * - * @param headers HttpHeaders object for which the headers are being parsed - * @param logger Logger if logging is enabled or {@code null} - */ - public ParseHeaderState(HttpHeaders headers, StringBuilder logger) { - Class clazz = headers.getClass(); - this.context = Arrays.asList(clazz); - this.classInfo = ClassInfo.of(clazz, true); - this.logger = logger; - this.arrayValueMap = new ArrayValueMap(headers); - } - - /** - * Finishes the parsing-process by setting all array-values. - */ - void finish() { - arrayValueMap.setValues(); - } - } - - /** Parses the specified case-insensitive header pair into this HttpHeaders instance. */ - void parseHeader(String headerName, String headerValue, ParseHeaderState state) { - List context = state.context; - ClassInfo classInfo = state.classInfo; - ArrayValueMap arrayValueMap = state.arrayValueMap; - StringBuilder logger = state.logger; - - if (logger != null) { - logger.append(headerName + ": " + headerValue).append(StringUtils.LINE_SEPARATOR); - } - // use field information if available - FieldInfo fieldInfo = classInfo.getFieldInfo(headerName); - if (fieldInfo != null) { - Type type = Data.resolveWildcardTypeOrTypeVariable(context, fieldInfo.getGenericType()); - // type is now class, parameterized type, or generic array type - if (Types.isArray(type)) { - // array that can handle repeating values - Class rawArrayComponentType = - Types.getRawArrayComponentType(context, Types.getArrayComponentType(type)); - arrayValueMap.put(fieldInfo.getField(), rawArrayComponentType, - parseValue(rawArrayComponentType, context, headerValue)); - } else if (Types.isAssignableToOrFrom( - Types.getRawArrayComponentType(context, type), Iterable.class)) { - // iterable that can handle repeating values - @SuppressWarnings("unchecked") - Collection collection = (Collection) fieldInfo.getValue(this); - if (collection == null) { - collection = Data.newCollectionInstance(type); - fieldInfo.setValue(this, collection); - } - Type subFieldType = type == Object.class ? null : Types.getIterableParameter(type); - collection.add(parseValue(subFieldType, context, headerValue)); - } else { - // parse value based on field type - fieldInfo.setValue(this, parseValue(type, context, headerValue)); - } - } else { - // store header values in an array list - @SuppressWarnings("unchecked") - ArrayList listValue = (ArrayList) this.get(headerName); - if (listValue == null) { - listValue = new ArrayList(); - this.set(headerName, listValue); - } - listValue.add(headerValue); - } - } - - private static Object parseValue(Type valueType, List context, String value) { - Type resolved = Data.resolveWildcardTypeOrTypeVariable(context, valueType); - return Data.parsePrimitiveValue(resolved, value); - } - - // TODO(yanivi): override equals and hashCode -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/HttpIOExceptionHandler.java b/src/autosaveworld/zlibs/com/google/api/client/http/HttpIOExceptionHandler.java deleted file mode 100644 index 2a89fd79..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/HttpIOExceptionHandler.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.IOException; - -import autosaveworld.zlibs.com.google.api.client.util.BackOff; -import autosaveworld.zlibs.com.google.api.client.util.Beta; - -/** - * {@link Beta}
- * Handles an {@link IOException} in an HTTP request. - * - *

- * For example, this might be used to handle an {@link IOException} with {@link BackOff} policy. - *

- * - *
-  public static class HttpBackOffIOExceptionHandler implements HttpIOExceptionHandler {
-    BackOff backOff;
-    Sleeper sleeper;
-    public boolean handle(HttpRequest request, boolean supportsRetry) throws IOException {
-      if (!supportsRetry) {
-        return false;
-      }
-      try {
-        return BackOffUtils.next(sleeper, backOff);
-      } catch (InterruptedException exception) {
-        return false;
-      }
-    }
-  }
- * 
- * - * @author Eyal Peled - * @since 1.15 - */ -@Beta -public interface HttpIOExceptionHandler { - - /** - * Invoked when an {@link IOException} is thrown during an HTTP request. - * - *

- * There is a simple rule that one must follow: If you modify the request object or modify its - * execute interceptors in a way that should resolve the error, you must return {@code true} to - * issue a retry. - *

- * - * @param request request object that can be read from for context or modified before retry - * @param supportsRetry whether there will actually be a retry if this handler return {@code true} - * . Some handlers may want to have an effect only when there will actually be a retry - * after they handle their event (e.g. a handler that implements backoff policy). - * @return whether or not this handler has made a change that will require the request to be - * re-sent. - */ - boolean handleIOException(HttpRequest request, boolean supportsRetry) throws IOException; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/HttpMediaType.java b/src/autosaveworld/zlibs/com/google/api/client/http/HttpMediaType.java deleted file mode 100644 index 198ca31b..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/HttpMediaType.java +++ /dev/null @@ -1,339 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.nio.charset.Charset; -import java.util.Collections; -import java.util.Map; -import java.util.Map.Entry; -import java.util.SortedMap; -import java.util.TreeMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * HTTP Media-type as specified in the HTTP RFC ( - * {@link "http://tools.ietf.org/html/rfc2616#section-3.7"}). - * - *

- * Implementation is not thread-safe. - *

- * - * @author Matthias Linder (mlinder) - * @since 1.10 - */ -public final class HttpMediaType { - - /** Matches a valid media type or '*' (examples: "text" or "*"). */ - private static final Pattern TYPE_REGEX; - - /** Matches a valid token which might be used as a type, key parameter or key value. */ - private static final Pattern TOKEN_REGEX; - - /** The pattern matching the full HTTP media type string. */ - private static final Pattern FULL_MEDIA_TYPE_REGEX; - - /** The pattern matching a single parameter (key, value) at a time. */ - private static final Pattern PARAMETER_REGEX; - - /** The main type of the media type, for example {@code "text"}. */ - private String type = "application"; - - /** The sub type of the media type, for example {@code "plain"}. */ - private String subType = "octet-stream"; - - /** Additional parameters to the media type, for example {@code "charset=utf-8"}. */ - private final SortedMap parameters = new TreeMap(); - - /** The last build result or {@code null}. */ - private String cachedBuildResult; - - /** Initialize all Patterns used for parsing. */ - static { - // TYPE_REGEX: Very restrictive regex accepting valid types and '*' for e.g. "text/*". - // http://tools.ietf.org/html/rfc4288#section-4.2 - TYPE_REGEX = Pattern.compile("[\\w!#$&.+\\-\\^_]+|[*]"); - - // TOKEN_REGEX: Restrictive (but less than TYPE_REGEX) regex accepting valid tokens. - // http://tools.ietf.org/html/rfc2045#section-5.1 - TOKEN_REGEX = - Pattern.compile("[\\p{ASCII}&&[^\\p{Cntrl} ;/=\\[\\]\\(\\)\\<\\>\\@\\,\\:\\\"\\?\\=]]+"); - - // FULL_MEDIA_TYPE_REGEX: Unrestrictive regex matching the general structure of the media type. - // Used to split a Content-Type string into different parts. Unrestrictive so that invalid char - // detection can be done on a per-type/parameter basis. - String typeOrKey = "[^\\s/=;\"]+"; // only disallow separators - String wholeParameterSection = ";.*"; - FULL_MEDIA_TYPE_REGEX = Pattern.compile( - "\\s*(" + typeOrKey + ")/(" + typeOrKey + ")" + // main type (G1)/sub type (G2) - "\\s*(" + wholeParameterSection + ")?", Pattern.DOTALL); // parameters (G3) or null - - // PARAMETER_REGEX: Semi-restrictive regex matching each parameter in the parameter section. - // We also allow multipart values here (http://www.w3.org/Protocols/rfc1341/7_2_Multipart.html) - // although those do not fully conform to the HTTP spec. - String quotedParameterValue = "\"([^\"]*)\""; - String unquotedParameterValue = "[^\\s;\"]*"; - String parameterValue = quotedParameterValue + "|" + unquotedParameterValue; - PARAMETER_REGEX = Pattern.compile("\\s*;\\s*(" + typeOrKey + ")" + // parameter key (G1) - "=(" + parameterValue + ")"); // G2 (if quoted) and else G3 - } - - /** - * Initializes the {@link HttpMediaType} by setting the specified media type. - * @param type main media type, for example {@code "text"} - * @param subType sub media type, for example {@code "plain"} - */ - public HttpMediaType(String type, String subType) { - setType(type); - setSubType(subType); - } - - /** - * Creates a {@link HttpMediaType} by parsing the specified media type string. - * - * @param mediaType full media type string, for example {@code "text/plain; charset=utf-8"} - */ - public HttpMediaType(String mediaType) { - fromString(mediaType); - } - - /** - * Sets the (main) media type, for example {@code "text"}. - * - * @param type main/major media type - */ - public HttpMediaType setType(String type) { - Preconditions.checkArgument( - TYPE_REGEX.matcher(type).matches(), "Type contains reserved characters"); - this.type = type; - cachedBuildResult = null; - return this; - } - - /** - * Returns the main media type, for example {@code "text"}, or {@code null} for '*'. - */ - public String getType() { - return type; - } - - /** - * Sets the sub media type, for example {@code "plain"} when using {@code "text"}. - * - * @param subType sub media type - */ - public HttpMediaType setSubType(String subType) { - Preconditions.checkArgument( - TYPE_REGEX.matcher(subType).matches(), "Subtype contains reserved characters"); - this.subType = subType; - cachedBuildResult = null; - return this; - } - - /** - * Returns the sub media type, for example {@code "plain"} when using {@code "text"}. - */ - public String getSubType() { - return subType; - } - - /** - * Sets the full media type by parsing a full content-type string, for example - * {@code "text/plain; foo=bar"}. - * - *

- * This method will not clear existing parameters. Use {@link #clearParameters()} if this behavior - * is required. - *

- * - * @param combinedType full media type in the {@code "maintype/subtype; key=value"} format. - */ - private HttpMediaType fromString(String combinedType) { - Matcher matcher = FULL_MEDIA_TYPE_REGEX.matcher(combinedType); - Preconditions.checkArgument( - matcher.matches(), "Type must be in the 'maintype/subtype; parameter=value' format"); - - setType(matcher.group(1)); - setSubType(matcher.group(2)); - String params = matcher.group(3); - if (params != null) { - matcher = PARAMETER_REGEX.matcher(params); - while (matcher.find()) { - // 1=key, 2=valueWithQuotes, 3=valueWithoutQuotes - String key = matcher.group(1); - String value = matcher.group(3); - if (value == null) { - value = matcher.group(2); - } - setParameter(key, value); - } - } - return this; - } - - /** - * Sets the media parameter to the specified value. - * - * @param name case-insensitive name of the parameter - * @param value value of the parameter or {@code null} to remove - */ - public HttpMediaType setParameter(String name, String value) { - if (value == null) { - removeParameter(name); - return this; - } - - Preconditions.checkArgument( - TOKEN_REGEX.matcher(name).matches(), "Name contains reserved characters"); - cachedBuildResult = null; - parameters.put(name.toLowerCase(), value); - return this; - } - - /** - * Returns the value of the specified parameter or {@code null} if not found. - * - * @param name name of the parameter - */ - public String getParameter(String name) { - return parameters.get(name.toLowerCase()); - } - - /** - * Removes the specified media parameter. - * - * @param name parameter to remove - */ - public HttpMediaType removeParameter(String name) { - cachedBuildResult = null; - parameters.remove(name.toLowerCase()); - return this; - } - - /** - * Removes all set parameters from this media type. - */ - public void clearParameters() { - cachedBuildResult = null; - parameters.clear(); - } - - /** - * Returns an unmodifiable map of all specified parameters. Parameter names will be stored in - * lower-case in this map. - */ - public Map getParameters() { - return Collections.unmodifiableMap(parameters); - } - - /** - * Returns whether the given value matches the regular expression for "token" as specified in RFC 2616 section 2.2. - */ - static boolean matchesToken(String value) { - return TOKEN_REGEX.matcher(value).matches(); - } - - private static String quoteString(String unquotedString) { - String escapedString = unquotedString.replace("\\", "\\\\"); // change \ to \\ - escapedString = escapedString.replace("\"", "\\\""); // change " to \" - return "\"" + escapedString + "\""; - } - - /** - * Builds the full media type string which can be passed in the Content-Type header. - */ - public String build() { - if (cachedBuildResult != null) { - return cachedBuildResult; - } - - StringBuilder str = new StringBuilder(); - str.append(type); - str.append('/'); - str.append(subType); - if (parameters != null) { - for (Entry entry : parameters.entrySet()) { - String value = entry.getValue(); - str.append("; "); - str.append(entry.getKey()); - str.append("="); - str.append(!matchesToken(value) ? quoteString(value) : value); - } - } - cachedBuildResult = str.toString(); - return cachedBuildResult; - } - - @Override - public String toString() { - return build(); - } - - /** - * Returns {@code true} if the specified media type has both the same type and subtype, or - * {@code false} if they don't match or the media type is {@code null}. - */ - public boolean equalsIgnoreParameters(HttpMediaType mediaType) { - return mediaType != null && getType().equalsIgnoreCase(mediaType.getType()) - && getSubType().equalsIgnoreCase(mediaType.getSubType()); - } - - /** - * Returns {@code true} if the two specified media types have the same type and subtype, or if - * both types are {@code null}. - */ - public static boolean equalsIgnoreParameters(String mediaTypeA, String mediaTypeB) { - // TODO(mlinder): Make the HttpMediaType.isSameType implementation more performant. - return (mediaTypeA == null && mediaTypeB == null) || mediaTypeA != null && mediaTypeB != null - && new HttpMediaType(mediaTypeA).equalsIgnoreParameters(new HttpMediaType(mediaTypeB)); - } - - /** - * Sets the charset parameter of the media type. - * - * @param charset new value for the charset parameter or {@code null} to remove - */ - public HttpMediaType setCharsetParameter(Charset charset) { - setParameter("charset", charset == null ? null : charset.name()); - return this; - } - - /** - * Returns the specified charset or {@code null} if unset. - */ - public Charset getCharsetParameter() { - String value = getParameter("charset"); - return value == null ? null : Charset.forName(value); - } - - @Override - public int hashCode() { - return build().hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof HttpMediaType)) { - return false; - } - - HttpMediaType otherType = (HttpMediaType) obj; - - return equalsIgnoreParameters(otherType) && parameters.equals(otherType.parameters); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/HttpMethods.java b/src/autosaveworld/zlibs/com/google/api/client/http/HttpMethods.java deleted file mode 100644 index 7b88f685..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/HttpMethods.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -/** - * HTTP request method constants specified in RFC 2616 Section 5.1.1. - * - * @since 1.12 - * @author Yaniv Inbar - */ -public final class HttpMethods { - - /** HTTP CONNECT method. */ - public static final String CONNECT = "CONNECT"; - - /** HTTP DELETE method. */ - public static final String DELETE = "DELETE"; - - /** HTTP GET method. */ - public static final String GET = "GET"; - - /** HTTP HEAD method. */ - public static final String HEAD = "HEAD"; - - /** HTTP OPTIONS method. */ - public static final String OPTIONS = "OPTIONS"; - - /** - * HTTP PATCH method. - * - * @since 1.14 - */ - public static final String PATCH = "PATCH"; - - /** HTTP POST method. */ - public static final String POST = "POST"; - - /** HTTP PUT method. */ - public static final String PUT = "PUT"; - - /** HTTP TRACE method. */ - public static final String TRACE = "TRACE"; - - private HttpMethods() { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/HttpRequest.java b/src/autosaveworld/zlibs/com/google/api/client/http/HttpRequest.java deleted file mode 100644 index 8307948d..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/HttpRequest.java +++ /dev/null @@ -1,1172 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.IOException; -import java.io.InputStream; -import java.util.concurrent.Callable; -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.FutureTask; -import java.util.logging.Level; -import java.util.logging.Logger; - -import autosaveworld.zlibs.com.google.api.client.util.Beta; -import autosaveworld.zlibs.com.google.api.client.util.IOUtils; -import autosaveworld.zlibs.com.google.api.client.util.LoggingStreamingContent; -import autosaveworld.zlibs.com.google.api.client.util.ObjectParser; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.Sleeper; -import autosaveworld.zlibs.com.google.api.client.util.StreamingContent; -import autosaveworld.zlibs.com.google.api.client.util.StringUtils; - -/** - * HTTP request. - * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.0 - * @author Yaniv Inbar - */ -public final class HttpRequest { - - /** - * Current version of the Google API Client Library for Java. - * - * @since 1.8 - */ - public static final String VERSION = "1.22.0"; - - /** - * User agent suffix for all requests. - * - *

- * Includes a {@code "(gzip)"} suffix in case the server -- as Google's servers may do -- checks - * the {@code User-Agent} header to try to detect if the client accepts gzip-encoded responses. - *

- * - * @since 1.4 - */ - public static final String USER_AGENT_SUFFIX = "Google-HTTP-Java-Client/" + VERSION + " (gzip)"; - - /** - * The default number of retries that will be allowed to execute before the request will be - * terminated. - * - * @see #getNumberOfRetries - * @since 1.22 - */ - public static final int DEFAULT_NUMBER_OF_RETRIES = 10; - - /** - * HTTP request execute interceptor to intercept the start of {@link #execute()} (before executing - * the HTTP request) or {@code null} for none. - */ - private HttpExecuteInterceptor executeInterceptor; - - /** HTTP request headers. */ - private HttpHeaders headers = new HttpHeaders(); - - /** - * HTTP response headers. - * - *

- * For example, this can be used if you want to use a subclass of {@link HttpHeaders} called - * MyHeaders to process the response: - *

- * - *
-  static String executeAndGetValueOfSomeCustomHeader(HttpRequest request) {
-    MyHeaders responseHeaders = new MyHeaders();
-    request.responseHeaders = responseHeaders;
-    HttpResponse response = request.execute();
-    return responseHeaders.someCustomHeader;
-  }
-   * 
- */ - private HttpHeaders responseHeaders = new HttpHeaders(); - - /** - * The number of retries that will be allowed to execute before the request will be terminated or - * {@code 0} to not retry requests. Retries occur as a result of either - * {@link HttpUnsuccessfulResponseHandler} or {@link HttpIOExceptionHandler} which handles - * abnormal HTTP response or the I/O exception. - */ - private int numRetries = DEFAULT_NUMBER_OF_RETRIES; - - /** - * Determines the limit to the content size that will be logged during {@link #execute()}. - * - *

- * Content will only be logged if {@link #isLoggingEnabled} is {@code true}. - *

- * - *

- * If the content size is greater than this limit then it will not be logged. - *

- * - *

- * Can be set to {@code 0} to disable content logging. This is useful for example if content has - * sensitive data such as authentication information. - *

- * - *

- * Defaults to 16KB. - *

- */ - private int contentLoggingLimit = 0x4000; - - /** Determines whether logging should be enabled for this request. Defaults to {@code true}. */ - private boolean loggingEnabled = true; - - /** Determines whether logging in form of curl commands should be enabled for this request. */ - private boolean curlLoggingEnabled = true; - - /** HTTP request content or {@code null} for none. */ - private HttpContent content; - - /** HTTP transport. */ - private final HttpTransport transport; - - /** HTTP request method or {@code null} for none. */ - private String requestMethod; - - /** HTTP request URL. */ - private GenericUrl url; - - /** Timeout in milliseconds to establish a connection or {@code 0} for an infinite timeout. */ - private int connectTimeout = 20 * 1000; - - /** - * Timeout in milliseconds to read data from an established connection or {@code 0} for an - * infinite timeout. - */ - private int readTimeout = 20 * 1000; - - /** HTTP unsuccessful (non-2XX) response handler or {@code null} for none. */ - private HttpUnsuccessfulResponseHandler unsuccessfulResponseHandler; - - /** HTTP I/O exception handler or {@code null} for none. */ - @Beta - private HttpIOExceptionHandler ioExceptionHandler; - - /** HTTP response interceptor or {@code null} for none. */ - private HttpResponseInterceptor responseInterceptor; - - /** Parser used to parse responses. */ - private ObjectParser objectParser; - - /** HTTP content encoding or {@code null} for none. */ - private HttpEncoding encoding; - - /** - * The {@link BackOffPolicy} to use between retry attempts or {@code null} for none. - */ - @Deprecated - @Beta - private BackOffPolicy backOffPolicy; - - /** Whether to automatically follow redirects ({@code true} by default). */ - private boolean followRedirects = true; - - /** - * Whether to throw an exception at the end of {@link #execute()} on an HTTP error code (non-2XX) - * after all retries and response handlers have been exhausted ({@code true} by default). - */ - private boolean throwExceptionOnExecuteError = true; - - /** - * Whether to retry the request if an {@link IOException} is encountered in - * {@link LowLevelHttpRequest#execute()}. - */ - @Deprecated - @Beta - private boolean retryOnExecuteIOException = false; - - /** - * Whether to not add the suffix {@link #USER_AGENT_SUFFIX} to the User-Agent header. - * - *

- * It is {@code false} by default. - *

- */ - private boolean suppressUserAgentSuffix; - - /** Sleeper. */ - private Sleeper sleeper = Sleeper.DEFAULT; - - /** - * @param transport HTTP transport - * @param requestMethod HTTP request method or {@code null} for none - */ - HttpRequest(HttpTransport transport, String requestMethod) { - this.transport = transport; - setRequestMethod(requestMethod); - } - - /** - * Returns the HTTP transport. - * - * @since 1.5 - */ - public HttpTransport getTransport() { - return transport; - } - - /** - * Returns the HTTP request method or {@code null} for none. - * - * @since 1.12 - */ - public String getRequestMethod() { - return requestMethod; - } - - /** - * Sets the HTTP request method or {@code null} for none. - * - * @since 1.12 - */ - public HttpRequest setRequestMethod(String requestMethod) { - Preconditions.checkArgument(requestMethod == null || HttpMediaType.matchesToken(requestMethod)); - this.requestMethod = requestMethod; - return this; - } - - /** - * Returns the HTTP request URL. - * - * @since 1.5 - */ - public GenericUrl getUrl() { - return url; - } - - /** - * Sets the HTTP request URL. - * - * @since 1.5 - */ - public HttpRequest setUrl(GenericUrl url) { - this.url = Preconditions.checkNotNull(url); - return this; - } - - /** - * Returns the HTTP request content or {@code null} for none. - * - * @since 1.5 - */ - public HttpContent getContent() { - return content; - } - - /** - * Sets the HTTP request content or {@code null} for none. - * - * @since 1.5 - */ - public HttpRequest setContent(HttpContent content) { - this.content = content; - return this; - } - - /** - * Returns the HTTP content encoding or {@code null} for none. - * - * @since 1.14 - */ - public HttpEncoding getEncoding() { - return encoding; - } - - /** - * Sets the HTTP content encoding or {@code null} for none. - * - * @since 1.14 - */ - public HttpRequest setEncoding(HttpEncoding encoding) { - this.encoding = encoding; - return this; - } - - /** - * {@link Beta}
- * Returns the {@link BackOffPolicy} to use between retry attempts or {@code null} for none. - * - * @since 1.7 - * @deprecated (scheduled to be removed in 1.18). - * {@link #setUnsuccessfulResponseHandler(HttpUnsuccessfulResponseHandler)} with a new - * {@link HttpBackOffUnsuccessfulResponseHandler} instead. - */ - @Deprecated - @Beta - public BackOffPolicy getBackOffPolicy() { - return backOffPolicy; - } - - /** - * {@link Beta}
- * Sets the {@link BackOffPolicy} to use between retry attempts or {@code null} for none. - * - * @since 1.7 - * @deprecated (scheduled to be removed in 1.18). Use - * {@link #setUnsuccessfulResponseHandler(HttpUnsuccessfulResponseHandler)} with a new - * {@link HttpBackOffUnsuccessfulResponseHandler} instead. - */ - @Deprecated - @Beta - public HttpRequest setBackOffPolicy(BackOffPolicy backOffPolicy) { - this.backOffPolicy = backOffPolicy; - return this; - } - - /** - * Returns the limit to the content size that will be logged during {@link #execute()}. - * - *

- * If the content size is greater than this limit then it will not be logged. - *

- * - *

- * Content will only be logged if {@link #isLoggingEnabled} is {@code true}. - *

- * - *

- * Can be set to {@code 0} to disable content logging. This is useful for example if content has - * sensitive data such as authentication information. - *

- * - *

- * Defaults to 16KB. - *

- * - * @since 1.7 - */ - public int getContentLoggingLimit() { - return contentLoggingLimit; - } - - /** - * Set the limit to the content size that will be logged during {@link #execute()}. - * - *

- * If the content size is greater than this limit then it will not be logged. - *

- * - *

- * Content will only be logged if {@link #isLoggingEnabled} is {@code true}. - *

- * - *

- * Can be set to {@code 0} to disable content logging. This is useful for example if content has - * sensitive data such as authentication information. - *

- * - *

- * Defaults to 16KB. - *

- * - * @since 1.7 - */ - public HttpRequest setContentLoggingLimit(int contentLoggingLimit) { - Preconditions.checkArgument( - contentLoggingLimit >= 0, "The content logging limit must be non-negative."); - this.contentLoggingLimit = contentLoggingLimit; - return this; - } - - /** - * Returns whether logging should be enabled for this request. - * - *

- * Defaults to {@code true}. - *

- * - * @since 1.9 - */ - public boolean isLoggingEnabled() { - return loggingEnabled; - } - - /** - * Sets whether logging should be enabled for this request. - * - *

- * Defaults to {@code true}. - *

- * - * @since 1.9 - */ - public HttpRequest setLoggingEnabled(boolean loggingEnabled) { - this.loggingEnabled = loggingEnabled; - return this; - } - - /** - * Returns whether logging in form of curl commands is enabled for this request. - * - * @since 1.11 - */ - public boolean isCurlLoggingEnabled() { - return curlLoggingEnabled; - } - - /** - * Sets whether logging in form of curl commands should be enabled for this request. - * - *

- * Defaults to {@code true}. - *

- * - * @since 1.11 - */ - public HttpRequest setCurlLoggingEnabled(boolean curlLoggingEnabled) { - this.curlLoggingEnabled = curlLoggingEnabled; - return this; - } - - /** - * Returns the timeout in milliseconds to establish a connection or {@code 0} for an infinite - * timeout. - * - * @since 1.5 - */ - public int getConnectTimeout() { - return connectTimeout; - } - - /** - * Sets the timeout in milliseconds to establish a connection or {@code 0} for an infinite - * timeout. - * - *

- * By default it is 20000 (20 seconds). - *

- * - * @since 1.5 - */ - public HttpRequest setConnectTimeout(int connectTimeout) { - Preconditions.checkArgument(connectTimeout >= 0); - this.connectTimeout = connectTimeout; - return this; - } - - /** - * Returns the timeout in milliseconds to read data from an established connection or {@code 0} - * for an infinite timeout. - * - *

- * By default it is 20000 (20 seconds). - *

- * - * @since 1.5 - */ - public int getReadTimeout() { - return readTimeout; - } - - /** - * Sets the timeout in milliseconds to read data from an established connection or {@code 0} for - * an infinite timeout. - * - * @since 1.5 - */ - public HttpRequest setReadTimeout(int readTimeout) { - Preconditions.checkArgument(readTimeout >= 0); - this.readTimeout = readTimeout; - return this; - } - - /** - * Returns the HTTP request headers. - * - * @since 1.5 - */ - public HttpHeaders getHeaders() { - return headers; - } - - /** - * Sets the HTTP request headers. - * - *

- * By default, this is a new unmodified instance of {@link HttpHeaders}. - *

- * - * @since 1.5 - */ - public HttpRequest setHeaders(HttpHeaders headers) { - this.headers = Preconditions.checkNotNull(headers); - return this; - } - - /** - * Returns the HTTP response headers. - * - * @since 1.5 - */ - public HttpHeaders getResponseHeaders() { - return responseHeaders; - } - - /** - * Sets the HTTP response headers. - * - *

- * By default, this is a new unmodified instance of {@link HttpHeaders}. - *

- * - *

- * For example, this can be used if you want to use a subclass of {@link HttpHeaders} called - * MyHeaders to process the response: - *

- * - *
-  static String executeAndGetValueOfSomeCustomHeader(HttpRequest request) {
-    MyHeaders responseHeaders = new MyHeaders();
-    request.responseHeaders = responseHeaders;
-    HttpResponse response = request.execute();
-    return responseHeaders.someCustomHeader;
-  }
-   * 
- * - * @since 1.5 - */ - public HttpRequest setResponseHeaders(HttpHeaders responseHeaders) { - this.responseHeaders = Preconditions.checkNotNull(responseHeaders); - return this; - } - - /** - * Returns the HTTP request execute interceptor to intercept the start of {@link #execute()} - * (before executing the HTTP request) or {@code null} for none. - * - * @since 1.5 - */ - public HttpExecuteInterceptor getInterceptor() { - return executeInterceptor; - } - - /** - * Sets the HTTP request execute interceptor to intercept the start of {@link #execute()} (before - * executing the HTTP request) or {@code null} for none. - * - * @since 1.5 - */ - public HttpRequest setInterceptor(HttpExecuteInterceptor interceptor) { - this.executeInterceptor = interceptor; - return this; - } - - /** - * Returns the HTTP unsuccessful (non-2XX) response handler or {@code null} for none. - * - * @since 1.5 - */ - public HttpUnsuccessfulResponseHandler getUnsuccessfulResponseHandler() { - return unsuccessfulResponseHandler; - } - - /** - * Sets the HTTP unsuccessful (non-2XX) response handler or {@code null} for none. - * - * @since 1.5 - */ - public HttpRequest setUnsuccessfulResponseHandler( - HttpUnsuccessfulResponseHandler unsuccessfulResponseHandler) { - this.unsuccessfulResponseHandler = unsuccessfulResponseHandler; - return this; - } - - /** - * {@link Beta}
- * Returns the HTTP I/O exception handler or {@code null} for none. - * - * @since 1.15 - */ - @Beta - public HttpIOExceptionHandler getIOExceptionHandler() { - return ioExceptionHandler; - } - - /** - * {@link Beta}
- * Sets the HTTP I/O exception handler or {@code null} for none. - * - * @since 1.15 - */ - @Beta - public HttpRequest setIOExceptionHandler(HttpIOExceptionHandler ioExceptionHandler) { - this.ioExceptionHandler = ioExceptionHandler; - return this; - } - - /** - * Returns the HTTP response interceptor or {@code null} for none. - * - * @since 1.13 - */ - public HttpResponseInterceptor getResponseInterceptor() { - return responseInterceptor; - } - - /** - * Sets the HTTP response interceptor or {@code null} for none. - * - * @since 1.13 - */ - public HttpRequest setResponseInterceptor(HttpResponseInterceptor responseInterceptor) { - this.responseInterceptor = responseInterceptor; - return this; - } - - /** - * Returns the number of retries that will be allowed to execute before the request will be - * terminated or {@code 0} to not retry requests. Retries occur as a result of either - * {@link HttpUnsuccessfulResponseHandler} or {@link HttpIOExceptionHandler} which handles - * abnormal HTTP response or the I/O exception. - * - * - * @since 1.5 - */ - public int getNumberOfRetries() { - return numRetries; - } - - /** - * Sets the number of retries that will be allowed to execute before the request will be - * terminated or {@code 0} to not retry requests. Retries occur as a result of either - * {@link HttpUnsuccessfulResponseHandler} or {@link HttpIOExceptionHandler} which handles - * abnormal HTTP response or the I/O exception. - * - *

- * The default value is {@link #DEFAULT_NUMBER_OF_RETRIES}. - *

- * - * @since 1.5 - */ - public HttpRequest setNumberOfRetries(int numRetries) { - Preconditions.checkArgument(numRetries >= 0); - this.numRetries = numRetries; - return this; - } - - /** - * Sets the {@link ObjectParser} used to parse the response to this request or {@code null} for - * none. - * - *

- * This parser will be preferred over any registered HttpParser. - *

- * - * @since 1.10 - */ - public HttpRequest setParser(ObjectParser parser) { - this.objectParser = parser; - return this; - } - - /** - * Returns the {@link ObjectParser} used to parse the response or {@code null} for none. - * - * @since 1.10 - */ - public final ObjectParser getParser() { - return objectParser; - } - - /** - * Returns whether to follow redirects automatically. - * - * @since 1.6 - */ - public boolean getFollowRedirects() { - return followRedirects; - } - - /** - * Sets whether to follow redirects automatically. - * - *

- * The default value is {@code true}. - *

- * - * @since 1.6 - */ - public HttpRequest setFollowRedirects(boolean followRedirects) { - this.followRedirects = followRedirects; - return this; - } - - /** - * Returns whether to throw an exception at the end of {@link #execute()} on an HTTP error code - * (non-2XX) after all retries and response handlers have been exhausted. - * - * @since 1.7 - */ - public boolean getThrowExceptionOnExecuteError() { - return throwExceptionOnExecuteError; - } - - /** - * Sets whether to throw an exception at the end of {@link #execute()} on a HTTP error code - * (non-2XX) after all retries and response handlers have been exhausted. - * - *

- * The default value is {@code true}. - *

- * - * @since 1.7 - */ - public HttpRequest setThrowExceptionOnExecuteError(boolean throwExceptionOnExecuteError) { - this.throwExceptionOnExecuteError = throwExceptionOnExecuteError; - return this; - } - - /** - * {@link Beta}
- * Returns whether to retry the request if an {@link IOException} is encountered in - * {@link LowLevelHttpRequest#execute()}. - * - * @since 1.9 - * @deprecated (scheduled to be removed in 1.18) Use - * {@link #setIOExceptionHandler(HttpIOExceptionHandler)} instead. - */ - @Deprecated - @Beta - public boolean getRetryOnExecuteIOException() { - return retryOnExecuteIOException; - } - - /** - * {@link Beta}
- * Sets whether to retry the request if an {@link IOException} is encountered in - * {@link LowLevelHttpRequest#execute()}. - * - *

- * The default value is {@code false}. - *

- * - * @since 1.9 - * @deprecated (scheduled to be removed in 1.18) Use - * {@link #setIOExceptionHandler(HttpIOExceptionHandler)} instead. - */ - @Deprecated - @Beta - public HttpRequest setRetryOnExecuteIOException(boolean retryOnExecuteIOException) { - this.retryOnExecuteIOException = retryOnExecuteIOException; - return this; - } - - /** - * Returns whether to not add the suffix {@link #USER_AGENT_SUFFIX} to the User-Agent header. - * - * @since 1.11 - */ - public boolean getSuppressUserAgentSuffix() { - return suppressUserAgentSuffix; - } - - /** - * Sets whether to not add the suffix {@link #USER_AGENT_SUFFIX} to the User-Agent header. - * - *

- * The default value is {@code false}. - *

- * - * @since 1.11 - */ - public HttpRequest setSuppressUserAgentSuffix(boolean suppressUserAgentSuffix) { - this.suppressUserAgentSuffix = suppressUserAgentSuffix; - return this; - } - - /** - * Execute the HTTP request and returns the HTTP response. - * - *

- * Note that regardless of the returned status code, the HTTP response content has not been parsed - * yet, and must be parsed by the calling code. - *

- * - *

- * Note that when calling to this method twice or more, the state of this HTTP request object - * isn't cleared, so the request will continue where it was left. For example, the state of the - * {@link HttpUnsuccessfulResponseHandler} attached to this HTTP request will remain the same as - * it was left after last execute. - *

- * - *

- * Almost all details of the request and response are logged if {@link Level#CONFIG} is loggable. - * The only exception is the value of the {@code Authorization} header which is only logged if - * {@link Level#ALL} is loggable. - *

- * - *

- * Callers should call {@link HttpResponse#disconnect} when the returned HTTP response object is - * no longer needed. However, {@link HttpResponse#disconnect} does not have to be called if the - * response stream is properly closed. Example usage: - *

- * - *
-     HttpResponse response = request.execute();
-     try {
-       // process the HTTP response object
-     } finally {
-       response.disconnect();
-     }
-   * 
- * - * @return HTTP response for an HTTP success response (or HTTP error response if - * {@link #getThrowExceptionOnExecuteError()} is {@code false}) - * @throws HttpResponseException for an HTTP error response (only if - * {@link #getThrowExceptionOnExecuteError()} is {@code true}) - * @see HttpResponse#isSuccessStatusCode() - */ - @SuppressWarnings("deprecation") - public HttpResponse execute() throws IOException { - boolean retryRequest = false; - Preconditions.checkArgument(numRetries >= 0); - int retriesRemaining = numRetries; - if (backOffPolicy != null) { - // Reset the BackOffPolicy at the start of each execute. - backOffPolicy.reset(); - } - HttpResponse response = null; - IOException executeException; - - Preconditions.checkNotNull(requestMethod); - Preconditions.checkNotNull(url); - - do { - // Cleanup any unneeded response from a previous iteration - if (response != null) { - response.ignore(); - } - - response = null; - executeException = null; - - // run the interceptor - if (executeInterceptor != null) { - executeInterceptor.intercept(this); - } - // build low-level HTTP request - String urlString = url.build(); - LowLevelHttpRequest lowLevelHttpRequest = transport.buildRequest(requestMethod, urlString); - Logger logger = HttpTransport.LOGGER; - boolean loggable = loggingEnabled && logger.isLoggable(Level.CONFIG); - StringBuilder logbuf = null; - StringBuilder curlbuf = null; - // log method and URL - if (loggable) { - logbuf = new StringBuilder(); - logbuf.append("-------------- REQUEST --------------").append(StringUtils.LINE_SEPARATOR); - logbuf.append(requestMethod) - .append(' ').append(urlString).append(StringUtils.LINE_SEPARATOR); - - // setup curl logging - if (curlLoggingEnabled) { - curlbuf = new StringBuilder("curl -v --compressed"); - if (!requestMethod.equals(HttpMethods.GET)) { - curlbuf.append(" -X ").append(requestMethod); - } - } - } - // add to user agent - String originalUserAgent = headers.getUserAgent(); - if (!suppressUserAgentSuffix) { - if (originalUserAgent == null) { - headers.setUserAgent(USER_AGENT_SUFFIX); - } else { - headers.setUserAgent(originalUserAgent + " " + USER_AGENT_SUFFIX); - } - } - // headers - HttpHeaders.serializeHeaders(headers, logbuf, curlbuf, logger, lowLevelHttpRequest); - if (!suppressUserAgentSuffix) { - // set the original user agent back so that retries do not keep appending to it - headers.setUserAgent(originalUserAgent); - } - - // content - StreamingContent streamingContent = content; - final boolean contentRetrySupported = streamingContent == null || content.retrySupported(); - if (streamingContent != null) { - final String contentEncoding; - final long contentLength; - final String contentType = content.getType(); - // log content - if (loggable) { - streamingContent = new LoggingStreamingContent( - streamingContent, HttpTransport.LOGGER, Level.CONFIG, contentLoggingLimit); - } - // encoding - if (encoding == null) { - contentEncoding = null; - contentLength = content.getLength(); - } else { - contentEncoding = encoding.getName(); - streamingContent = new HttpEncodingStreamingContent(streamingContent, encoding); - contentLength = contentRetrySupported ? IOUtils.computeLength(streamingContent) : -1; - } - // append content headers to log buffer - if (loggable) { - if (contentType != null) { - String header = "Content-Type: " + contentType; - logbuf.append(header).append(StringUtils.LINE_SEPARATOR); - if (curlbuf != null) { - curlbuf.append(" -H '" + header + "'"); - } - } - if (contentEncoding != null) { - String header = "Content-Encoding: " + contentEncoding; - logbuf.append(header).append(StringUtils.LINE_SEPARATOR); - if (curlbuf != null) { - curlbuf.append(" -H '" + header + "'"); - } - } - if (contentLength >= 0) { - String header = "Content-Length: " + contentLength; - logbuf.append(header).append(StringUtils.LINE_SEPARATOR); - // do not log @ curl as the user will most likely manipulate the content - } - } - if (curlbuf != null) { - curlbuf.append(" -d '@-'"); - } - // send content information to low-level HTTP request - lowLevelHttpRequest.setContentType(contentType); - lowLevelHttpRequest.setContentEncoding(contentEncoding); - lowLevelHttpRequest.setContentLength(contentLength); - lowLevelHttpRequest.setStreamingContent(streamingContent); - } - // log from buffer - if (loggable) { - logger.config(logbuf.toString()); - if (curlbuf != null) { - curlbuf.append(" -- '"); - curlbuf.append(urlString.replaceAll("\'", "'\"'\"'")); - curlbuf.append("'"); - if (streamingContent != null) { - curlbuf.append(" << $$$"); - } - logger.config(curlbuf.toString()); - } - } - - // We need to make sure our content type can support retry - // null content is inherently able to be retried - retryRequest = contentRetrySupported && retriesRemaining > 0; - - // execute - lowLevelHttpRequest.setTimeout(connectTimeout, readTimeout); - try { - LowLevelHttpResponse lowLevelHttpResponse = lowLevelHttpRequest.execute(); - // Flag used to indicate if an exception is thrown before the response is constructed. - boolean responseConstructed = false; - try { - response = new HttpResponse(this, lowLevelHttpResponse); - responseConstructed = true; - } finally { - if (!responseConstructed) { - InputStream lowLevelContent = lowLevelHttpResponse.getContent(); - if (lowLevelContent != null) { - lowLevelContent.close(); - } - } - } - } catch (IOException e) { - if (!retryOnExecuteIOException && (ioExceptionHandler == null - || !ioExceptionHandler.handleIOException(this, retryRequest))) { - throw e; - } - // Save the exception in case the retries do not work and we need to re-throw it later. - executeException = e; - logger.log(Level.WARNING, "exception thrown while executing request", e); - } - - // Flag used to indicate if an exception is thrown before the response has completed - // processing. - boolean responseProcessed = false; - try { - if (response != null && !response.isSuccessStatusCode()) { - boolean errorHandled = false; - if (unsuccessfulResponseHandler != null) { - // Even if we don't have the potential to retry, we might want to run the - // handler to fix conditions (like expired tokens) that might cause us - // trouble on our next request - errorHandled = unsuccessfulResponseHandler.handleResponse(this, response, retryRequest); - } - if (!errorHandled) { - if (handleRedirect(response.getStatusCode(), response.getHeaders())) { - // The unsuccessful request's error could not be handled and it is a redirect request. - errorHandled = true; - } else if (retryRequest && backOffPolicy != null - && backOffPolicy.isBackOffRequired(response.getStatusCode())) { - // The unsuccessful request's error could not be handled and should be backed off - // before retrying - long backOffTime = backOffPolicy.getNextBackOffMillis(); - if (backOffTime != BackOffPolicy.STOP) { - try { - sleeper.sleep(backOffTime); - } catch (InterruptedException exception) { - // ignore - } - errorHandled = true; - } - } - } - // A retry is required if the error was successfully handled or if it is a redirect - // request or if the back off policy determined a retry is necessary. - retryRequest &= errorHandled; - // need to close the response stream before retrying a request - if (retryRequest) { - response.ignore(); - } - } else { - // Retry is not required for a successful status code unless the response is null. - retryRequest &= (response == null); - } - // Once there are no more retries remaining, this will be -1 - // Count redirects as retries, we want a finite limit of redirects. - retriesRemaining--; - - responseProcessed = true; - } finally { - if (response != null && !responseProcessed) { - response.disconnect(); - } - } - } while (retryRequest); - - if (response == null) { - // Retries did not help resolve the execute exception, re-throw it. - throw executeException; - } - // response interceptor - if (responseInterceptor != null) { - responseInterceptor.interceptResponse(response); - } - // throw an exception if unsuccessful response - if (throwExceptionOnExecuteError && !response.isSuccessStatusCode()) { - try { - throw new HttpResponseException(response); - } finally { - response.disconnect(); - } - } - return response; - } - - /** - * {@link Beta}
- * Executes this request asynchronously in a single separate thread using the supplied executor. - * - * @param executor executor to run the asynchronous request - * @return future for accessing the HTTP response - * @since 1.13 - */ - @Beta - public Future executeAsync(Executor executor) { - FutureTask future = new FutureTask(new Callable() { - - public HttpResponse call() throws Exception { - return execute(); - } - }); - executor.execute(future); - return future; - } - - /** - * {@link Beta}
- * Executes this request asynchronously using {@link #executeAsync(Executor)} in a single separate - * thread using {@link Executors#newSingleThreadExecutor()}. - * - * @return A future for accessing the results of the asynchronous request. - * @since 1.13 - */ - @Beta - public Future executeAsync() { - return executeAsync(Executors.newSingleThreadExecutor()); - } - - /** - * Sets up this request object to handle the necessary redirect if redirects are turned on, it is - * a redirect status code and the header has a location. - * - *

- * When the status code is {@code 303} the method on the request is changed to a GET as per the - * RFC2616 specification. On a redirect, it also removes the {@code "Authorization"} and all - * {@code "If-*"} request headers. - *

- * - *

- * Upgrade warning: When handling a status code of 303, {@link #handleRedirect(int, HttpHeaders)} - * now correctly removes any content from the body of the new request, as GET requests should not - * have content. It did not do this in prior version 1.16. - *

- * - * @return whether the redirect was successful - * @since 1.11 - */ - public boolean handleRedirect(int statusCode, HttpHeaders responseHeaders) { - String redirectLocation = responseHeaders.getLocation(); - if (getFollowRedirects() && HttpStatusCodes.isRedirect(statusCode) - && redirectLocation != null) { - // resolve the redirect location relative to the current location - setUrl(new GenericUrl(url.toURL(redirectLocation))); - // on 303 change method to GET - if (statusCode == HttpStatusCodes.STATUS_CODE_SEE_OTHER) { - setRequestMethod(HttpMethods.GET); - // GET requests do not support non-zero content length - setContent(null); - } - // remove Authorization and If-* headers - headers.setAuthorization((String) null); - headers.setIfMatch((String) null); - headers.setIfNoneMatch((String) null); - headers.setIfModifiedSince((String) null); - headers.setIfUnmodifiedSince((String) null); - headers.setIfRange((String) null); - return true; - } - return false; - } - - /** - * Returns the sleeper. - * - * @since 1.15 - */ - public Sleeper getSleeper() { - return sleeper; - } - - /** - * Sets the sleeper. The default value is {@link Sleeper#DEFAULT}. - * - * @since 1.15 - */ - public HttpRequest setSleeper(Sleeper sleeper) { - this.sleeper = Preconditions.checkNotNull(sleeper); - return this; - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/HttpRequestFactory.java b/src/autosaveworld/zlibs/com/google/api/client/http/HttpRequestFactory.java deleted file mode 100644 index e98313d8..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/HttpRequestFactory.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.IOException; - - -/** - * Thread-safe light-weight HTTP request factory layer on top of the HTTP transport that has an - * optional {@link HttpRequestInitializer HTTP request initializer} for initializing requests. - * - *

- * For example, to use a particular authorization header across all requests, use: - *

- * - *
-  public static HttpRequestFactory createRequestFactory(HttpTransport transport) {
-    return transport.createRequestFactory(new HttpRequestInitializer() {
-      public void initialize(HttpRequest request) throws IOException {
-        request.getHeaders().setAuthorization("...");
-      }
-    });
-  }
- * 
- * - * @since 1.4 - * @author Yaniv Inbar - */ -public final class HttpRequestFactory { - - /** HTTP transport. */ - private final HttpTransport transport; - - /** HTTP request initializer or {@code null} for none. */ - private final HttpRequestInitializer initializer; - - /** - * @param transport HTTP transport - * @param initializer HTTP request initializer or {@code null} for none - */ - HttpRequestFactory(HttpTransport transport, HttpRequestInitializer initializer) { - this.transport = transport; - this.initializer = initializer; - } - - /** - * Returns the HTTP transport. - * - * @since 1.5 - */ - public HttpTransport getTransport() { - return transport; - } - - /** - * Returns the HTTP request initializer or {@code null} for none. - * - *

- * This initializer is invoked before setting its method, URL, or content. - *

- * - * @since 1.5 - */ - public HttpRequestInitializer getInitializer() { - return initializer; - } - - /** - * Builds a request for the given HTTP method, URL, and content. - * - * @param requestMethod HTTP request method - * @param url HTTP request URL or {@code null} for none - * @param content HTTP request content or {@code null} for none - * @return new HTTP request - * @since 1.12 - */ - public HttpRequest buildRequest(String requestMethod, GenericUrl url, HttpContent content) - throws IOException { - HttpRequest request = transport.buildRequest(); - if (initializer != null) { - initializer.initialize(request); - } - request.setRequestMethod(requestMethod); - if (url != null) { - request.setUrl(url); - } - if (content != null) { - request.setContent(content); - } - return request; - } - - /** - * Builds a {@code DELETE} request for the given URL. - * - * @param url HTTP request URL or {@code null} for none - * @return new HTTP request - */ - public HttpRequest buildDeleteRequest(GenericUrl url) throws IOException { - return buildRequest(HttpMethods.DELETE, url, null); - } - - /** - * Builds a {@code GET} request for the given URL. - * - * @param url HTTP request URL or {@code null} for none - * @return new HTTP request - */ - public HttpRequest buildGetRequest(GenericUrl url) throws IOException { - return buildRequest(HttpMethods.GET, url, null); - } - - /** - * Builds a {@code POST} request for the given URL and content. - * - * @param url HTTP request URL or {@code null} for none - * @param content HTTP request content or {@code null} for none - * @return new HTTP request - */ - public HttpRequest buildPostRequest(GenericUrl url, HttpContent content) throws IOException { - return buildRequest(HttpMethods.POST, url, content); - } - - /** - * Builds a {@code PUT} request for the given URL and content. - * - * @param url HTTP request URL or {@code null} for none - * @param content HTTP request content or {@code null} for none - * @return new HTTP request - */ - public HttpRequest buildPutRequest(GenericUrl url, HttpContent content) throws IOException { - return buildRequest(HttpMethods.PUT, url, content); - } - - /** - * Builds a {@code PATCH} request for the given URL and content. - * - * @param url HTTP request URL or {@code null} for none - * @param content HTTP request content or {@code null} for none - * @return new HTTP request - */ - public HttpRequest buildPatchRequest(GenericUrl url, HttpContent content) throws IOException { - return buildRequest(HttpMethods.PATCH, url, content); - } - - /** - * Builds a {@code HEAD} request for the given URL. - * - * @param url HTTP request URL or {@code null} for none - * @return new HTTP request - */ - public HttpRequest buildHeadRequest(GenericUrl url) throws IOException { - return buildRequest(HttpMethods.HEAD, url, null); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/HttpRequestInitializer.java b/src/autosaveworld/zlibs/com/google/api/client/http/HttpRequestInitializer.java deleted file mode 100644 index 960e4edc..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/HttpRequestInitializer.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.IOException; - -/** - * HTTP request initializer. - * - *

- * For example, this might be used to disable request timeouts: - *

- * - *
-  public class DisableTimeout implements HttpRequestInitializer {
-    public void initialize(HttpRequest request) {
-      request.setConnectTimeout(0);
-      request.setReadTimeout(0);
-    }
-  }
- * 
- * - *

- * Sample usage with a request factory: - *

- * - *
-  public static HttpRequestFactory createRequestFactory(HttpTransport transport) {
-    return transport.createRequestFactory(new DisableTimeout());
-  }
- * 
- * - *

- * More complex usage example: - *

- * - *
-  public static HttpRequestFactory createRequestFactory2(HttpTransport transport) {
-    final DisableTimeout disableTimeout = new DisableTimeout();
-    return transport.createRequestFactory(new HttpRequestInitializer() {
-      public void initialize(HttpRequest request) {
-        disableTimeout.initialize(request);
-      }
-    });
-  }
- * 
- * - *

- * Implementations should normally be thread-safe. - *

- * - * @since 1.4 - * @author Yaniv Inbar - */ -public interface HttpRequestInitializer { - - /** - * Initializes a request. - * - * @param request HTTP request - */ - void initialize(HttpRequest request) throws IOException; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/HttpResponse.java b/src/autosaveworld/zlibs/com/google/api/client/http/HttpResponse.java deleted file mode 100644 index b36decf6..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/HttpResponse.java +++ /dev/null @@ -1,529 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.ByteArrayOutputStream; -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.Type; -import java.nio.charset.Charset; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.zip.GZIPInputStream; - -import autosaveworld.zlibs.com.google.api.client.util.Charsets; -import autosaveworld.zlibs.com.google.api.client.util.IOUtils; -import autosaveworld.zlibs.com.google.api.client.util.LoggingInputStream; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.StringUtils; - -/** - * HTTP response. - * - *

- * Callers should call {@link #disconnect} when the HTTP response object is no longer needed. - * However, {@link #disconnect} does not have to be called if the response stream is properly - * closed. Example usage: - *

- * - *
-   HttpResponse response = request.execute();
-   try {
-     // process the HTTP response object
-   } finally {
-     response.disconnect();
-   }
- * 
- * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.0 - * @author Yaniv Inbar - */ -public final class HttpResponse { - - /** HTTP response content or {@code null} before {@link #getContent()}. */ - private InputStream content; - - /** Content encoding or {@code null}. */ - private final String contentEncoding; - - /** Content type or {@code null} for none. */ - private final String contentType; - - /** Parsed content-type/media type or {@code null} if content-type is null. */ - private final HttpMediaType mediaType; - - /** Low-level HTTP response. */ - LowLevelHttpResponse response; - - /** Status code. */ - private final int statusCode; - - /** Status message or {@code null}. */ - private final String statusMessage; - - /** HTTP request. */ - private final HttpRequest request; - - /** - * Determines the limit to the content size that will be logged during {@link #getContent()}. - * - *

- * Content will only be logged if {@link #isLoggingEnabled} is {@code true}. - *

- * - *

- * If the content size is greater than this limit then it will not be logged. - *

- * - *

- * Can be set to {@code 0} to disable content logging. This is useful for example if content has - * sensitive data such as authentication information. - *

- * - *

- * Defaults to {@link HttpRequest#getContentLoggingLimit()}. - *

- */ - private int contentLoggingLimit; - - /** - * Determines whether logging should be enabled on this response. - * - *

- * Defaults to {@link HttpRequest#isLoggingEnabled()}. - *

- */ - private boolean loggingEnabled; - - /** Signals whether the content has been read from the input stream. */ - private boolean contentRead; - - HttpResponse(HttpRequest request, LowLevelHttpResponse response) throws IOException { - this.request = request; - contentLoggingLimit = request.getContentLoggingLimit(); - loggingEnabled = request.isLoggingEnabled(); - this.response = response; - contentEncoding = response.getContentEncoding(); - int code = response.getStatusCode(); - statusCode = code < 0 ? 0 : code; - String message = response.getReasonPhrase(); - statusMessage = message; - Logger logger = HttpTransport.LOGGER; - boolean loggable = loggingEnabled && logger.isLoggable(Level.CONFIG); - StringBuilder logbuf = null; - if (loggable) { - logbuf = new StringBuilder(); - logbuf.append("-------------- RESPONSE --------------").append(StringUtils.LINE_SEPARATOR); - String statusLine = response.getStatusLine(); - if (statusLine != null) { - logbuf.append(statusLine); - } else { - logbuf.append(statusCode); - if (message != null) { - logbuf.append(' ').append(message); - } - } - logbuf.append(StringUtils.LINE_SEPARATOR); - } - - // headers - request.getResponseHeaders().fromHttpResponse(response, loggable ? logbuf : null); - - // Retrieve the content-type directly from the headers as response.getContentType() is outdated - // and e.g. not set by BatchUnparsedResponse.FakeLowLevelHttpResponse - String contentType = response.getContentType(); - if (contentType == null) { - contentType = request.getResponseHeaders().getContentType(); - } - this.contentType = contentType; - mediaType = contentType == null ? null : new HttpMediaType(contentType); - - // log from buffer - if (loggable) { - logger.config(logbuf.toString()); - } - } - - /** - * Returns the limit to the content size that will be logged during {@link #getContent()}. - * - *

- * Content will only be logged if {@link #isLoggingEnabled} is {@code true}. - *

- * - *

- * If the content size is greater than this limit then it will not be logged. - *

- * - *

- * Can be set to {@code 0} to disable content logging. This is useful for example if content has - * sensitive data such as authentication information. - *

- * - *

- * Defaults to {@link HttpRequest#getContentLoggingLimit()}. - *

- * - * @since 1.7 - */ - public int getContentLoggingLimit() { - return contentLoggingLimit; - } - - /** - * Set the limit to the content size that will be logged during {@link #getContent()}. - * - *

- * Content will only be logged if {@link #isLoggingEnabled} is {@code true}. - *

- * - *

- * If the content size is greater than this limit then it will not be logged. - *

- * - *

- * Can be set to {@code 0} to disable content logging. This is useful for example if content has - * sensitive data such as authentication information. - *

- * - *

- * Defaults to {@link HttpRequest#getContentLoggingLimit()}. - *

- * - * @since 1.7 - */ - public HttpResponse setContentLoggingLimit(int contentLoggingLimit) { - Preconditions.checkArgument( - contentLoggingLimit >= 0, "The content logging limit must be non-negative."); - this.contentLoggingLimit = contentLoggingLimit; - return this; - } - - /** - * Returns whether logging should be enabled on this response. - * - *

- * Defaults to {@link HttpRequest#isLoggingEnabled()}. - *

- * - * @since 1.9 - */ - public boolean isLoggingEnabled() { - return loggingEnabled; - } - - /** - * Sets whether logging should be enabled on this response. - * - *

- * Defaults to {@link HttpRequest#isLoggingEnabled()}. - *

- * - * @since 1.9 - */ - public HttpResponse setLoggingEnabled(boolean loggingEnabled) { - this.loggingEnabled = loggingEnabled; - return this; - } - - /** - * Returns the content encoding or {@code null} for none. - * - * @since 1.5 - */ - public String getContentEncoding() { - return contentEncoding; - } - - /** - * Returns the content type or {@code null} for none. - * - * @since 1.5 - */ - public String getContentType() { - return contentType; - } - - /** - * Returns the parsed Content-Type in form of a {@link HttpMediaType} or {@code null} if no - * content-type was set. - * - * @since 1.10 - */ - public HttpMediaType getMediaType() { - return mediaType; - } - - /** - * Returns the HTTP response headers. - * - * @since 1.5 - */ - public HttpHeaders getHeaders() { - return request.getResponseHeaders(); - } - - /** - * Returns whether received a successful HTTP status code {@code >= 200 && < 300} (see - * {@link #getStatusCode()}). - * - * @since 1.5 - */ - public boolean isSuccessStatusCode() { - return HttpStatusCodes.isSuccess(statusCode); - } - - /** - * Returns the HTTP status code or {@code 0} for none. - * - * @since 1.5 - */ - public int getStatusCode() { - return statusCode; - } - - /** - * Returns the HTTP status message or {@code null} for none. - * - * @since 1.5 - */ - public String getStatusMessage() { - return statusMessage; - } - - /** - * Returns the HTTP transport. - * - * @since 1.5 - */ - public HttpTransport getTransport() { - return request.getTransport(); - } - - /** - * Returns the HTTP request. - * - * @since 1.5 - */ - public HttpRequest getRequest() { - return request; - } - - /** - * Returns the content of the HTTP response. - *

- * The result is cached, so subsequent calls will be fast. - *

- * Callers should call {@link InputStream#close} after the returned {@link InputStream} is no - * longer needed. Example usage: - * - *

-     InputStream is = response.getContent();
-     try {
-       // Process the input stream..
-     } finally {
-       is.close();
-     }
-   * 
- *

- * {@link HttpResponse#disconnect} does not have to be called if the content is closed. - * - * @return input stream content of the HTTP response or {@code null} for none - * @throws IOException I/O exception - */ - public InputStream getContent() throws IOException { - if (!contentRead) { - InputStream lowLevelResponseContent = this.response.getContent(); - if (lowLevelResponseContent != null) { - // Flag used to indicate if an exception is thrown before the content is successfully - // processed. - boolean contentProcessed = false; - try { - // gzip encoding (wrap content with GZipInputStream) - String contentEncoding = this.contentEncoding; - if (contentEncoding != null && contentEncoding.contains("gzip")) { - lowLevelResponseContent = new GZIPInputStream(lowLevelResponseContent); - } - // logging (wrap content with LoggingInputStream) - Logger logger = HttpTransport.LOGGER; - if (loggingEnabled && logger.isLoggable(Level.CONFIG)) { - lowLevelResponseContent = new LoggingInputStream( - lowLevelResponseContent, logger, Level.CONFIG, contentLoggingLimit); - } - content = lowLevelResponseContent; - contentProcessed = true; - } catch (EOFException e) { - // this may happen for example on a HEAD request since there no actual response data read - // in GZIPInputStream - } finally { - if (!contentProcessed) { - lowLevelResponseContent.close(); - } - } - } - contentRead = true; - } - return content; - } - - /** - * Writes the content of the HTTP response into the given destination output stream. - * - *

- * Sample usage: - * - *

-     HttpRequest request = requestFactory.buildGetRequest(
-         new GenericUrl("https://www.google.com/images/srpr/logo3w.png"));
-     OutputStream outputStream = new FileOutputStream(new File("/tmp/logo3w.png"));
-     try {
-       HttpResponse response = request.execute();
-       response.download(outputStream);
-     } finally {
-       outputStream.close();
-     }
-    
- * - *

- * - *

- * This method closes the content of the HTTP response from {@link #getContent()}. - *

- * - *

- * This method does not close the given output stream. - *

- * - * @param outputStream destination output stream - * @throws IOException I/O exception - * @since 1.9 - */ - public void download(OutputStream outputStream) throws IOException { - InputStream inputStream = getContent(); - IOUtils.copy(inputStream, outputStream); - } - - /** - * Closes the content of the HTTP response from {@link #getContent()}, ignoring any content. - */ - public void ignore() throws IOException { - InputStream content = getContent(); - if (content != null) { - content.close(); - } - } - - /** - * Close the HTTP response content using {@link #ignore}, and disconnect using - * {@link LowLevelHttpResponse#disconnect()}. - * - * @since 1.4 - */ - public void disconnect() throws IOException { - ignore(); - response.disconnect(); - } - - /** - * Parses the content of the HTTP response from {@link #getContent()} and reads it into a data - * class of key/value pairs using the parser returned by {@link HttpRequest#getParser()}. - * - *

- * Reference: http://tools.ietf.org/html/rfc2616#section-4.3 - *

- * - * @return parsed data class or {@code null} for no content - */ - public T parseAs(Class dataClass) throws IOException { - if (!hasMessageBody()) { - return null; - } - return request.getParser().parseAndClose(getContent(), getContentCharset(), dataClass); - } - - /** - * Returns whether this response contains a message body as specified in {@href - * http://tools.ietf.org/html/rfc2616#section-4.3}, calling {@link #ignore()} if {@code false}. - */ - private boolean hasMessageBody() throws IOException { - int statusCode = getStatusCode(); - if (getRequest().getRequestMethod().equals(HttpMethods.HEAD) || statusCode / 100 == 1 - || statusCode == HttpStatusCodes.STATUS_CODE_NO_CONTENT - || statusCode == HttpStatusCodes.STATUS_CODE_NOT_MODIFIED) { - ignore(); - return false; - } - return true; - } - - /** - * Parses the content of the HTTP response from {@link #getContent()} and reads it into a data - * type of key/value pairs using the parser returned by {@link HttpRequest#getParser()}. - * - * @return parsed data type instance or {@code null} for no content - * @since 1.10 - */ - public Object parseAs(Type dataType) throws IOException { - if (!hasMessageBody()) { - return null; - } - return request.getParser().parseAndClose(getContent(), getContentCharset(), dataType); - } - - /** - * Parses the content of the HTTP response from {@link #getContent()} and reads it into a string. - * - *

- * Since this method returns {@code ""} for no content, a simpler check for no content is to check - * if {@link #getContent()} is {@code null}. - *

- * - *

- * All content is read from the input content stream rather than being limited by the - * Content-Length. For the character set, it follows the specification by parsing the "charset" - * parameter of the Content-Type header or by default {@code "ISO-8859-1"} if the parameter is - * missing. - *

- * - * @return parsed string or {@code ""} for no content - * @throws IOException I/O exception - */ - public String parseAsString() throws IOException { - InputStream content = getContent(); - if (content == null) { - return ""; - } - ByteArrayOutputStream out = new ByteArrayOutputStream(); - IOUtils.copy(content, out); - return out.toString(getContentCharset().name()); - } - - /** - * Returns the {@link Charset} specified in the Content-Type of this response or the - * {@code "ISO-8859-1"} charset as a default. - * - * @since 1.10 - * */ - public Charset getContentCharset() { - return mediaType == null || mediaType.getCharsetParameter() == null - ? Charsets.ISO_8859_1 : mediaType.getCharsetParameter(); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/HttpResponseException.java b/src/autosaveworld/zlibs/com/google/api/client/http/HttpResponseException.java deleted file mode 100644 index 9373ec72..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/HttpResponseException.java +++ /dev/null @@ -1,308 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.IOException; - -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.StringUtils; - -/** - * Exception thrown when an error status code is detected in an HTTP response. - * - *

- * Implementation is not thread safe. - *

- * - * @since 1.0 - * @author Yaniv Inbar - */ -public class HttpResponseException extends IOException { - - private static final long serialVersionUID = -1875819453475890043L; - - /** HTTP status code. */ - private final int statusCode; - - /** Status message or {@code null}. */ - private final String statusMessage; - - /** HTTP headers. */ - private final transient HttpHeaders headers; - - /** HTTP response content or {@code null} for none. */ - private final String content; - - /** - * Constructor that constructs a detail message from the given HTTP response that includes the - * status code, status message and HTTP response content. - * - *

- * Callers of this constructor should call {@link HttpResponse#disconnect} after - * {@link HttpResponseException} is instantiated. Example usage: - *

- * - *
-     try {
-       throw new HttpResponseException(response);
-     } finally {
-       response.disconnect();
-     }
-   * 
- * - * @param response HTTP response - */ - public HttpResponseException(HttpResponse response) { - this(new Builder(response)); - } - - /** - * @param builder builder - * - * @since 1.14 - */ - protected HttpResponseException(Builder builder) { - super(builder.message); - statusCode = builder.statusCode; - statusMessage = builder.statusMessage; - headers = builder.headers; - content = builder.content; - } - - /** - * Returns whether received a successful HTTP status code {@code >= 200 && < 300} (see - * {@link #getStatusCode()}). - * - * @since 1.7 - */ - public final boolean isSuccessStatusCode() { - return HttpStatusCodes.isSuccess(statusCode); - } - - /** - * Returns the HTTP status code or {@code 0} for none. - * - * @since 1.7 - */ - public final int getStatusCode() { - return statusCode; - } - - /** - * Returns the HTTP status message or {@code null} for none. - * - * @since 1.9 - */ - public final String getStatusMessage() { - return statusMessage; - } - - /** - * Returns the HTTP response headers. - * - * @since 1.7 - */ - public HttpHeaders getHeaders() { - return headers; - } - - /** - * Returns the HTTP response content or {@code null} for none. - * - * @since 1.14 - */ - public final String getContent() { - return content; - } - - /** - * Builder. - * - *

- * Implementation is not thread safe. - *

- * - * - * @since 1.14 - */ - public static class Builder { - - /** HTTP status code. */ - int statusCode; - - /** Status message or {@code null}. */ - String statusMessage; - - /** HTTP headers. */ - HttpHeaders headers; - - /** Response content or {@code null} for none. */ - String content; - - /** Detail message to use or {@code null} for none. */ - String message; - - /** - * @param statusCode HTTP status code - * @param statusMessage status message or {@code null} - * @param headers HTTP headers - */ - public Builder(int statusCode, String statusMessage, HttpHeaders headers) { - setStatusCode(statusCode); - setStatusMessage(statusMessage); - setHeaders(headers); - } - - /** - * @param response HTTP response - */ - public Builder(HttpResponse response) { - this(response.getStatusCode(), response.getStatusMessage(), response.getHeaders()); - // content - try { - content = response.parseAsString(); - if (content.length() == 0) { - content = null; - } - } catch (IOException exception) { - // it would be bad to throw an exception while throwing an exception - exception.printStackTrace(); - } - // message - StringBuilder builder = computeMessageBuffer(response); - if (content != null) { - builder.append(StringUtils.LINE_SEPARATOR).append(content); - } - message = builder.toString(); - } - - /** Returns the detail message to use or {@code null} for none. */ - public final String getMessage() { - return message; - } - - /** - * Sets the detail message to use or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setMessage(String message) { - this.message = message; - return this; - } - - /** Returns the HTTP status code or {@code 0} for none. */ - public final int getStatusCode() { - return statusCode; - } - - /** - * Sets the HTTP status code or {@code 0} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setStatusCode(int statusCode) { - Preconditions.checkArgument(statusCode >= 0); - this.statusCode = statusCode; - return this; - } - - /** Returns the HTTP status message or {@code null} for none. */ - public final String getStatusMessage() { - return statusMessage; - } - - /** - * Sets the HTTP status message or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setStatusMessage(String statusMessage) { - this.statusMessage = statusMessage; - return this; - } - - /** Returns the HTTP response headers. */ - public HttpHeaders getHeaders() { - return headers; - } - - /** - * Sets the HTTP response headers. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setHeaders(HttpHeaders headers) { - this.headers = Preconditions.checkNotNull(headers); - return this; - } - - /** Returns the HTTP response content or {@code null} for none. */ - public final String getContent() { - return content; - } - - /** - * Sets the HTTP response content or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setContent(String content) { - this.content = content; - return this; - } - - /** Returns a new instance of {@link HttpResponseException} based on this builder. */ - public HttpResponseException build() { - return new HttpResponseException(this); - } - } - - /** - * Returns an exception message string builder to use for the given HTTP response. - * - * @since 1.7 - */ - public static StringBuilder computeMessageBuffer(HttpResponse response) { - StringBuilder builder = new StringBuilder(); - int statusCode = response.getStatusCode(); - if (statusCode != 0) { - builder.append(statusCode); - } - String statusMessage = response.getStatusMessage(); - if (statusMessage != null) { - if (statusCode != 0) { - builder.append(' '); - } - builder.append(statusMessage); - } - return builder; - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/HttpResponseInterceptor.java b/src/autosaveworld/zlibs/com/google/api/client/http/HttpResponseInterceptor.java deleted file mode 100644 index 47dcaef3..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/HttpResponseInterceptor.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.IOException; - -/** - * HTTP response interceptor to intercept the end of {@link HttpRequest#execute()} before returning - * a successful response or throwing an exception for an unsuccessful response. - * - *

- * For example, this might be used to add a simple timer on requests: - *

- * - *
-  public static class TimerResponseInterceptor implements HttpResponseInterceptor {
-
-    private final long startTime = System.nanoTime();
-
-    public void interceptResponse(HttpResponse response) {
-      long elapsedNanos = System.nanoTime() - startTime;
-      System.out.println("elapsed seconds: " + TimeUnit.NANOSECONDS.toSeconds(elapsedNanos) + "s");
-    }
-  }
- * 
- * - *

- * Sample usage with a request factory: - *

- * - *
-  public static HttpRequestFactory createRequestFactory(HttpTransport transport) {
-    return transport.createRequestFactory(new HttpRequestInitializer() {
-
-      {@literal @}Override
-      public void initialize(HttpRequest request) {
-        request.setResponseInterceptor(new TimerResponseInterceptor());
-      }
-    });
-  }
- * 
- * - *

- * More complex usage example: - *

- * - *
-  public static HttpRequestFactory createRequestFactory2(HttpTransport transport) {
-    final HttpResponseInterceptor responseInterceptor = new TimerResponseInterceptor();
-    return transport.createRequestFactory(new HttpRequestInitializer() {
-
-      public void initialize(HttpRequest request) {
-        request.setResponseInterceptor(new HttpResponseInterceptor() {
-
-          public void interceptResponse(HttpResponse response) throws IOException {
-            responseInterceptor.interceptResponse(response);
-          }
-        });
-      }
-    });
-  }
- * 
- * - *

- * Implementations should normally be thread-safe. - *

- * - * @author Yaniv Inbar - * @since 1.13 - */ -public interface HttpResponseInterceptor { - - /** - * Invoked at the end of {@link HttpRequest#execute()} before returning a successful response or - * throwing an exception for an unsuccessful response. - * - *

- * Do not read from the content stream unless you intend to throw an exception. Otherwise, it - * would prevent the caller of {@link HttpRequest#execute()} to be able to read the stream from - * {@link HttpResponse#getContent()}. If you intend to throw an exception, you should parse the - * response, or alternatively pass the response as part of the exception. - *

- * - * @param response HTTP response - */ - void interceptResponse(HttpResponse response) throws IOException; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/HttpStatusCodes.java b/src/autosaveworld/zlibs/com/google/api/client/http/HttpStatusCodes.java deleted file mode 100644 index 3d4e00f5..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/HttpStatusCodes.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -/** - * Constants enumerating the HTTP status codes. Includes status codes specified in RFC2616 (HTTP/1.1). - * - * @since 1.6 - * @author Ravi Mistry - */ -public class HttpStatusCodes { - - /** Status code for a successful request. */ - public static final int STATUS_CODE_OK = 200; - - /** - * Status code for a successful request with no content information. - * - * @since 1.11 - */ - public static final int STATUS_CODE_NO_CONTENT = 204; - - /** Status code for a resource corresponding to any one of a set of representations. */ - public static final int STATUS_CODE_MULTIPLE_CHOICES = 300; - - /** Status code for a resource that has permanently moved to a new URI. */ - public static final int STATUS_CODE_MOVED_PERMANENTLY = 301; - - /** Status code for a resource that has temporarily moved to a new URI. */ - public static final int STATUS_CODE_FOUND = 302; - - /** Status code for a resource that has moved to a new URI and should be retrieved using GET. */ - public static final int STATUS_CODE_SEE_OTHER = 303; - - /** Status code for a resource that access is allowed but the document has not been modified. */ - public static final int STATUS_CODE_NOT_MODIFIED = 304; - - /** Status code for a resource that has temporarily moved to a new URI. */ - public static final int STATUS_CODE_TEMPORARY_REDIRECT = 307; - - /** Status code for a request that requires user authentication. */ - public static final int STATUS_CODE_UNAUTHORIZED = 401; - - /** Status code for a server that understood the request, but is refusing to fulfill it. */ - public static final int STATUS_CODE_FORBIDDEN = 403; - - /** Status code for a server that has not found anything matching the Request-URI. */ - public static final int STATUS_CODE_NOT_FOUND = 404; - - /** Status code for a request that could not be completed due to a resource conflict. */ - public static final int STATUS_CODE_CONFLICT = 409; - - /** Status code for an internal server error. */ - public static final int STATUS_CODE_SERVER_ERROR = 500; - - /** - * Status code for a bad gateway. - * - * @since 1.16 - */ - public static final int STATUS_CODE_BAD_GATEWAY = 502; - - /** Status code for a service that is unavailable on the server. */ - public static final int STATUS_CODE_SERVICE_UNAVAILABLE = 503; - - /** - * Returns whether the given HTTP response status code is a success code {@code >= 200 and < 300}. - */ - public static boolean isSuccess(int statusCode) { - return statusCode >= STATUS_CODE_OK && statusCode < STATUS_CODE_MULTIPLE_CHOICES; - } - - /** - * Returns whether the given HTTP response status code is a redirect code - * {@code 301, 302, 303, 307}. - * - * @since 1.11 - */ - public static boolean isRedirect(int statusCode) { - switch (statusCode) { - case HttpStatusCodes.STATUS_CODE_MOVED_PERMANENTLY: // 301 - case HttpStatusCodes.STATUS_CODE_FOUND: // 302 - case HttpStatusCodes.STATUS_CODE_SEE_OTHER: // 303 - case HttpStatusCodes.STATUS_CODE_TEMPORARY_REDIRECT: // 307 - return true; - default: - return false; - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/HttpTransport.java b/src/autosaveworld/zlibs/com/google/api/client/http/HttpTransport.java deleted file mode 100644 index 168d390e..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/HttpTransport.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.IOException; -import java.util.Arrays; -import java.util.logging.Logger; - -/** - * Thread-safe abstract HTTP transport. - * - *

- * Implementation is thread-safe, and sub-classes must be thread-safe. For maximum efficiency, - * applications should use a single globally-shared instance of the HTTP transport. - *

- * - *

- * The recommended concrete implementation HTTP transport library to use depends on what environment - * you are running in: - *

- *
    - *
  • Google App Engine: use - * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}. - *
      - *
    • {@code com.google.api.client.apache.ApacheHttpTransport} doesn't work on App Engine because - * the Apache HTTP Client opens its own sockets (though in theory there are ways to hack it to work - * on App Engine that might work).
    • - *
    • {@code com.google.api.client.javanet.NetHttpTransport} is discouraged due to a bug in the App - * Engine SDK itself in how it parses HTTP headers in the response.
    • - *
    - *
  • - *
  • Android: - *
      - *
    • For maximum backwards compatibility with older SDK's use {@code newCompatibleTransport} from - * {@code com.google.api.client.extensions.android.http.AndroidHttp} (read its JavaDoc for details). - *
    • - *
    • If your application is targeting Gingerbread (SDK 2.3) or higher, simply use - * {@code com.google.api.client.javanet.NetHttpTransport}.
    • - *
    - *
  • - *
  • Other Java environments - *
      - *
    • {@code com.google.api.client.javanet.NetHttpTransport} is based on the HttpURLConnection - * built into the Java SDK, so it is normally the preferred choice.
    • - *
    • {@code com.google.api.client.apache.ApacheHttpTransport} is a good choice for users of the - * Apache HTTP Client, especially if you need some of the configuration options available in that - * library.
    • - *
    - *
  • - *
- * - *

- * Some HTTP transports do not support all HTTP methods. Use {@link #supportsMethod(String)} to - * check if a certain HTTP method is supported. Calling {@link #buildRequest()} on a method that is - * not supported will result in an {@link IllegalArgumentException}. - *

- * - *

- * Subclasses should override {@link #supportsMethod(String)} and - * {@link #buildRequest(String, String)} to build requests and specify which HTTP methods are - * supported. - *

- * - * @since 1.0 - * @author Yaniv Inbar - */ -public abstract class HttpTransport { - - static final Logger LOGGER = Logger.getLogger(HttpTransport.class.getName()); - - /** - * All valid request methods as specified in {@link #supportsMethod(String)}, sorted in ascending - * alphabetical order. - */ - private static final String[] SUPPORTED_METHODS = - {HttpMethods.DELETE, HttpMethods.GET, HttpMethods.POST, HttpMethods.PUT}; - static { - Arrays.sort(SUPPORTED_METHODS); - } - - /** - * Returns a new instance of an HTTP request factory based on this HTTP transport. - * - * @return new instance of an HTTP request factory - * @since 1.4 - */ - public final HttpRequestFactory createRequestFactory() { - return createRequestFactory(null); - } - - /** - * Returns a new instance of an HTTP request factory based on this HTTP transport with the given - * HTTP request initializer. - * - * @param initializer HTTP request initializer or {@code null} for none - * @return new instance of an HTTP request factory - * @since 1.4 - */ - public final HttpRequestFactory createRequestFactory(HttpRequestInitializer initializer) { - return new HttpRequestFactory(this, initializer); - } - - /** - * Builds a request without specifying the HTTP method. - * - * @return new HTTP request - */ - HttpRequest buildRequest() { - return new HttpRequest(this, null); - } - - /** - * Returns whether a specified HTTP method is supported by this transport. - * - *

- * Default implementation returns true if and only if the request method is {@code "DELETE"}, - * {@code "GET"}, {@code "POST"}, or {@code "PUT"}. Subclasses should override. - *

- * - * @param method HTTP method - * @throws IOException I/O exception - * @since 1.12 - */ - public boolean supportsMethod(String method) throws IOException { - return Arrays.binarySearch(SUPPORTED_METHODS, method) >= 0; - } - - /** - * Builds a low level HTTP request for the given HTTP method. - * - * @param method HTTP method - * @param url URL - * @return new low level HTTP request - * @throws IllegalArgumentException if HTTP method is not supported - * @since 1.12 - */ - protected abstract LowLevelHttpRequest buildRequest(String method, String url) throws IOException; - - /** - * Default implementation does nothing, but subclasses may override to possibly release allocated - * system resources or close connections. - * - * @throws IOException I/O exception - * @since 1.4 - */ - public void shutdown() throws IOException { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/HttpUnsuccessfulResponseHandler.java b/src/autosaveworld/zlibs/com/google/api/client/http/HttpUnsuccessfulResponseHandler.java deleted file mode 100644 index f1c8fcab..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/HttpUnsuccessfulResponseHandler.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.IOException; - -/** - * Interface which handles abnormal HTTP responses (in other words not 2XX). - * - *

- * For example, this might be used to refresh an OAuth 2 token: - *

- * - *
-  public static class RefreshTokenHandler implements HttpUnsuccessfulResponseHandler {
-    public boolean handleResponse(
-        HttpRequest request, HttpResponse response, boolean retrySupported) throws IOException {
-      if (response.getStatusCode() == HttpStatusCodes.STATUS_CODE_UNAUTHORIZED) {
-        refreshToken();
-      }
-      return false;
-    }
-  }
- * 
- * - *

- * Sample usage with a request factory: - *

- * - *
-  public static HttpRequestFactory createRequestFactory(HttpTransport transport) {
-    final RefreshTokenHandler handler = new RefreshTokenHandler();
-    return transport.createRequestFactory(new HttpRequestInitializer() {
-      public void initialize(HttpRequest request) {
-        request.setUnsuccessfulResponseHandler(handler);
-      }
-    });
-  }
- * 
- * - *

- * More complex usage example: - *

- * - *
-  public static HttpRequestFactory createRequestFactory2(HttpTransport transport) {
-    final RefreshTokenHandler handler = new RefreshTokenHandler();
-    return transport.createRequestFactory(new HttpRequestInitializer() {
-      public void initialize(HttpRequest request) {
-        request.setUnsuccessfulResponseHandler(new HttpUnsuccessfulResponseHandler() {
-          public boolean handleResponse(
-              HttpRequest request, HttpResponse response, boolean retrySupported)
-              throws IOException {
-            return handler.handleResponse(request, response, retrySupported);
-          }
-        });
-      }
-    });
-  }
- * 
- * - * @author moshenko@google.com (Jacob Moshenko) - * @since 1.4 - */ -public interface HttpUnsuccessfulResponseHandler { - - /** - * Handler that will be invoked when an abnormal response is received. There are a few simple - * rules that one must follow: - *
    - *
  • If you modify the request object or modify its execute interceptors in a way that should - * resolve the error, you must return true to issue a retry.
  • - *
  • Do not read from the content stream, this will prevent the eventual end user from having - * access to it.
  • - *
- * - * @param request Request object that can be read from for context or modified before retry - * @param response Response to process - * @param supportsRetry Whether there will actually be a retry if this handler return {@code - * true}. Some handlers may want to have an effect only when there will actually be a retry - * after they handle their event (e.g. a handler that implements exponential backoff). - * @return Whether or not this handler has made a change that will require the request to be - * re-sent. - */ - boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry) - throws IOException; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/InputStreamContent.java b/src/autosaveworld/zlibs/com/google/api/client/http/InputStreamContent.java deleted file mode 100644 index bd34877f..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/InputStreamContent.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.InputStream; -import java.io.OutputStream; - -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * Concrete implementation of {@link AbstractInputStreamContent} that simply handles the transfer of - * data from an input stream to an output stream. This should only be used for streams that can not - * be re-opened and retried. If you have a stream that it is possible to recreate please create a - * new subclass of {@link AbstractInputStreamContent}. - * - *

- * The input stream is guaranteed to be closed at the end of {@link #writeTo(OutputStream)}. - *

- * - *

- * Sample use with a URL: - * - *

- * 
-  private static void setRequestJpegContent(HttpRequest request, URL jpegUrl) throws IOException {
-    request.setContent(new InputStreamContent("image/jpeg", jpegUrl.openStream()));
-  }
- * 
- * 
- * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.0 - * @author Yaniv Inbar - */ -public final class InputStreamContent extends AbstractInputStreamContent { - - /** Content length or less than zero if not known. Defaults to {@code -1}. */ - private long length = -1; - - /** Whether or not retry is supported. Defaults to {@code false}. */ - private boolean retrySupported; - - /** Input stream to read from. */ - private final InputStream inputStream; - - /** - * @param type Content type or {@code null} for none - * @param inputStream Input stream to read from - * @since 1.5 - */ - public InputStreamContent(String type, InputStream inputStream) { - super(type); - this.inputStream = Preconditions.checkNotNull(inputStream); - } - - public long getLength() { - return length; - } - - public boolean retrySupported() { - return retrySupported; - } - - /** - * Sets whether or not retry is supported. Defaults to {@code false}. - * - *

- * Should be set to {@code true} if {@link #getInputStream} is called to reset to the original - * position of the input stream. - *

- * - * @since 1.7 - */ - public InputStreamContent setRetrySupported(boolean retrySupported) { - this.retrySupported = retrySupported; - return this; - } - - @Override - public InputStream getInputStream() { - return inputStream; - } - - @Override - public InputStreamContent setType(String type) { - return (InputStreamContent) super.setType(type); - } - - @Override - public InputStreamContent setCloseInputStream(boolean closeInputStream) { - return (InputStreamContent) super.setCloseInputStream(closeInputStream); - } - - /** - * Sets the content length or less than zero if not known. - * - *

- * Defaults to {@code -1}. - *

- * - * @since 1.5 - */ - public InputStreamContent setLength(long length) { - this.length = length; - return this; - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/LowLevelHttpRequest.java b/src/autosaveworld/zlibs/com/google/api/client/http/LowLevelHttpRequest.java deleted file mode 100644 index a154a14d..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/LowLevelHttpRequest.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.IOException; - -import autosaveworld.zlibs.com.google.api.client.util.StreamingContent; - -/** - * Low-level HTTP request. - * - *

- * This allows providing a different implementation of the HTTP request that is more compatible with - * the Java environment used. - *

- * - *

- * Implementation has no fields and therefore thread-safe, but sub-classes are not necessarily - * thread-safe. - *

- * - * @since 1.0 - * @author Yaniv Inbar - */ -public abstract class LowLevelHttpRequest { - - /** Content length or less than zero if not known. */ - private long contentLength = -1; - - /** Content encoding (for example {@code "gzip"}) or {@code null} for none. */ - private String contentEncoding; - - /** Content type or {@code null} for none. */ - private String contentType; - - /** Streaming content or {@code null} for no content. */ - private StreamingContent streamingContent; - - /** - * Adds a header to the HTTP request. - * - *

- * Note that multiple headers of the same name need to be supported, in which case - * {@link #addHeader} will be called for each instance of the header. - *

- * - * @param name header name - * @param value header value - */ - public abstract void addHeader(String name, String value) throws IOException; - - /** - * Sets the content length or less than zero if not known. - * - *

- * Default value is {@code -1}. - *

- * - * @throws IOException I/O exception - * @since 1.14 - */ - public final void setContentLength(long contentLength) throws IOException { - this.contentLength = contentLength; - } - - /** - * Returns the content length or less than zero if not known. - * - * @since 1.14 - */ - public final long getContentLength() { - return contentLength; - } - - /** - * Sets the content encoding (for example {@code "gzip"}) or {@code null} for none. - * - * @throws IOException I/O exception - * @since 1.14 - */ - public final void setContentEncoding(String contentEncoding) throws IOException { - this.contentEncoding = contentEncoding; - } - - /** - * Returns the content encoding (for example {@code "gzip"}) or {@code null} for none. - * - * @since 1.14 - */ - public final String getContentEncoding() { - return contentEncoding; - } - - /** - * Sets the content type or {@code null} for none. - * - * @throws IOException I/O exception - * @since 1.14 - */ - public final void setContentType(String contentType) throws IOException { - this.contentType = contentType; - } - - /** - * Returns the content type or {@code null} for none. - * - * @since 1.14 - */ - public final String getContentType() { - return contentType; - } - - /** - * Sets the streaming content or {@code null} for no content. - * - * @throws IOException I/O exception - * @since 1.14 - */ - public final void setStreamingContent(StreamingContent streamingContent) - throws IOException { - this.streamingContent = streamingContent; - } - - /** - * Returns the streaming content or {@code null} for no content. - * - * @since 1.14 - */ - public final StreamingContent getStreamingContent() { - return streamingContent; - } - - /** - * Sets the connection and read timeouts. - * - *

- * Default implementation does nothing, but subclasses should normally override. - *

- * - * @param connectTimeout timeout in milliseconds to establish a connection or {@code 0} for an - * infinite timeout - * @param readTimeout Timeout in milliseconds to read data from an established connection or - * {@code 0} for an infinite timeout - * @throws IOException I/O exception - * @since 1.4 - */ - public void setTimeout(int connectTimeout, int readTimeout) throws IOException { - } - - /** Executes the request and returns a low-level HTTP response object. */ - public abstract LowLevelHttpResponse execute() throws IOException; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/LowLevelHttpResponse.java b/src/autosaveworld/zlibs/com/google/api/client/http/LowLevelHttpResponse.java deleted file mode 100644 index 84da03d7..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/LowLevelHttpResponse.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.IOException; -import java.io.InputStream; - -/** - * Low-level HTTP response. - * - *

- * This allows providing a different implementation of the HTTP response that is more compatible - * with the Java environment used. - *

- * - *

- * Implementation has no fields and therefore thread-safe, but sub-classes are not necessarily - * thread-safe. - *

- * - * @since 1.0 - * @author Yaniv Inbar - */ -public abstract class LowLevelHttpResponse { - - /** - * Returns the HTTP response content input stream or {@code null} for none. - * - * @throws IOException I/O exception - */ - public abstract InputStream getContent() throws IOException; - - /** Returns the content encoding (for example {@code "gzip"}) or {@code null} for none. */ - public abstract String getContentEncoding() throws IOException; - - /** Returns the content length or {@code 0} for none. */ - public abstract long getContentLength() throws IOException; - - /** Returns the content type or {@code null} for none. */ - public abstract String getContentType() throws IOException; - - /** Returns the response status line or {@code null} for none. */ - public abstract String getStatusLine() throws IOException; - - /** Returns the response status code or {@code <=0} for none. */ - public abstract int getStatusCode() throws IOException; - - /** Returns the HTTP reason phrase or {@code null} for none. */ - public abstract String getReasonPhrase() throws IOException; - - /** - * Returns the number of HTTP response headers. - * - *

- * Note that multiple headers of the same name need to be supported, in which case each header - * value is treated as a separate header. - *

- */ - public abstract int getHeaderCount() throws IOException; - - /** Returns the HTTP response header name at the given zero-based index. */ - public abstract String getHeaderName(int index) throws IOException; - - /** Returns the HTTP response header value at the given zero-based index. */ - public abstract String getHeaderValue(int index) throws IOException; - - /** - * Default implementation does nothing, but subclasses may override to attempt to abort the - * connection or release allocated system resources for this connection. - * - * @throws IOException I/O exception - * @since 1.4 - */ - public void disconnect() throws IOException { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/MultipartContent.java b/src/autosaveworld/zlibs/com/google/api/client/http/MultipartContent.java deleted file mode 100644 index 13fce9dc..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/MultipartContent.java +++ /dev/null @@ -1,277 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; - -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.StreamingContent; - -/** - * Serializes MIME multipart content as specified by RFC 2387: The MIME Multipart/Related Content-type - * and RFC 2046: Multipurpose Internet - * Mail Extensions: The Multipart/mixed (primary) subtype. - * - *

- * By default the media type is {@code "multipart/related; boundary=__END_OF_PART__"}, but this may - * be customized by calling {@link #setMediaType(HttpMediaType)}, {@link #getMediaType()}, or - * {@link #setBoundary(String)}. - *

- * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.14 - * @author Yaniv Inbar - */ -public class MultipartContent extends AbstractHttpContent { - - static final String NEWLINE = "\r\n"; - - private static final String TWO_DASHES = "--"; - - /** Parts of the HTTP multipart request. */ - private ArrayList parts = new ArrayList(); - - public MultipartContent() { - super(new HttpMediaType("multipart/related").setParameter("boundary", "__END_OF_PART__")); - } - - public void writeTo(OutputStream out) throws IOException { - Writer writer = new OutputStreamWriter(out, getCharset()); - String boundary = getBoundary(); - for (Part part : parts) { - HttpHeaders headers = new HttpHeaders().setAcceptEncoding(null); - if (part.headers != null) { - headers.fromHttpHeaders(part.headers); - } - headers.setContentEncoding(null) - .setUserAgent(null) - .setContentType(null) - .setContentLength(null) - .set("Content-Transfer-Encoding", null); - // analyze the content - HttpContent content = part.content; - StreamingContent streamingContent = null; - if (content != null) { - headers.set("Content-Transfer-Encoding", Arrays.asList("binary")); - headers.setContentType(content.getType()); - HttpEncoding encoding = part.encoding; - long contentLength; - if (encoding == null) { - contentLength = content.getLength(); - streamingContent = content; - } else { - headers.setContentEncoding(encoding.getName()); - streamingContent = new HttpEncodingStreamingContent(content, encoding); - contentLength = AbstractHttpContent.computeLength(content); - } - if (contentLength != -1) { - headers.setContentLength(contentLength); - } - } - // write multipart-body from RFC 1521 §7.2.1 - // write encapsulation - // write delimiter - writer.write(TWO_DASHES); - writer.write(boundary); - writer.write(NEWLINE); - // write body-part; message from RFC 822 §4.1 - // write message fields - HttpHeaders.serializeHeadersForMultipartRequests(headers, null, null, writer); - if (streamingContent != null) { - writer.write(NEWLINE); - writer.flush(); - // write message text/body - streamingContent.writeTo(out); - } - // terminate encapsulation - writer.write(NEWLINE); - } - // write close-delimiter - writer.write(TWO_DASHES); - writer.write(boundary); - writer.write(TWO_DASHES); - writer.write(NEWLINE); - writer.flush(); - } - - @Override - public boolean retrySupported() { - for (Part part : parts) { - if (!part.content.retrySupported()) { - return false; - } - } - return true; - } - - @Override - public MultipartContent setMediaType(HttpMediaType mediaType) { - super.setMediaType(mediaType); - return this; - } - - /** Returns an unmodifiable view of the parts of the HTTP multipart request. */ - public final Collection getParts() { - return Collections.unmodifiableCollection(parts); - } - - /** - * Adds an HTTP multipart part. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public MultipartContent addPart(Part part) { - parts.add(Preconditions.checkNotNull(part)); - return this; - } - - /** - * Sets the parts of the HTTP multipart request. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public MultipartContent setParts(Collection parts) { - this.parts = new ArrayList(parts); - return this; - } - - /** - * Sets the HTTP content parts of the HTTP multipart request, where each part is assumed to have - * no HTTP headers and no encoding. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public MultipartContent setContentParts(Collection contentParts) { - this.parts = new ArrayList(contentParts.size()); - for (HttpContent contentPart : contentParts) { - addPart(new Part(contentPart)); - } - return this; - } - - /** Returns the boundary string to use. */ - public final String getBoundary() { - return getMediaType().getParameter("boundary"); - } - - /** - * Sets the boundary string to use. - * - *

- * Defaults to {@code "END_OF_PART"}. - *

- * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public MultipartContent setBoundary(String boundary) { - getMediaType().setParameter("boundary", Preconditions.checkNotNull(boundary)); - return this; - } - - /** - * Single part of a multi-part request. - * - *

- * Implementation is not thread-safe. - *

- */ - public static final class Part { - - /** HTTP content or {@code null} for none. */ - HttpContent content; - - /** HTTP headers or {@code null} for none. */ - HttpHeaders headers; - - /** HTTP encoding or {@code null} for none. */ - HttpEncoding encoding; - - public Part() { - this(null); - } - - /** - * @param content HTTP content or {@code null} for none - */ - public Part(HttpContent content) { - this(null, content); - } - - /** - * @param headers HTTP headers or {@code null} for none - * @param content HTTP content or {@code null} for none - */ - public Part(HttpHeaders headers, HttpContent content) { - setHeaders(headers); - setContent(content); - } - - /** Sets the HTTP content or {@code null} for none. */ - public Part setContent(HttpContent content) { - this.content = content; - return this; - } - - /** Returns the HTTP content or {@code null} for none. */ - public HttpContent getContent() { - return content; - } - - /** Sets the HTTP headers or {@code null} for none. */ - public Part setHeaders(HttpHeaders headers) { - this.headers = headers; - return this; - } - - /** Returns the HTTP headers or {@code null} for none. */ - public HttpHeaders getHeaders() { - return headers; - } - - /** Sets the HTTP encoding or {@code null} for none. */ - public Part setEncoding(HttpEncoding encoding) { - this.encoding = encoding; - return this; - } - - /** Returns the HTTP encoding or {@code null} for none. */ - public HttpEncoding getEncoding() { - return encoding; - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/UriTemplate.java b/src/autosaveworld/zlibs/com/google/api/client/http/UriTemplate.java deleted file mode 100644 index 98be4347..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/UriTemplate.java +++ /dev/null @@ -1,462 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import com.google.common.base.Splitter; - -import autosaveworld.zlibs.com.google.api.client.util.Data; -import autosaveworld.zlibs.com.google.api.client.util.FieldInfo; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.Types; -import autosaveworld.zlibs.com.google.api.client.util.escape.CharEscapers; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.ListIterator; -import java.util.Map; - -/** - * Expands URI Templates. - * - * This Class supports Level 1 templates and all Level 4 composite templates as described in: - * RFC 6570. - * - * Specifically, for the variables: - * var := "value" - * list := ["red", "green", "blue"] - * keys := [("semi", ";"),("dot", "."),("comma", ",")] - * - * The following templates results in the following expansions: - * {var} -> value - * {list} -> red,green,blue - * {list*} -> red,green,blue - * {keys} -> semi,%3B,dot,.,comma,%2C - * {keys*} -> semi=%3B,dot=.,comma=%2C - * {+list} -> red,green,blue - * {+list*} -> red,green,blue - * {+keys} -> semi,;,dot,.,comma,, - * {+keys*} -> semi=;,dot=.,comma=, - * {#list} -> #red,green,blue - * {#list*} -> #red,green,blue - * {#keys} -> #semi,;,dot,.,comma,, - * {#keys*} -> #semi=;,dot=.,comma=, - * X{.list} -> X.red,green,blue - * X{.list*} -> X.red.green.blue - * X{.keys} -> X.semi,%3B,dot,.,comma,%2C - * X{.keys*} -> X.semi=%3B.dot=..comma=%2C - * {/list} -> /red,green,blue - * {/list*} -> /red/green/blue - * {/keys} -> /semi,%3B,dot,.,comma,%2C - * {/keys*} -> /semi=%3B/dot=./comma=%2C - * {;list} -> ;list=red,green,blue - * {;list*} -> ;list=red;list=green;list=blue - * {;keys} -> ;keys=semi,%3B,dot,.,comma,%2C - * {;keys*} -> ;semi=%3B;dot=.;comma=%2C - * {?list} -> ?list=red,green,blue - * {?list*} -> ?list=red&list=green&list=blue - * {?keys} -> ?keys=semi,%3B,dot,.,comma,%2C - * {?keys*} -> ?semi=%3B&dot=.&comma=%2C - * {&list} -> &list=red,green,blue - * {&list*} -> &list=red&list=green&list=blue - * {&keys} -> &keys=semi,%3B,dot,.,comma,%2C - * {&keys*} -> &semi=%3B&dot=.&comma=%2C - * {?var,list} -> ?var=value&list=red,green,blue - * - * @since 1.6 - * @author Ravi Mistry - */ -public class UriTemplate { - - static final Map COMPOSITE_PREFIXES = - new HashMap(); - - static { - CompositeOutput.values(); - } - - private static final String COMPOSITE_NON_EXPLODE_JOINER = ","; - - /** - * Contains information on how to output a composite value. - */ - private enum CompositeOutput { - - /** Reserved expansion. */ - PLUS('+', "", ",", false, true), - - /** Fragment expansion. */ - HASH('#', "#", ",", false, true), - - /** Label expansion with dot-prefix. */ - DOT('.', ".", ".", false, false), - - /** Path segment expansion. */ - FORWARD_SLASH('/', "/", "/", false, false), - - /** Path segment parameter expansion. */ - SEMI_COLON(';', ";", ";", true, false), - - /** Form-style query expansion. */ - QUERY('?', "?", "&", true, false), - - /** Form-style query continuation. */ - AMP('&', "&", "&", true, false), - - /** Simple expansion. */ - SIMPLE(null, "", ",", false, false); - - private final Character propertyPrefix; - private final String outputPrefix; - private final String explodeJoiner; - private final boolean requiresVarAssignment; - private final boolean reservedExpansion; - - /** - * @param propertyPrefix The prefix of a parameter or {@code null} for none. In {+var} the - * prefix is '+' - * @param outputPrefix The string that should be prefixed to the expanded template. - * @param explodeJoiner The delimiter used to join composite values. - * @param requiresVarAssignment Denotes whether or not the expanded template should contain - * an assignment with the variable. - * @param reservedExpansion Reserved expansion allows pct-encoded triplets and characters in - * the reserved set. - */ - CompositeOutput(Character propertyPrefix, String outputPrefix, String explodeJoiner, - boolean requiresVarAssignment, boolean reservedExpansion) { - this.propertyPrefix = propertyPrefix; - this.outputPrefix = Preconditions.checkNotNull(outputPrefix); - this.explodeJoiner = Preconditions.checkNotNull(explodeJoiner); - this.requiresVarAssignment = requiresVarAssignment; - this.reservedExpansion = reservedExpansion; - if (propertyPrefix != null) { - COMPOSITE_PREFIXES.put(propertyPrefix, this); - } - } - - /** - * Returns the string that should be prefixed to the expanded template. - */ - String getOutputPrefix() { - return outputPrefix; - } - - /** - * Returns the delimiter used to join composite values. - */ - String getExplodeJoiner() { - return explodeJoiner; - } - - /** - * Returns whether or not the expanded template should contain an assignment with the variable. - */ - boolean requiresVarAssignment() { - return requiresVarAssignment; - } - - /** - * Returns the start index of the var name. If the variable contains a prefix the start index - * will be 1 else it will be 0. - */ - int getVarNameStartIndex() { - return propertyPrefix == null ? 0 : 1; - } - - /** - * Encodes the specified value. If reserved expansion is turned on then - * pct-encoded triplets and characters are allowed in the reserved set. - * - * @param value The string to be encoded. - * - * @return The encoded string. - */ - String getEncodedValue(String value) { - String encodedValue; - if (reservedExpansion) { - // Reserved expansion allows pct-encoded triplets and characters in the reserved set. - encodedValue = CharEscapers.escapeUriPath(value); - } else { - encodedValue = CharEscapers.escapeUri(value); - } - return encodedValue; - } - - boolean getReservedExpansion() { - return reservedExpansion; - } - } - - static CompositeOutput getCompositeOutput(String propertyName) { - CompositeOutput compositeOutput = COMPOSITE_PREFIXES.get(propertyName.charAt(0)); - return compositeOutput == null ? CompositeOutput.SIMPLE : compositeOutput; - } - - /** - * Constructs a new {@code Map} from an {@code Object}. - * - *

- * There are no null values in the returned map. - *

- */ - private static Map getMap(Object obj) { - // Using a LinkedHashMap to maintain the original order of insertions. This is done to help - // with handling unused parameters and makes testing easier as well. - Map map = new LinkedHashMap(); - for (Map.Entry entry : Data.mapOf(obj).entrySet()) { - Object value = entry.getValue(); - if (value != null && !Data.isNull(value)) { - map.put(entry.getKey(), value); - } - } - return map; - } - - /** - * Expands templates in a URI template that is relative to a base URL. - * - *

- * If the URI template starts with a "/" the raw path from the base URL is stripped out. If the - * URI template is a full URL then it is used instead of the base URL. - *

- * - *

- * Supports Level 1 templates and all Level 4 composite templates as described in: - * RFC 6570. - *

- * - * @param baseUrl The base URL which the URI component is relative to. - * @param uriTemplate URI component. It may contain one or more sequences of the form "{name}", - * where "name" must be a key in variableMap. - * @param parameters an object with parameters designated by Key annotations. If the template has - * no variable references, parameters may be {@code null}. - * @param addUnusedParamsAsQueryParams If true then parameters that do not match the template are - * appended to the expanded template as query parameters. - * @return The expanded template - * @since 1.7 - */ - public static String expand(String baseUrl, String uriTemplate, Object parameters, - boolean addUnusedParamsAsQueryParams) { - String pathUri; - if (uriTemplate.startsWith("/")) { - // Remove the base path from the base URL. - GenericUrl url = new GenericUrl(baseUrl); - url.setRawPath(null); - pathUri = url.build() + uriTemplate; - } else if (uriTemplate.startsWith("http://") || uriTemplate.startsWith("https://")) { - pathUri = uriTemplate; - } else { - pathUri = baseUrl + uriTemplate; - } - return expand(pathUri, parameters, addUnusedParamsAsQueryParams); - } - - /** - * Expands templates in a URI. - * - *

- * Supports Level 1 templates and all Level 4 composite templates as described in: - * RFC 6570. - *

- * - * @param pathUri URI component. It may contain one or more sequences of the form "{name}", where - * "name" must be a key in variableMap - * @param parameters an object with parameters designated by Key annotations. If the template has - * no variable references, parameters may be {@code null}. - * @param addUnusedParamsAsQueryParams If true then parameters that do not match the template are - * appended to the expanded template as query parameters. - * @return The expanded template - * @since 1.6 - */ - public static String expand(String pathUri, Object parameters, - boolean addUnusedParamsAsQueryParams) { - Map variableMap = getMap(parameters); - StringBuilder pathBuf = new StringBuilder(); - int cur = 0; - int length = pathUri.length(); - while (cur < length) { - int next = pathUri.indexOf('{', cur); - if (next == -1) { - if (cur == 0 && !addUnusedParamsAsQueryParams) { - // No expansions exist and we do not need to add any query parameters. - return pathUri; - } - pathBuf.append(pathUri.substring(cur)); - break; - } - pathBuf.append(pathUri.substring(cur, next)); - int close = pathUri.indexOf('}', next + 2); - cur = close + 1; - - String templates = pathUri.substring(next + 1, close); - CompositeOutput compositeOutput = getCompositeOutput(templates); - ListIterator templateIterator = - Splitter.on(',').splitToList(templates).listIterator(); - boolean isFirstParameter = true; - while (templateIterator.hasNext()) { - String template = templateIterator.next(); - boolean containsExplodeModifier = template.endsWith("*"); - - int varNameStartIndex = templateIterator.nextIndex() == 1 - ? compositeOutput.getVarNameStartIndex() : 0; - int varNameEndIndex = template.length(); - if (containsExplodeModifier) { - // The expression contains an explode modifier '*' at the end, update end index. - varNameEndIndex = varNameEndIndex - 1; - } - // Now get varName devoid of any prefixes and explode modifiers. - String varName = template.substring(varNameStartIndex, varNameEndIndex); - - Object value = variableMap.remove(varName); - if (value == null) { - // The value for this variable is undefined. continue with the next template. - continue; - } - if (!isFirstParameter) { - pathBuf.append(compositeOutput.getExplodeJoiner()); - } else { - pathBuf.append(compositeOutput.getOutputPrefix()); - isFirstParameter = false; - } - if (value instanceof Iterator) { - // Get the list property value. - Iterator iterator = (Iterator) value; - value = getListPropertyValue(varName, iterator, containsExplodeModifier, compositeOutput); - } else if (value instanceof Iterable || value.getClass().isArray()) { - // Get the list property value. - Iterator iterator = Types.iterableOf(value).iterator(); - value = getListPropertyValue(varName, iterator, containsExplodeModifier, compositeOutput); - } else if (value.getClass().isEnum()) { - String name = FieldInfo.of((Enum) value).getName(); - if (name != null) { - if (compositeOutput.requiresVarAssignment()) { - value = String.format("%s=%s", varName, value); - } - value = CharEscapers.escapeUriPath(value.toString()); - } - } else if (!Data.isValueOfPrimitiveType(value)) { - // Parse the value as a key/value map. - Map map = getMap(value); - value = getMapPropertyValue(varName, map, containsExplodeModifier, compositeOutput); - } else { - // For everything else... - if (compositeOutput.requiresVarAssignment()) { - value = String.format("%s=%s", varName, value); - } - if (compositeOutput.getReservedExpansion()) { - value = CharEscapers.escapeUriPathWithoutReserved(value.toString()); - } else { - value = CharEscapers.escapeUriPath(value.toString()); - } - } - pathBuf.append(value); - } - } - if (addUnusedParamsAsQueryParams) { - // Add the parameters remaining in the variableMap as query parameters. - GenericUrl.addQueryParams(variableMap.entrySet(), pathBuf); - } - return pathBuf.toString(); - } - - /** - * Expand the template of a composite list property. - * Eg: If d := ["red", "green", "blue"] - * then {/d*} is expanded to "/red/green/blue" - * - * @param varName The name of the variable the value corresponds to. Eg: "d" - * @param iterator The iterator over list values. Eg: ["red", "green", "blue"] - * @param containsExplodeModifier Set to true if the template contains the explode modifier "*" - * @param compositeOutput An instance of CompositeOutput. Contains information on how the - * expansion should be done - * @return The expanded list template - * @throws IllegalArgumentException if the required list path parameter is empty - */ - private static String getListPropertyValue(String varName, Iterator iterator, - boolean containsExplodeModifier, CompositeOutput compositeOutput) { - if (!iterator.hasNext()) { - return ""; - } - StringBuilder retBuf = new StringBuilder(); - String joiner; - if (containsExplodeModifier) { - joiner = compositeOutput.getExplodeJoiner(); - } else { - joiner = COMPOSITE_NON_EXPLODE_JOINER; - if (compositeOutput.requiresVarAssignment()) { - retBuf.append(CharEscapers.escapeUriPath(varName)); - retBuf.append("="); - } - } - while (iterator.hasNext()) { - if (containsExplodeModifier && compositeOutput.requiresVarAssignment()) { - retBuf.append(CharEscapers.escapeUriPath(varName)); - retBuf.append("="); - } - retBuf.append(compositeOutput.getEncodedValue(iterator.next().toString())); - if (iterator.hasNext()) { - retBuf.append(joiner); - } - } - return retBuf.toString(); - } - - /** - * Expand the template of a composite map property. - * Eg: If d := [("semi", ";"),("dot", "."),("comma", ",")] - * then {/d*} is expanded to "/semi=%3B/dot=./comma=%2C" - * - * @param varName The name of the variable the value corresponds to. Eg: "d" - * @param map The map property value. Eg: [("semi", ";"),("dot", "."),("comma", ",")] - * @param containsExplodeModifier Set to true if the template contains the explode modifier "*" - * @param compositeOutput An instance of CompositeOutput. Contains information on how the - * expansion should be done - * @return The expanded map template - * @throws IllegalArgumentException if the required list path parameter is map - */ - private static String getMapPropertyValue(String varName, Map map, - boolean containsExplodeModifier, CompositeOutput compositeOutput) { - if (map.isEmpty()) { - return ""; - } - StringBuilder retBuf = new StringBuilder(); - String joiner; - String mapElementsJoiner; - if (containsExplodeModifier) { - joiner = compositeOutput.getExplodeJoiner(); - mapElementsJoiner = "="; - } else { - joiner = COMPOSITE_NON_EXPLODE_JOINER; - mapElementsJoiner = COMPOSITE_NON_EXPLODE_JOINER; - if (compositeOutput.requiresVarAssignment()) { - retBuf.append(CharEscapers.escapeUriPath(varName)); - retBuf.append("="); - } - } - for (Iterator> mapIterator = map.entrySet().iterator(); - mapIterator.hasNext();) { - Map.Entry entry = mapIterator.next(); - String encodedKey = compositeOutput.getEncodedValue(entry.getKey()); - String encodedValue = compositeOutput.getEncodedValue(entry.getValue().toString()); - retBuf.append(encodedKey); - retBuf.append(mapElementsJoiner); - retBuf.append(encodedValue); - if (mapIterator.hasNext()) { - retBuf.append(joiner); - } - } - return retBuf.toString(); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/UrlEncodedContent.java b/src/autosaveworld/zlibs/com/google/api/client/http/UrlEncodedContent.java deleted file mode 100644 index 07292b34..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/UrlEncodedContent.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.BufferedWriter; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.util.HashMap; -import java.util.Map; - -import autosaveworld.zlibs.com.google.api.client.util.Data; -import autosaveworld.zlibs.com.google.api.client.util.FieldInfo; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.Types; -import autosaveworld.zlibs.com.google.api.client.util.escape.CharEscapers; - -/** - * Implements support for HTTP form content encoding serialization of type - * {@code application/x-www-form-urlencoded} as specified in the HTML 4.0 Specification. - * - *

- * Sample usage: - *

- * - *
-  static void setContent(HttpRequest request, Object item) {
-    request.setContent(new UrlEncodedContent(item));
-  }
- * 
- * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.0 - * @author Yaniv Inbar - */ -public class UrlEncodedContent extends AbstractHttpContent { - - /** Key name/value data. */ - private Object data; - - /** - * @param data key name/value data - */ - public UrlEncodedContent(Object data) { - super(UrlEncodedParser.MEDIA_TYPE); - setData(data); - } - - public void writeTo(OutputStream out) throws IOException { - Writer writer = new BufferedWriter(new OutputStreamWriter(out, getCharset())); - boolean first = true; - for (Map.Entry nameValueEntry : Data.mapOf(data).entrySet()) { - Object value = nameValueEntry.getValue(); - if (value != null) { - String name = CharEscapers.escapeUri(nameValueEntry.getKey()); - Class valueClass = value.getClass(); - if (value instanceof Iterable || valueClass.isArray()) { - for (Object repeatedValue : Types.iterableOf(value)) { - first = appendParam(first, writer, name, repeatedValue); - } - } else { - first = appendParam(first, writer, name, value); - } - } - } - writer.flush(); - } - - @Override - public UrlEncodedContent setMediaType(HttpMediaType mediaType) { - super.setMediaType(mediaType); - return this; - } - - /** - * Returns the key name/value data or {@code null} for none. - * - * @since 1.5 - */ - public final Object getData() { - return data; - } - - /** - * Sets the key name/value data. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.5 - */ - public UrlEncodedContent setData(Object data) { - this.data = Preconditions.checkNotNull(data); - return this; - } - - /** - * Returns the URL-encoded content of the given HTTP request, or if none return and set as content - * a new instance of {@link UrlEncodedContent} (whose {@link #getData()} is an implementation of - * {@link Map}). - * - * @param request HTTP request - * @return URL-encoded content - * @throws ClassCastException if the HTTP request has a content defined that is not - * {@link UrlEncodedContent} - * @since 1.7 - */ - public static UrlEncodedContent getContent(HttpRequest request) { - HttpContent content = request.getContent(); - if (content != null) { - return (UrlEncodedContent) content; - } - UrlEncodedContent result = new UrlEncodedContent(new HashMap()); - request.setContent(result); - return result; - } - - private static boolean appendParam(boolean first, Writer writer, String name, Object value) - throws IOException { - // ignore nulls - if (value == null || Data.isNull(value)) { - return first; - } - // append value - if (first) { - first = false; - } else { - writer.write("&"); - } - writer.write(name); - String stringValue = CharEscapers.escapeUri( - value instanceof Enum ? FieldInfo.of((Enum) value).getName() : value.toString()); - if (stringValue.length() != 0) { - writer.write("="); - writer.write(stringValue); - } - return first; - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/UrlEncodedParser.java b/src/autosaveworld/zlibs/com/google/api/client/http/UrlEncodedParser.java deleted file mode 100644 index d6b887a1..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/UrlEncodedParser.java +++ /dev/null @@ -1,243 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; -import java.lang.reflect.Type; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Map; - -import autosaveworld.zlibs.com.google.api.client.util.ArrayValueMap; -import autosaveworld.zlibs.com.google.api.client.util.Charsets; -import autosaveworld.zlibs.com.google.api.client.util.ClassInfo; -import autosaveworld.zlibs.com.google.api.client.util.Data; -import autosaveworld.zlibs.com.google.api.client.util.FieldInfo; -import autosaveworld.zlibs.com.google.api.client.util.GenericData; -import autosaveworld.zlibs.com.google.api.client.util.ObjectParser; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.Throwables; -import autosaveworld.zlibs.com.google.api.client.util.Types; -import autosaveworld.zlibs.com.google.api.client.util.escape.CharEscapers; - -/** - * Implements support for HTTP form content encoding parsing of type - * {@code application/x-www-form-urlencoded} as specified in the HTML 4.0 - * Specification. - * - *

- * Implementation is thread-safe. - *

- * - *

- * The data is parsed using {@link #parse(String, Object)}. - *

- * - *

- * Sample usage: - *

- * - *
-   static void setParser(HttpTransport transport) {
-     transport.addParser(new UrlEncodedParser());
-   }
- * 
- * - * @since 1.0 - * @author Yaniv Inbar - */ -public class UrlEncodedParser implements ObjectParser { - - /** {@code "application/x-www-form-urlencoded"} content type. */ - public static final String CONTENT_TYPE = "application/x-www-form-urlencoded"; - - /** - * {@code "application/x-www-form-urlencoded"} media type with UTF-8 encoding. - * - * @since 1.13 - */ - public static final String MEDIA_TYPE = - new HttpMediaType(UrlEncodedParser.CONTENT_TYPE).setCharsetParameter(Charsets.UTF_8).build(); - - /** - * Parses the given URL-encoded content into the given data object of data key name/value pairs - * using {@link #parse(Reader, Object)}. - * - * @param content URL-encoded content or {@code null} to ignore content - * @param data data key name/value pairs - */ - public static void parse(String content, Object data) { - if (content == null) { - return; - } - try { - parse(new StringReader(content), data); - } catch (IOException exception) { - // I/O exception not expected on a string - throw Throwables.propagate(exception); - } - } - - /** - * Parses the given URL-encoded content into the given data object of data key name/value pairs, - * including support for repeating data key names. - * - *

- * Declared fields of a "primitive" type (as defined by {@link Data#isPrimitive(Type)} are parsed - * using {@link Data#parsePrimitiveValue(Type, String)} where the {@link Class} parameter is the - * declared field class. Declared fields of type {@link Collection} are used to support repeating - * data key names, so each member of the collection is an additional data key value. They are - * parsed the same as "primitive" fields, except that the generic type parameter of the collection - * is used as the {@link Class} parameter. - *

- * - *

- * If there is no declared field for an input parameter name, it will be ignored unless the input - * {@code data} parameter is a {@link Map}. If it is a map, the parameter value will be stored - * either as a string, or as a {@link ArrayList}<String> in the case of repeated parameters. - *

- * - * @param reader URL-encoded reader - * @param data data key name/value pairs - * - * @since 1.14 - */ - public static void parse(Reader reader, Object data) throws IOException { - Class clazz = data.getClass(); - ClassInfo classInfo = ClassInfo.of(clazz); - List context = Arrays.asList(clazz); - GenericData genericData = GenericData.class.isAssignableFrom(clazz) ? (GenericData) data : null; - @SuppressWarnings("unchecked") - Map map = Map.class.isAssignableFrom(clazz) ? (Map) data : null; - ArrayValueMap arrayValueMap = new ArrayValueMap(data); - StringWriter nameWriter = new StringWriter(); - StringWriter valueWriter = new StringWriter(); - boolean readingName = true; - mainLoop: while (true) { - int read = reader.read(); - switch (read) { - case -1: - // falls through - case '&': - // parse name/value pair - String name = CharEscapers.decodeUri(nameWriter.toString()); - if (name.length() != 0) { - String stringValue = CharEscapers.decodeUri(valueWriter.toString()); - // get the field from the type information - FieldInfo fieldInfo = classInfo.getFieldInfo(name); - if (fieldInfo != null) { - Type type = - Data.resolveWildcardTypeOrTypeVariable(context, fieldInfo.getGenericType()); - // type is now class, parameterized type, or generic array type - if (Types.isArray(type)) { - // array that can handle repeating values - Class rawArrayComponentType = - Types.getRawArrayComponentType(context, Types.getArrayComponentType(type)); - arrayValueMap.put(fieldInfo.getField(), rawArrayComponentType, - parseValue(rawArrayComponentType, context, stringValue)); - } else if (Types.isAssignableToOrFrom( - Types.getRawArrayComponentType(context, type), Iterable.class)) { - // iterable that can handle repeating values - @SuppressWarnings("unchecked") - Collection collection = (Collection) fieldInfo.getValue(data); - if (collection == null) { - collection = Data.newCollectionInstance(type); - fieldInfo.setValue(data, collection); - } - Type subFieldType = type == Object.class ? null : Types.getIterableParameter(type); - collection.add(parseValue(subFieldType, context, stringValue)); - } else { - // parse into a field that assumes it is a single value - fieldInfo.setValue(data, parseValue(type, context, stringValue)); - } - } else if (map != null) { - // parse into a map: store as an ArrayList of values - @SuppressWarnings("unchecked") - ArrayList listValue = (ArrayList) map.get(name); - if (listValue == null) { - listValue = new ArrayList(); - if (genericData != null) { - genericData.set(name, listValue); - } else { - map.put(name, listValue); - } - } - listValue.add(stringValue); - } - } - // ready to read next name/value pair - readingName = true; - nameWriter = new StringWriter(); - valueWriter = new StringWriter(); - if (read == -1) { - break mainLoop; - } - break; - case '=': - // finished with name, now read value - readingName = false; - break; - default: - // read one more character - if (readingName) { - nameWriter.write(read); - } else { - valueWriter.write(read); - } - } - } - arrayValueMap.setValues(); - } - - private static Object parseValue(Type valueType, List context, String value) { - Type resolved = Data.resolveWildcardTypeOrTypeVariable(context, valueType); - return Data.parsePrimitiveValue(resolved, value); - } - - public T parseAndClose(InputStream in, Charset charset, Class dataClass) - throws IOException { - InputStreamReader r = new InputStreamReader(in, charset); - return parseAndClose(r, dataClass); - } - - public Object parseAndClose(InputStream in, Charset charset, Type dataType) throws IOException { - InputStreamReader r = new InputStreamReader(in, charset); - return parseAndClose(r, dataType); - } - - @SuppressWarnings("unchecked") - public T parseAndClose(Reader reader, Class dataClass) throws IOException { - return (T) parseAndClose(reader, (Type) dataClass); - } - - public Object parseAndClose(Reader reader, Type dataType) throws IOException { - Preconditions.checkArgument( - dataType instanceof Class, "dataType has to be of type Class"); - - Object newInstance = Types.newInstance((Class) dataType); - parse(new BufferedReader(reader), newInstance); - return newInstance; - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/javanet/ConnectionFactory.java b/src/autosaveworld/zlibs/com/google/api/client/http/javanet/ConnectionFactory.java deleted file mode 100644 index cb0058a6..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/javanet/ConnectionFactory.java +++ /dev/null @@ -1,21 +0,0 @@ -package autosaveworld.zlibs.com.google.api.client.http.javanet; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URL; - -/** - * Given a {@link URL} instance, produces an {@link HttpURLConnection}. - */ -public interface ConnectionFactory { - - /** - * Creates a new {@link HttpURLConnection} from the given {@code url}. - * - * @param url the URL to which the conneciton will be made - * @return the created connection object, which will still be in the pre-connected state - * @throws IOException if there was a problem producing the connection - * @throws ClassCastException if the URL is not for an HTTP endpoint - */ - HttpURLConnection openConnection(URL url) throws IOException, ClassCastException; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/javanet/DefaultConnectionFactory.java b/src/autosaveworld/zlibs/com/google/api/client/http/javanet/DefaultConnectionFactory.java deleted file mode 100644 index 5df9c6b1..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/javanet/DefaultConnectionFactory.java +++ /dev/null @@ -1,33 +0,0 @@ -package autosaveworld.zlibs.com.google.api.client.http.javanet; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.Proxy; -import java.net.URL; - -/** - * Default implementation of {@link ConnectionFactory}, which simply attempts to open the connection - * with an optional {@link Proxy}. - */ -public class DefaultConnectionFactory implements ConnectionFactory { - - private final Proxy proxy; - - public DefaultConnectionFactory() { - this(null); - } - - /** - * @param proxy HTTP proxy or {@code null} to use the proxy settings from - * system properties - */ - public DefaultConnectionFactory(Proxy proxy) { - this.proxy = proxy; - } - - @Override - public HttpURLConnection openConnection(URL url) throws IOException { - return (HttpURLConnection) (proxy == null ? url.openConnection() : url.openConnection(proxy)); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/javanet/NetHttpRequest.java b/src/autosaveworld/zlibs/com/google/api/client/http/javanet/NetHttpRequest.java deleted file mode 100644 index eaa7398f..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/javanet/NetHttpRequest.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http.javanet; - -import java.io.IOException; -import java.io.OutputStream; -import java.net.HttpURLConnection; - -import autosaveworld.zlibs.com.google.api.client.http.LowLevelHttpRequest; -import autosaveworld.zlibs.com.google.api.client.http.LowLevelHttpResponse; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * @author Yaniv Inbar - */ -final class NetHttpRequest extends LowLevelHttpRequest { - - private final HttpURLConnection connection; - - /** - * @param connection HTTP URL connection - */ - NetHttpRequest(HttpURLConnection connection) { - this.connection = connection; - connection.setInstanceFollowRedirects(false); - } - - @Override - public void addHeader(String name, String value) { - connection.addRequestProperty(name, value); - } - - @Override - public void setTimeout(int connectTimeout, int readTimeout) { - connection.setReadTimeout(readTimeout); - connection.setConnectTimeout(connectTimeout); - } - - @Override - public LowLevelHttpResponse execute() throws IOException { - HttpURLConnection connection = this.connection; - // write content - if (getStreamingContent() != null) { - String contentType = getContentType(); - if (contentType != null) { - addHeader("Content-Type", contentType); - } - String contentEncoding = getContentEncoding(); - if (contentEncoding != null) { - addHeader("Content-Encoding", contentEncoding); - } - long contentLength = getContentLength(); - if (contentLength >= 0) { - addHeader("Content-Length", Long.toString(contentLength)); - } - String requestMethod = connection.getRequestMethod(); - if ("POST".equals(requestMethod) || "PUT".equals(requestMethod)) { - connection.setDoOutput(true); - // see http://developer.android.com/reference/java/net/HttpURLConnection.html - if (contentLength >= 0 && contentLength <= Integer.MAX_VALUE) { - connection.setFixedLengthStreamingMode((int) contentLength); - } else { - connection.setChunkedStreamingMode(0); - } - OutputStream out = connection.getOutputStream(); - try { - getStreamingContent().writeTo(out); - } finally { - out.close(); - } - } else { - // cannot call setDoOutput(true) because it would change a GET method to POST - // for HEAD, OPTIONS, DELETE, or TRACE it would throw an exceptions - Preconditions.checkArgument( - contentLength == 0, "%s with non-zero content length is not supported", requestMethod); - } - } - // connect - boolean successfulConnection = false; - try { - connection.connect(); - NetHttpResponse response = new NetHttpResponse(connection); - successfulConnection = true; - return response; - } finally { - if (!successfulConnection) { - connection.disconnect(); - } - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/javanet/NetHttpResponse.java b/src/autosaveworld/zlibs/com/google/api/client/http/javanet/NetHttpResponse.java deleted file mode 100644 index 04cda9fc..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/javanet/NetHttpResponse.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http.javanet; - -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import autosaveworld.zlibs.com.google.api.client.http.LowLevelHttpResponse; - -final class NetHttpResponse extends LowLevelHttpResponse { - - private final HttpURLConnection connection; - private final int responseCode; - private final String responseMessage; - private final ArrayList headerNames = new ArrayList(); - private final ArrayList headerValues = new ArrayList(); - - NetHttpResponse(HttpURLConnection connection) throws IOException { - this.connection = connection; - int responseCode = connection.getResponseCode(); - this.responseCode = responseCode == -1 ? 0 : responseCode; - responseMessage = connection.getResponseMessage(); - List headerNames = this.headerNames; - List headerValues = this.headerValues; - for (Map.Entry> entry : connection.getHeaderFields().entrySet()) { - String key = entry.getKey(); - if (key != null) { - for (String value : entry.getValue()) { - if (value != null) { - headerNames.add(key); - headerValues.add(value); - } - } - } - } - } - - @Override - public int getStatusCode() { - return responseCode; - } - - /** - * {@inheritDoc} - * - *

- * Returns {@link HttpURLConnection#getInputStream} when it doesn't throw {@link IOException}, - * otherwise it returns {@link HttpURLConnection#getErrorStream}. - *

- * - *

- * Upgrade warning: in prior version 1.16 {@link #getContent()} returned - * {@link HttpURLConnection#getInputStream} only when the status code was successful. Starting - * with version 1.17 it returns {@link HttpURLConnection#getInputStream} when it doesn't throw - * {@link IOException}, otherwise it returns {@link HttpURLConnection#getErrorStream} - *

- * - *

- * Upgrade warning: in versions prior to 1.20 {@link #getContent()} returned - * {@link HttpURLConnection#getInputStream()} or {@link HttpURLConnection#getErrorStream()}, both - * of which silently returned -1 for read() calls when the connection got closed in the middle - * of receiving a response. This is highly likely a bug from JDK's {@link HttpURLConnection}. - * Since version 1.20, the bytes read off the wire will be checked and an {@link IOException} will - * be thrown if the response is not fully delivered when the connection is closed by server for - * whatever reason, e.g., server restarts. Note though that this is a best-effort check: when the - * response is chunk encoded, we have to rely on the underlying HTTP library to behave correctly. - *

- */ - @Override - public InputStream getContent() throws IOException { - InputStream in = null; - try { - in = connection.getInputStream(); - } catch (IOException ioe) { - in = connection.getErrorStream(); - } - return in == null ? null : new SizeValidatingInputStream(in); - } - - @Override - public String getContentEncoding() { - return connection.getContentEncoding(); - } - - @Override - public long getContentLength() { - String string = connection.getHeaderField("Content-Length"); - return string == null ? -1 : Long.parseLong(string); - } - - @Override - public String getContentType() { - return connection.getHeaderField("Content-Type"); - } - - @Override - public String getReasonPhrase() { - return responseMessage; - } - - @Override - public String getStatusLine() { - String result = connection.getHeaderField(0); - return result != null && result.startsWith("HTTP/1.") ? result : null; - } - - @Override - public int getHeaderCount() { - return headerNames.size(); - } - - @Override - public String getHeaderName(int index) { - return headerNames.get(index); - } - - @Override - public String getHeaderValue(int index) { - return headerValues.get(index); - } - - /** - * Closes the connection to the HTTP server. - * - * @since 1.4 - */ - @Override - public void disconnect() { - connection.disconnect(); - } - - /** - * A wrapper arround the base {@link InputStream} that validates EOF returned by the read calls. - * - * @since 1.20 - */ - private final class SizeValidatingInputStream extends FilterInputStream { - - private long bytesRead = 0; - - public SizeValidatingInputStream(InputStream in) { - super(in); - } - - /** - * java.io.InputStream#read(byte[], int, int) swallows IOException thrown from read() so we have - * to override it. - * @see "http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/io/InputStream.java#185" - */ - @Override - public int read(byte[] b, int off, int len) throws IOException { - int n = in.read(b, off, len); - if (n == -1) { - throwIfFalseEOF(); - } else { - bytesRead += n; - } - return n; - } - - @Override - public int read() throws IOException { - int n = in.read(); - if (n == -1) { - throwIfFalseEOF(); - } else { - bytesRead++; - } - return n; - } - - // Throws an IOException if gets an EOF in the middle of a response. - private void throwIfFalseEOF() throws IOException { - long contentLength = getContentLength(); - if (contentLength == -1) { - // If a Content-Length header is missing, there's nothing we can do. - return; - } - // According to RFC2616, message-body is prohibited in responses to certain requests, e.g., - // HEAD. Nevertheless an entity-header (possibly with non-zero Content-Length) may be present. - // Thus we exclude the case where bytesRead == 0. - // - // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.4 for details. - if (bytesRead != 0 && bytesRead < contentLength) { - throw new IOException("Connection closed prematurely: bytesRead = " + bytesRead - + ", Content-Length = " + contentLength); - } - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/javanet/NetHttpTransport.java b/src/autosaveworld/zlibs/com/google/api/client/http/javanet/NetHttpTransport.java deleted file mode 100644 index 10e8cdaa..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/javanet/NetHttpTransport.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http.javanet; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.Arrays; - -import autosaveworld.zlibs.com.google.api.client.http.HttpMethods; -import autosaveworld.zlibs.com.google.api.client.http.HttpTransport; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * Thread-safe HTTP low-level transport based on the {@code java.net} package. - * - *

- * Users should consider modifying the keep alive property on {@link NetHttpTransport} to control - * whether the socket should be returned to a pool of connected sockets. More information is - * available here. - *

- * - *

- * We honor the default global caching behavior. To change the default behavior use - * {@link HttpURLConnection#setDefaultUseCaches(boolean)}. - *

- * - *

- * Implementation is thread-safe. For maximum efficiency, applications should use a single - * globally-shared instance of the HTTP transport. - *

- * - * @since 1.0 - * @author Yaniv Inbar - */ -public final class NetHttpTransport extends HttpTransport { - - /** - * All valid request methods as specified in {@link HttpURLConnection#setRequestMethod}, sorted in - * ascending alphabetical order. - */ - private static final String[] SUPPORTED_METHODS = {HttpMethods.DELETE, - HttpMethods.GET, - HttpMethods.HEAD, - HttpMethods.OPTIONS, - HttpMethods.POST, - HttpMethods.PUT, - HttpMethods.TRACE}; - static { - Arrays.sort(SUPPORTED_METHODS); - } - - /** Factory to produce connections from {@link URL}s */ - private final ConnectionFactory connectionFactory; - - /** - * Constructor with the default behavior. - * - *

- * Instead use {@link Builder} to modify behavior. - *

- */ - public NetHttpTransport() { - this(null); - } - - /** - * @param connectionFactory factory to produce connections from {@link URL}s; if {@code null} then - * {@link DefaultConnectionFactory} is used - * @param sslSocketFactory SSL socket factory or {@code null} for the default - * @param hostnameVerifier host name verifier or {@code null} for the default - * @since 1.20 - */ - public NetHttpTransport(ConnectionFactory connectionFactory) { - this.connectionFactory = connectionFactory == null ? new DefaultConnectionFactory() : connectionFactory; - } - - @Override - public boolean supportsMethod(String method) { - return Arrays.binarySearch(SUPPORTED_METHODS, method) >= 0; - } - - @Override - protected NetHttpRequest buildRequest(String method, String url) throws IOException { - Preconditions.checkArgument(supportsMethod(method), "HTTP method %s not supported", method); - // connection with proxy settings - URL connUrl = new URL(url); - HttpURLConnection connection = connectionFactory.openConnection(connUrl); - connection.setRequestMethod(method); - return new NetHttpRequest(connection); - } - -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/http/json/JsonHttpContent.java b/src/autosaveworld/zlibs/com/google/api/client/http/json/JsonHttpContent.java deleted file mode 100644 index fdbb5936..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/http/json/JsonHttpContent.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.http.json; - -import java.io.IOException; -import java.io.OutputStream; - -import autosaveworld.zlibs.com.google.api.client.http.AbstractHttpContent; -import autosaveworld.zlibs.com.google.api.client.http.HttpMediaType; -import autosaveworld.zlibs.com.google.api.client.json.Json; -import autosaveworld.zlibs.com.google.api.client.json.JsonFactory; -import autosaveworld.zlibs.com.google.api.client.json.JsonGenerator; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * Serializes JSON HTTP content based on the data key/value mapping object for an item. - * - *

- * Sample usage: - *

- * - *
- *
-  static void setContent(HttpRequest request, Object data) {
-    request.setContent(new JsonHttpContent(new JacksonFactory(), data));
-  }
- * 
- * 
- * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.0 - * @author Yaniv Inbar - */ -public class JsonHttpContent extends AbstractHttpContent { - // TODO(yanivi): ability to annotate fields as only needed for POST? - - /** JSON key name/value data. */ - private final Object data; - - /** JSON factory. */ - private final JsonFactory jsonFactory; - - /** Wrapper key for the JSON content or {@code null} for none. */ - private String wrapperKey; - - /** - * @param jsonFactory JSON factory to use - * @param data JSON key name/value data - * @since 1.5 - */ - public JsonHttpContent(JsonFactory jsonFactory, Object data) { - super(Json.MEDIA_TYPE); - this.jsonFactory = Preconditions.checkNotNull(jsonFactory); - this.data = Preconditions.checkNotNull(data); - } - - public void writeTo(OutputStream out) throws IOException { - JsonGenerator generator = jsonFactory.createJsonGenerator(out, getCharset()); - if (wrapperKey != null) { - generator.writeStartObject(); - generator.writeFieldName(wrapperKey); - } - generator.serialize(data); - if (wrapperKey != null) { - generator.writeEndObject(); - } - generator.flush(); - } - - @Override - public JsonHttpContent setMediaType(HttpMediaType mediaType) { - super.setMediaType(mediaType); - return this; - } - - /** - * Returns the JSON key name/value data. - * - * @since 1.5 - */ - public final Object getData() { - return data; - } - - /** - * Returns the JSON factory. - * - * @since 1.5 - */ - public final JsonFactory getJsonFactory() { - return jsonFactory; - } - - /** - * Returns the wrapper key for the JSON content or {@code null} for none. - * - * @since 1.14 - */ - public final String getWrapperKey() { - return wrapperKey; - } - - /** - * Sets the wrapper key for the JSON content or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.14 - */ - public JsonHttpContent setWrapperKey(String wrapperKey) { - this.wrapperKey = wrapperKey; - return this; - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/json/CustomizeJsonParser.java b/src/autosaveworld/zlibs/com/google/api/client/json/CustomizeJsonParser.java deleted file mode 100644 index 95b45589..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/json/CustomizeJsonParser.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.json; - -import java.lang.reflect.Field; -import java.util.Collection; - -import autosaveworld.zlibs.com.google.api.client.util.Beta; - -/** - * {@link Beta}
- * Customizes the behavior of a JSON parser. - * - *

- * All methods have a default trivial implementation, so subclasses need only implement the methods - * whose behavior needs customization. - *

- * - *

- * Implementation has no fields and therefore thread-safe, but sub-classes are not necessarily - * thread-safe. - *

- * - * @since 1.0 - * @author Yaniv Inbar - */ -@Beta -public class CustomizeJsonParser { - - /** - * Returns whether to stop parsing at the given key of the given context object. - */ - public boolean stopAt(Object context, String key) { - return false; - } - - /** - * Called when the given unrecognized key is encountered in the given context object. - */ - public void handleUnrecognizedKey(Object context, String key) { - } - - /** - * Returns a new instance value for the given field in the given context object for a JSON array - * or {@code null} for the default behavior. - */ - public Collection newInstanceForArray(Object context, Field field) { - return null; - } - - /** - * Returns a new instance value for the given field class in the given context object for JSON - * Object or {@code null} for the default behavior. - */ - public Object newInstanceForObject(Object context, Class fieldClass) { - return null; - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/json/GenericJson.java b/src/autosaveworld/zlibs/com/google/api/client/json/GenericJson.java deleted file mode 100644 index d4cb9a4a..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/json/GenericJson.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.json; - -import java.io.IOException; -import java.util.concurrent.ConcurrentMap; - -import autosaveworld.zlibs.com.google.api.client.util.GenericData; -import autosaveworld.zlibs.com.google.api.client.util.Key; -import autosaveworld.zlibs.com.google.api.client.util.Throwables; - -/** - * Generic JSON data that stores all unknown key name/value pairs. - * - *

- * Subclasses can declare fields for known data keys using the {@link Key} annotation. Each field - * can be of any visibility (private, package private, protected, or public) and must not be static. - * {@code null} unknown data key names are not allowed, but {@code null} data values are allowed. - * - *

- * Implementation is not thread-safe. For a thread-safe choice instead use an implementation of - * {@link ConcurrentMap}. - *

- * - * @since 1.0 - * @author Yaniv Inbar - */ -public class GenericJson extends GenericData implements Cloneable { - - /** JSON factory or {@code null} for none. */ - private JsonFactory jsonFactory; - - /** - * Returns the JSON factory or {@code null} for none. - * - * @since 1.6 - */ - public final JsonFactory getFactory() { - return jsonFactory; - } - - /** - * Sets the JSON factory or {@code null} for none. - * - * @since 1.6 - */ - public final void setFactory(JsonFactory factory) { - this.jsonFactory = factory; - } - - @Override - public String toString() { - if (jsonFactory != null) { - try { - return jsonFactory.toString(this); - } catch (IOException e) { - throw Throwables.propagate(e); - } - } - return super.toString(); - } - - /** - * Returns a pretty-printed serialized JSON string representation or {@link #toString()} if - * {@link #getFactory()} is {@code null}. - * - * @since 1.6 - */ - public String toPrettyString() throws IOException { - if (jsonFactory != null) { - return jsonFactory.toPrettyString(this); - } - return super.toString(); - } - - @Override - public GenericJson clone() { - return (GenericJson) super.clone(); - } - - @Override - public GenericJson set(String fieldName, Object value) { - return (GenericJson) super.set(fieldName, value); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/json/Json.java b/src/autosaveworld/zlibs/com/google/api/client/json/Json.java deleted file mode 100644 index baa293ec..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/json/Json.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.json; - -/** - * JSON utilities. - * - * @since 1.0 - * @author Yaniv Inbar - */ -public class Json { - - /** - * {@code "application/json; charset=utf-8"} media type used as a default for JSON parsing. - * - *

- * Use {@link autosaveworld.zlibs.com.google.api.client.http.HttpMediaType#equalsIgnoreParameters} for comparing - * media types. - *

- * - * @since 1.10 - */ - public static final String MEDIA_TYPE = "application/json; charset=UTF-8"; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/json/JsonFactory.java b/src/autosaveworld/zlibs/com/google/api/client/json/JsonFactory.java deleted file mode 100644 index 08353d86..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/json/JsonFactory.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc.J - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.json; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; -import java.nio.charset.Charset; - -import autosaveworld.zlibs.com.google.api.client.util.Charsets; - -/** - * Abstract low-level JSON factory. - * - *

- * Implementation is thread-safe, and sub-classes must be thread-safe. For maximum efficiency, - * applications should use a single globally-shared instance of the JSON factory. - *

- * - * @since 1.3 - * @author Yaniv Inbar - */ -public abstract class JsonFactory { - - /** - * Returns a new instance of a low-level JSON parser for the given input stream. The parser tries - * to detect the charset of the input stream by itself. - * - * @param in input stream - * @return new instance of a low-level JSON parser - */ - public abstract JsonParser createJsonParser(InputStream in) throws IOException; - - /** - * Returns a new instance of a low-level JSON parser for the given input stream. - * - * @param in input stream - * @param charset charset in which the input stream is encoded or {@code null} to let the parser - * detect the charset - * @return new instance of a low-level JSON parser - * @since 1.10 - */ - public abstract JsonParser createJsonParser(InputStream in, Charset charset) throws IOException; - - /** - * Returns a new instance of a low-level JSON parser for the given string value. - * - * @param value string value - * @return new instance of a low-level JSON parser - */ - public abstract JsonParser createJsonParser(String value) throws IOException; - - /** - * Returns a new instance of a low-level JSON parser for the given reader. - * - * @param reader reader - * @return new instance of a low-level JSON parser - */ - public abstract JsonParser createJsonParser(Reader reader) throws IOException; - - /** - * Returns a new instance of a low-level JSON serializer for the given output stream and encoding. - * - * @param out output stream - * @param enc encoding - * @return new instance of a low-level JSON serializer - * @since 1.10 - */ - public abstract JsonGenerator createJsonGenerator(OutputStream out, Charset enc) - throws IOException; - - /** - * Returns a new instance of a low-level JSON serializer for the given writer. - * - * @param writer writer - * @return new instance of a low-level JSON serializer - */ - public abstract JsonGenerator createJsonGenerator(Writer writer) throws IOException; - - /** - * Creates an object parser which uses this factory to parse JSON data. - * - * @since 1.10 - */ - public final JsonObjectParser createJsonObjectParser() { - return new JsonObjectParser(this); - } - - /** - * Returns a serialized JSON string representation for the given item using - * {@link JsonGenerator#serialize(Object)}. - * - * @param item data key/value pairs - * @return serialized JSON string representation - */ - public final String toString(Object item) throws IOException { - return toString(item, false); - } - - /** - * Returns a pretty-printed serialized JSON string representation for the given item using - * {@link JsonGenerator#serialize(Object)} with {@link JsonGenerator#enablePrettyPrint()}. - * - *

- * The specifics of how the JSON representation is made pretty is implementation dependent, and - * should not be relied on. However, it is assumed to be legal, and in fact differs from - * {@link #toString(Object)} only by adding whitespace that does not change its meaning. - *

- * - * @param item data key/value pairs - * @return serialized JSON string representation - * @since 1.6 - */ - public final String toPrettyString(Object item) throws IOException { - return toString(item, true); - } - - /** - * Returns a UTF-8 encoded byte array of the serialized JSON representation for the given item - * using {@link JsonGenerator#serialize(Object)}. - * - * @param item data key/value pairs - * @return byte array of the serialized JSON representation - * @since 1.7 - */ - public final byte[] toByteArray(Object item) throws IOException { - return toByteStream(item, false).toByteArray(); - } - - /** - * Returns a serialized JSON string representation for the given item using - * {@link JsonGenerator#serialize(Object)}. - * - * @param item data key/value pairs - * @param pretty whether to return a pretty representation - * @return serialized JSON string representation - */ - private String toString(Object item, boolean pretty) throws IOException { - return toByteStream(item, pretty).toString("UTF-8"); - } - - /** - * Returns a UTF-8 byte array output stream of the serialized JSON representation for the given - * item using {@link JsonGenerator#serialize(Object)}. - * - * @param item data key/value pairs - * @param pretty whether to return a pretty representation - * @return serialized JSON string representation - */ - private ByteArrayOutputStream toByteStream(Object item, boolean pretty) throws IOException { - ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); - JsonGenerator generator = createJsonGenerator(byteStream, Charsets.UTF_8); - if (pretty) { - generator.enablePrettyPrint(); - } - generator.serialize(item); - generator.flush(); - return byteStream; - } - - /** - * Parses a string value as a JSON object, array, or value into a new instance of the given - * destination class using {@link JsonParser#parse(Class)}. - * - * @param value JSON string value - * @param destinationClass destination class that has an accessible default constructor to use to - * create a new instance - * @return new instance of the parsed destination class - * @since 1.4 - */ - public final T fromString(String value, Class destinationClass) throws IOException { - return createJsonParser(value).parse(destinationClass); - } - - /** - * Parse and close an input stream as a JSON object, array, or value into a new instance of the - * given destination class using {@link JsonParser#parseAndClose(Class)}. - * - *

- * Tries to detect the charset of the input stream automatically. - *

- * - * @param inputStream JSON value in an input stream - * @param destinationClass destination class that has an accessible default constructor to use to - * create a new instance - * @return new instance of the parsed destination class - * @since 1.7 - */ - public final T fromInputStream(InputStream inputStream, Class destinationClass) - throws IOException { - return createJsonParser(inputStream).parseAndClose(destinationClass); - } - - /** - * Parse and close an input stream as a JSON object, array, or value into a new instance of the - * given destination class using {@link JsonParser#parseAndClose(Class)}. - * - * @param inputStream JSON value in an input stream - * @param charset Charset in which the stream is encoded - * @param destinationClass destination class that has an accessible default constructor to use to - * create a new instance - * @return new instance of the parsed destination class - * @since 1.10 - */ - public final T fromInputStream( - InputStream inputStream, Charset charset, Class destinationClass) throws IOException { - return createJsonParser(inputStream, charset).parseAndClose(destinationClass); - } - - /** - * Parse and close a reader as a JSON object, array, or value into a new instance of the given - * destination class using {@link JsonParser#parseAndClose(Class)}. - * - * @param reader JSON value in a reader - * @param destinationClass destination class that has an accessible default constructor to use to - * create a new instance - * @return new instance of the parsed destination class - * @since 1.7 - */ - public final T fromReader(Reader reader, Class destinationClass) throws IOException { - return createJsonParser(reader).parseAndClose(destinationClass); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/json/JsonGenerator.java b/src/autosaveworld/zlibs/com/google/api/client/json/JsonGenerator.java deleted file mode 100644 index 6977158a..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/json/JsonGenerator.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.json; - -import java.io.IOException; -import java.lang.reflect.Field; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.Map; - -import autosaveworld.zlibs.com.google.api.client.util.ClassInfo; -import autosaveworld.zlibs.com.google.api.client.util.Data; -import autosaveworld.zlibs.com.google.api.client.util.DateTime; -import autosaveworld.zlibs.com.google.api.client.util.FieldInfo; -import autosaveworld.zlibs.com.google.api.client.util.GenericData; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.Types; - -/** - * Abstract low-level JSON serializer. - * - *

- * Implementation has no fields and therefore thread-safe, but sub-classes are not necessarily - * thread-safe. - *

- * - * @since 1.3 - * @author Yaniv Inbar - */ -public abstract class JsonGenerator { - - /** Returns the JSON factory from which this generator was created. */ - public abstract JsonFactory getFactory(); - - /** Flushes any buffered content to the underlying output stream or writer. */ - public abstract void flush() throws IOException; - - /** - * Closes the serializer and the underlying output stream or writer, and releases any memory - * associated with it. - */ - public abstract void close() throws IOException; - - /** Writes a JSON start array character '['. */ - public abstract void writeStartArray() throws IOException; - - /** Writes a JSON end array character ']'. */ - public abstract void writeEndArray() throws IOException; - - /** Writes a JSON start object character '{'. */ - public abstract void writeStartObject() throws IOException; - - /** Writes a JSON end object character '}'. */ - public abstract void writeEndObject() throws IOException; - - /** Writes a JSON quoted field name. */ - public abstract void writeFieldName(String name) throws IOException; - - /** Writes a literal JSON null value. */ - public abstract void writeNull() throws IOException; - - /** Writes a JSON quoted string value. */ - public abstract void writeString(String value) throws IOException; - - /** Writes a literal JSON boolean value ('true' or 'false'). */ - public abstract void writeBoolean(boolean state) throws IOException; - - /** Writes a JSON int value. */ - public abstract void writeNumber(int v) throws IOException; - - /** Writes a JSON long value. */ - public abstract void writeNumber(long v) throws IOException; - - /** Writes a JSON big integer value. */ - public abstract void writeNumber(BigInteger v) throws IOException; - - /** Writes a JSON float value. */ - public abstract void writeNumber(float v) throws IOException; - - /** Writes a JSON double value. */ - public abstract void writeNumber(double v) throws IOException; - - /** Writes a JSON big decimal value. */ - public abstract void writeNumber(BigDecimal v) throws IOException; - - /** Writes a JSON numeric value that has already been encoded properly. */ - public abstract void writeNumber(String encodedValue) throws IOException; - - /** - * Serializes the given JSON value object, or if {@code value} is {@code null} it does no - * serialization. - */ - public final void serialize(Object value) throws IOException { - serialize(false, value); - } - - private void serialize(boolean isJsonString, Object value) throws IOException { - if (value == null) { - return; - } - Class valueClass = value.getClass(); - if (Data.isNull(value)) { - writeNull(); - } else if (value instanceof String) { - writeString((String) value); - } else if (value instanceof Number) { - if (isJsonString) { - writeString(value.toString()); - } else if (value instanceof BigDecimal) { - writeNumber((BigDecimal) value); - } else if (value instanceof BigInteger) { - writeNumber((BigInteger) value); - } else if (value instanceof Long) { - writeNumber((Long) value); - } else if (value instanceof Float) { - float floatValue = ((Number) value).floatValue(); - Preconditions.checkArgument(!Float.isInfinite(floatValue) && !Float.isNaN(floatValue)); - writeNumber(floatValue); - } else if (value instanceof Integer || value instanceof Short || value instanceof Byte) { - writeNumber(((Number) value).intValue()); - } else { - double doubleValue = ((Number) value).doubleValue(); - Preconditions.checkArgument(!Double.isInfinite(doubleValue) && !Double.isNaN(doubleValue)); - writeNumber(doubleValue); - } - } else if (value instanceof Boolean) { - writeBoolean((Boolean) value); - } else if (value instanceof DateTime) { - writeString(((DateTime) value).toStringRfc3339()); - } else if (value instanceof Iterable || valueClass.isArray()) { - writeStartArray(); - for (Object o : Types.iterableOf(value)) { - serialize(isJsonString, o); - } - writeEndArray(); - } else if (valueClass.isEnum()) { - String name = FieldInfo.of((Enum) value).getName(); - if (name == null) { - writeNull(); - } else { - writeString(name); - } - } else { - writeStartObject(); - // only inspect fields of POJO (possibly extends GenericData) but not generic Map - boolean isMapNotGenericData = value instanceof Map && !(value instanceof GenericData); - ClassInfo classInfo = isMapNotGenericData ? null : ClassInfo.of(valueClass); - for (Map.Entry entry : Data.mapOf(value).entrySet()) { - Object fieldValue = entry.getValue(); - if (fieldValue != null) { - String fieldName = entry.getKey(); - boolean isJsonStringForField; - if (isMapNotGenericData) { - isJsonStringForField = isJsonString; - } else { - Field field = classInfo.getField(fieldName); - isJsonStringForField = field != null && field.getAnnotation(JsonString.class) != null; - } - writeFieldName(fieldName); - serialize(isJsonStringForField, fieldValue); - } - } - writeEndObject(); - } - } - - /** - * Requests that the output be pretty printed (by default it is not). - * - *

- * Default implementation does nothing, but implementations may override to provide actual pretty - * printing. - *

- * - * @throws IOException possible I/O exception (unused in default implementation) - * - * @since 1.6 - */ - public void enablePrettyPrint() throws IOException { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/json/JsonObjectParser.java b/src/autosaveworld/zlibs/com/google/api/client/json/JsonObjectParser.java deleted file mode 100644 index 16354d5b..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/json/JsonObjectParser.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.json; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.lang.reflect.Type; -import java.nio.charset.Charset; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -import autosaveworld.zlibs.com.google.api.client.util.ObjectParser; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.Sets; - -/** - * Parses JSON data into an data class of key/value pairs. - * - *

- * Implementation is thread-safe. - *

- * - *

- * Sample usage: - *

- * - *
- *
-  static void setParser(HttpRequest request) {
-    request.setParser(new JsonObjectParser(new JacksonFactory()));
-  }
- * 
- * 
- * - * @author Matthias Linder (mlinder) - * @since 1.10 - */ -public class JsonObjectParser implements ObjectParser { - - /** JSON factory. */ - private final JsonFactory jsonFactory; - - /** Wrapper keys for the JSON content or empty for none. */ - private final Set wrapperKeys; - - /** - * @param jsonFactory JSON factory - */ - public JsonObjectParser(JsonFactory jsonFactory) { - this(new Builder(jsonFactory)); - } - - /** - * @param builder builder - * - * @since 1.14 - */ - protected JsonObjectParser(Builder builder) { - jsonFactory = builder.jsonFactory; - wrapperKeys = new HashSet(builder.wrapperKeys); - } - - @SuppressWarnings("unchecked") - public T parseAndClose(InputStream in, Charset charset, Class dataClass) - throws IOException { - return (T) parseAndClose(in, charset, (Type) dataClass); - } - - public Object parseAndClose(InputStream in, Charset charset, Type dataType) throws IOException { - JsonParser parser = jsonFactory.createJsonParser(in, charset); - initializeParser(parser); - return parser.parse(dataType, true); - } - - @SuppressWarnings("unchecked") - public T parseAndClose(Reader reader, Class dataClass) throws IOException { - return (T) parseAndClose(reader, (Type) dataClass); - } - - public Object parseAndClose(Reader reader, Type dataType) throws IOException { - JsonParser parser = jsonFactory.createJsonParser(reader); - initializeParser(parser); - return parser.parse(dataType, true); - } - - /** Returns the JSON factory. */ - public final JsonFactory getJsonFactory() { - return jsonFactory; - } - - /** - * Returns the unmodifiable set of wrapper keys for the JSON content. - * - * @since 1.14 - */ - public Set getWrapperKeys() { - return Collections.unmodifiableSet(wrapperKeys); - } - - /** - * Initialize the parser to skip to wrapped keys (if any). - * - * @param parser JSON parser - */ - private void initializeParser(JsonParser parser) throws IOException { - if (wrapperKeys.isEmpty()) { - return; - } - boolean failed = true; - try { - String match = parser.skipToKey(wrapperKeys); - Preconditions.checkArgument(match != null && parser.getCurrentToken() != JsonToken.END_OBJECT, - "wrapper key(s) not found: %s", wrapperKeys); - failed = false; - } finally { - if (failed) { - parser.close(); - } - } - } - - /** - * Builder. - * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.14 - */ - public static class Builder { - - /** JSON factory. */ - final JsonFactory jsonFactory; - - /** Wrapper keys for the JSON content or empty for none. */ - Collection wrapperKeys = Sets.newHashSet(); - - /** - * @param jsonFactory JSON factory - */ - public Builder(JsonFactory jsonFactory) { - this.jsonFactory = Preconditions.checkNotNull(jsonFactory); - } - - /** Returns a new instance of a JSON object parser. */ - public JsonObjectParser build() { - return new JsonObjectParser(this); - } - - /** Returns the JSON factory. */ - public final JsonFactory getJsonFactory() { - return jsonFactory; - } - - /** Returns the wrapper keys for the JSON content. */ - public final Collection getWrapperKeys() { - return wrapperKeys; - } - - /** - * Sets the wrapper keys for the JSON content. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Builder setWrapperKeys(Collection wrapperKeys) { - this.wrapperKeys = wrapperKeys; - return this; - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/json/JsonParser.java b/src/autosaveworld/zlibs/com/google/api/client/json/JsonParser.java deleted file mode 100644 index dac79dde..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/json/JsonParser.java +++ /dev/null @@ -1,948 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.json; - -import java.io.IOException; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.WeakHashMap; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import autosaveworld.zlibs.com.google.api.client.json.JsonPolymorphicTypeMap.TypeDef; -import autosaveworld.zlibs.com.google.api.client.util.Beta; -import autosaveworld.zlibs.com.google.api.client.util.ClassInfo; -import autosaveworld.zlibs.com.google.api.client.util.Data; -import autosaveworld.zlibs.com.google.api.client.util.FieldInfo; -import autosaveworld.zlibs.com.google.api.client.util.GenericData; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.Sets; -import autosaveworld.zlibs.com.google.api.client.util.Types; - -/** - * Abstract low-level JSON parser. See - * - * https://code.google.com/p/google-http-java-client/wiki/JSON - * - *

- * Implementation has no fields and therefore thread-safe, but sub-classes are not necessarily - * thread-safe. - *

- *

- *

- * If a JSON map is encountered while using a destination class of type Map, then an - * {@link ArrayMap} is used by default for the parsed values. - *

- * - * @since 1.3 - * @author Yaniv Inbar - */ -public abstract class JsonParser { - - /** - * Maps a polymorphic {@link Class} to its {@link Field} with the {@link JsonPolymorphicTypeMap} - * annotation, or {@code null} if there is no field with that annotation. - */ - private static WeakHashMap, Field> cachedTypemapFields = - new WeakHashMap, Field>(); - - /** Lock on the {@code cachedTypemapFields}. */ - private static final Lock lock = new ReentrantLock(); - - /** Returns the JSON factory from which this generator was created. */ - public abstract JsonFactory getFactory(); - - /** - * Closes the parser and the underlying input stream or reader, and releases any memory associated - * with it. - */ - public abstract void close() throws IOException; - - /** Returns the next token from the stream or {@code null} to indicate end of input. */ - public abstract JsonToken nextToken() throws IOException; - - /** - * Returns the token the parser currently points to or {@code null} for none (at start of input or - * after end of input). - */ - public abstract JsonToken getCurrentToken(); - - /** - * Returns the most recent field name or {@code null} for array values or for root-level values. - */ - public abstract String getCurrentName() throws IOException; - - /** - * Skips to the matching {@link JsonToken#END_ARRAY} if current token is - * {@link JsonToken#START_ARRAY}, the matching {@link JsonToken#END_OBJECT} if the current token - * is {@link JsonToken#START_OBJECT}, else does nothing. - */ - public abstract JsonParser skipChildren() throws IOException; - - /** - * Returns a textual representation of the current token or {@code null} if - * {@link #getCurrentToken()} is {@code null}. - */ - public abstract String getText() throws IOException; - - // TODO(yanivi): Jackson provides getTextCharacters(), getTextLength(), and getTextOffset() - - /** Returns the byte value of the current token. */ - public abstract byte getByteValue() throws IOException; - - /** Returns the short value of the current token. */ - public abstract short getShortValue() throws IOException; - - /** Returns the int value of the current token. */ - public abstract int getIntValue() throws IOException; - - /** Returns the float value of the current token. */ - public abstract float getFloatValue() throws IOException; - - /** Returns the long value of the current token. */ - public abstract long getLongValue() throws IOException; - - /** Returns the double value of the current token. */ - public abstract double getDoubleValue() throws IOException; - - /** Returns the {@link BigInteger} value of the current token. */ - public abstract BigInteger getBigIntegerValue() throws IOException; - - /** Returns the {@link BigDecimal} value of the current token. */ - public abstract BigDecimal getDecimalValue() throws IOException; - - /** - * Parse a JSON object, array, or value into a new instance of the given destination class, and - * then closes the parser. - * - * @param destination class - * @param destinationClass destination class that has a public default constructor to use to - * create a new instance - * @return new instance of the parsed destination class - * @since 1.15 - */ - public final T parseAndClose(Class destinationClass) throws IOException { - return parseAndClose(destinationClass, null); - } - - /** - * {@link Beta}
- * Parse a JSON object, array, or value into a new instance of the given destination class using - * {@link JsonParser#parse(Class, CustomizeJsonParser)}, and then closes the parser. - * - * @param destination class - * @param destinationClass destination class that has a public default constructor to use to - * create a new instance - * @param customizeParser optional parser customizer or {@code null} for none - * @return new instance of the parsed destination class - */ - @Beta - public final T parseAndClose(Class destinationClass, CustomizeJsonParser customizeParser) - throws IOException { - try { - return parse(destinationClass, customizeParser); - } finally { - close(); - } - } - - /** - * Skips the values of all keys in the current object until it finds the given key. - * - *

- * Before this method is called, the parser must either point to the start or end of a JSON object - * or to a field name. After this method ends, the current token will either be the - * {@link JsonToken#END_OBJECT} of the current object if the key is not found, or the value of the - * key that was found. - *

- * - * @param keyToFind key to find - */ - public final void skipToKey(String keyToFind) throws IOException { - skipToKey(Collections.singleton(keyToFind)); - } - - /** - * Skips the values of all keys in the current object until it finds one of the given keys. - * - *

- * Before this method is called, the parser must either point to the start or end of a JSON object - * or to a field name. After this method ends, the current token will either be the - * {@link JsonToken#END_OBJECT} of the current object if no matching key is found, or the value of - * the key that was found. - *

- * - * @param keysToFind set of keys to look for - * @return name of the first matching key found or {@code null} if no match was found - * @since 1.10 - */ - public final String skipToKey(Set keysToFind) throws IOException { - JsonToken curToken = startParsingObjectOrArray(); - while (curToken == JsonToken.FIELD_NAME) { - String key = getText(); - nextToken(); - if (keysToFind.contains(key)) { - return key; - } - skipChildren(); - curToken = nextToken(); - } - return null; - } - - /** Starts parsing that handles start of input by calling {@link #nextToken()}. */ - private JsonToken startParsing() throws IOException { - JsonToken currentToken = getCurrentToken(); - // token is null at start, so get next token - if (currentToken == null) { - currentToken = nextToken(); - } - Preconditions.checkArgument(currentToken != null, "no JSON input found"); - return currentToken; - } - - /** - * Starts parsing an object or array by making sure the parser points to an object field name, - * first array value or end of object or array. - * - *

- * If the parser is at the start of input, {@link #nextToken()} is called. The current token must - * then be {@link JsonToken#START_OBJECT}, {@link JsonToken#END_OBJECT}, - * {@link JsonToken#START_ARRAY}, {@link JsonToken#END_ARRAY}, or {@link JsonToken#FIELD_NAME}. - * For an object only, after the method is called, the current token must be either - * {@link JsonToken#FIELD_NAME} or {@link JsonToken#END_OBJECT}. - *

- */ - private JsonToken startParsingObjectOrArray() throws IOException { - JsonToken currentToken = startParsing(); - switch (currentToken) { - case START_OBJECT: - currentToken = nextToken(); - Preconditions.checkArgument( - currentToken == JsonToken.FIELD_NAME || currentToken == JsonToken.END_OBJECT, - currentToken); - break; - case START_ARRAY: - currentToken = nextToken(); - break; - default: - break; - } - return currentToken; - } - - /** - * Parse a JSON Object from the given JSON parser -- which is closed after parsing completes -- - * into the given destination object. - * - *

- * Before this method is called, the parser must either point to the start or end of a JSON object - * or to a field name. - *

- * - * @param destination destination object - * @since 1.15 - */ - public final void parseAndClose(Object destination) throws IOException { - parseAndClose(destination, null); - } - - /** - * {@link Beta}
- * Parse a JSON Object from the given JSON parser -- which is closed after parsing completes -- - * into the given destination object, optionally using the given parser customizer. - * - *

- * Before this method is called, the parser must either point to the start or end of a JSON object - * or to a field name. - *

- * - * @param destination destination object - * @param customizeParser optional parser customizer or {@code null} for none - */ - @Beta - public final void parseAndClose(Object destination, CustomizeJsonParser customizeParser) - throws IOException { - try { - parse(destination, customizeParser); - } finally { - close(); - } - } - - /** - * Parse a JSON object, array, or value into a new instance of the given destination class. - * - *

- * If it parses an object, after this method ends, the current token will be the object's ending - * {@link JsonToken#END_OBJECT}. If it parses an array, after this method ends, the current token - * will be the array's ending {@link JsonToken#END_ARRAY}. - *

- * - * @param destination class - * @param destinationClass destination class that has a public default constructor to use to - * create a new instance - * @return new instance of the parsed destination class - * @since 1.15 - */ - public final T parse(Class destinationClass) throws IOException { - return parse(destinationClass, null); - } - - /** - * {@link Beta}
- * Parse a JSON object, array, or value into a new instance of the given destination class, - * optionally using the given parser customizer. - * - *

- * If it parses an object, after this method ends, the current token will be the object's ending - * {@link JsonToken#END_OBJECT}. If it parses an array, after this method ends, the current token - * will be the array's ending {@link JsonToken#END_ARRAY}. - *

- * - * @param destination class - * @param destinationClass destination class that has a public default constructor to use to - * create a new instance - * @param customizeParser optional parser customizer or {@code null} for none - * @return new instance of the parsed destination class - */ - @Beta - public final T parse(Class destinationClass, CustomizeJsonParser customizeParser) - throws IOException { - @SuppressWarnings("unchecked") - T result = (T) parse(destinationClass, false, customizeParser); - return result; - } - - /** - * Parse a JSON object, array, or value into a new instance of the given destination class. - * - *

- * If it parses an object, after this method ends, the current token will be the object's ending - * {@link JsonToken#END_OBJECT}. If it parses an array, after this method ends, the current token - * will be the array's ending {@link JsonToken#END_ARRAY}. - *

- * - * @param dataType Type into which the JSON should be parsed - * @param close {@code true} if {@link #close()} should be called after parsing - * @return new instance of the parsed dataType - * @since 1.15 - */ - public Object parse(Type dataType, boolean close) throws IOException { - return parse(dataType, close, null); - } - - /** - * {@link Beta}
- * Parse a JSON object, array, or value into a new instance of the given destination class, - * optionally using the given parser customizer. - * - *

- * If it parses an object, after this method ends, the current token will be the object's ending - * {@link JsonToken#END_OBJECT}. If it parses an array, after this method ends, the current token - * will be the array's ending {@link JsonToken#END_ARRAY}. - *

- * - * @param dataType Type into which the JSON should be parsed - * @param close {@code true} if {@link #close()} should be called after parsing - * @param customizeParser optional parser customizer or {@code null} for none - * @return new instance of the parsed dataType - * @since 1.10 - */ - @Beta - public Object parse(Type dataType, boolean close, CustomizeJsonParser customizeParser) - throws IOException { - try { - if (!Void.class.equals(dataType)) { - startParsing(); - } - return parseValue(null, dataType, new ArrayList(), null, customizeParser, true); - } finally { - if (close) { - close(); - } - } - } - - /** - * Parse a JSON object from the given JSON parser into the given destination object. - * - *

- * Before this method is called, the parser must either point to the start or end of a JSON object - * or to a field name. After this method ends, the current token will be the - * {@link JsonToken#END_OBJECT} of the current object. - *

- * - * @param destination destination object - * @since 1.15 - */ - public final void parse(Object destination) throws IOException { - parse(destination, null); - } - - /** - * {@link Beta}
- * Parse a JSON object from the given JSON parser into the given destination object, optionally - * using the given parser customizer. - * - *

- * Before this method is called, the parser must either point to the start or end of a JSON object - * or to a field name. After this method ends, the current token will be the - * {@link JsonToken#END_OBJECT} of the current object. - *

- * - * @param destination destination object - * @param customizeParser optional parser customizer or {@code null} for none - */ - @Beta - public final void parse(Object destination, CustomizeJsonParser customizeParser) - throws IOException { - ArrayList context = new ArrayList(); - context.add(destination.getClass()); - parse(context, destination, customizeParser); - } - - /** - * Parses the next field from the given JSON parser into the given destination object. - * - * @param context destination context stack (possibly empty) - * @param destination destination object instance or {@code null} for none (for example empty - * context stack) - * @param customizeParser optional parser customizer or {@code null} for none - */ - private void parse( - ArrayList context, Object destination, CustomizeJsonParser customizeParser) - throws IOException { - if (destination instanceof GenericJson) { - ((GenericJson) destination).setFactory(getFactory()); - } - JsonToken curToken = startParsingObjectOrArray(); - Class destinationClass = destination.getClass(); - ClassInfo classInfo = ClassInfo.of(destinationClass); - boolean isGenericData = GenericData.class.isAssignableFrom(destinationClass); - if (!isGenericData && Map.class.isAssignableFrom(destinationClass)) { - // The destination class is not a sub-class of GenericData but is of Map, so parse data - // using parseMap. - @SuppressWarnings("unchecked") - Map destinationMap = (Map) destination; - parseMap(null, destinationMap, Types.getMapValueParameter(destinationClass), context, - customizeParser); - return; - } - while (curToken == JsonToken.FIELD_NAME) { - String key = getText(); - nextToken(); - // stop at items for feeds - if (customizeParser != null && customizeParser.stopAt(destination, key)) { - return; - } - // get the field from the type information - FieldInfo fieldInfo = classInfo.getFieldInfo(key); - if (fieldInfo != null) { - // skip final fields - if (fieldInfo.isFinal() && !fieldInfo.isPrimitive()) { - throw new IllegalArgumentException("final array/object fields are not supported"); - } - Field field = fieldInfo.getField(); - int contextSize = context.size(); - context.add(field.getGenericType()); - Object fieldValue = parseValue(field, - fieldInfo.getGenericType(), - context, - destination, - customizeParser, - true); - context.remove(contextSize); - fieldInfo.setValue(destination, fieldValue); - } else if (isGenericData) { - // store unknown field in generic JSON - GenericData object = (GenericData) destination; - object.set(key, parseValue(null, null, context, destination, customizeParser, true)); - } else { - // unrecognized field, skip value. - if (customizeParser != null) { - customizeParser.handleUnrecognizedKey(destination, key); - } - skipChildren(); - } - curToken = nextToken(); - } - } - - /** - * Parse a JSON Array from the given JSON parser (which is closed after parsing completes) into - * the given destination collection. - * - * @param destinationCollectionClass class of destination collection (must have a public default - * constructor) - * @param destinationItemClass class of destination collection item (must have a public default - * constructor) - * @since 1.15 - */ - public final Collection parseArrayAndClose( - Class destinationCollectionClass, Class destinationItemClass) throws IOException { - return parseArrayAndClose(destinationCollectionClass, destinationItemClass, null); - } - - /** - * {@link Beta}
- * Parse a JSON Array from the given JSON parser (which is closed after parsing completes) into - * the given destination collection, optionally using the given parser customizer. - * - * @param destinationCollectionClass class of destination collection (must have a public default - * constructor) - * @param destinationItemClass class of destination collection item (must have a public default - * constructor) - * @param customizeParser optional parser customizer or {@code null} for none - */ - @Beta - public final Collection parseArrayAndClose(Class destinationCollectionClass, - Class destinationItemClass, CustomizeJsonParser customizeParser) throws IOException { - try { - return parseArray(destinationCollectionClass, destinationItemClass, customizeParser); - } finally { - close(); - } - } - - /** - * Parse a JSON Array from the given JSON parser (which is closed after parsing completes) into - * the given destination collection. - * - * @param destinationCollection destination collection - * @param destinationItemClass class of destination collection item (must have a public default - * constructor) - * @since 1.15 - */ - public final void parseArrayAndClose( - Collection destinationCollection, Class destinationItemClass) - throws IOException { - parseArrayAndClose(destinationCollection, destinationItemClass, null); - } - - /** - * {@link Beta}
- * Parse a JSON Array from the given JSON parser (which is closed after parsing completes) into - * the given destination collection, optionally using the given parser customizer. - * - * @param destinationCollection destination collection - * @param destinationItemClass class of destination collection item (must have a public default - * constructor) - * @param customizeParser optional parser customizer or {@code null} for none - */ - @Beta - public final void parseArrayAndClose(Collection destinationCollection, - Class destinationItemClass, CustomizeJsonParser customizeParser) throws IOException { - try { - parseArray(destinationCollection, destinationItemClass, customizeParser); - } finally { - close(); - } - } - - /** - * Parse a JSON Array from the given JSON parser into the given destination collection. - * - * @param destinationCollectionClass class of destination collection (must have a public default - * constructor) - * @param destinationItemClass class of destination collection item (must have a public default - * constructor) - * @since 1.15 - */ - public final Collection parseArray( - Class destinationCollectionClass, Class destinationItemClass) throws IOException { - return parseArray(destinationCollectionClass, destinationItemClass, null); - } - - /** - * {@link Beta}
- * Parse a JSON Array from the given JSON parser into the given destination collection, optionally - * using the given parser customizer. - * - * @param destinationCollectionClass class of destination collection (must have a public default - * constructor) - * @param destinationItemClass class of destination collection item (must have a public default - * constructor) - * @param customizeParser optional parser customizer or {@code null} for none - */ - @Beta - public final Collection parseArray(Class destinationCollectionClass, - Class destinationItemClass, CustomizeJsonParser customizeParser) throws IOException { - @SuppressWarnings("unchecked") - Collection destinationCollection = - (Collection) Data.newCollectionInstance(destinationCollectionClass); - parseArray(destinationCollection, destinationItemClass, customizeParser); - return destinationCollection; - } - - /** - * Parse a JSON Array from the given JSON parser into the given destination collection. - * - * @param destinationCollection destination collection - * @param destinationItemClass class of destination collection item (must have a public default - * constructor) - * @since 1.15 - */ - public final void parseArray( - Collection destinationCollection, Class destinationItemClass) - throws IOException { - parseArray(destinationCollection, destinationItemClass, null); - } - - /** - * {@link Beta}
- * Parse a JSON Array from the given JSON parser into the given destination collection, optionally - * using the given parser customizer. - * - * @param destinationCollection destination collection - * @param destinationItemClass class of destination collection item (must have a public default - * constructor) - * @param customizeParser optional parser customizer or {@code null} for none - */ - @Beta - public final void parseArray(Collection destinationCollection, - Class destinationItemClass, CustomizeJsonParser customizeParser) throws IOException { - parseArray( - null, destinationCollection, destinationItemClass, new ArrayList(), customizeParser); - } - - /** - * Parse a JSON Array from the given JSON parser into the given destination collection, optionally - * using the given parser customizer. - * - * @param fieldContext field context or {@code null} for none - * @param destinationCollection destination collection - * @param destinationItemType type of destination collection item - * @param context destination context stack (possibly empty) - * @param customizeParser optional parser customizer or {@code null} for none - */ - private void parseArray(Field fieldContext, Collection destinationCollection, - Type destinationItemType, ArrayList context, CustomizeJsonParser customizeParser) - throws IOException { - JsonToken curToken = startParsingObjectOrArray(); - while (curToken != JsonToken.END_ARRAY) { - @SuppressWarnings("unchecked") - T parsedValue = (T) parseValue(fieldContext, - destinationItemType, - context, - destinationCollection, - customizeParser, - true); - destinationCollection.add(parsedValue); - curToken = nextToken(); - } - } - - /** - * Parse a JSON Object from the given JSON parser into the given destination map, optionally using - * the given parser customizer. - * - * @param fieldContext field context or {@code null} for none - * @param destinationMap destination map - * @param valueType valueType of the map value type parameter - * @param context destination context stack (possibly empty) - * @param customizeParser optional parser customizer or {@code null} for none - */ - private void parseMap(Field fieldContext, Map destinationMap, Type valueType, - ArrayList context, CustomizeJsonParser customizeParser) throws IOException { - JsonToken curToken = startParsingObjectOrArray(); - while (curToken == JsonToken.FIELD_NAME) { - String key = getText(); - nextToken(); - // stop at items for feeds - if (customizeParser != null && customizeParser.stopAt(destinationMap, key)) { - return; - } - Object value = - parseValue(fieldContext, valueType, context, destinationMap, customizeParser, true); - destinationMap.put(key, value); - curToken = nextToken(); - } - } - - /** - * Parse a value. - * - * @param fieldContext field context or {@code null} for none (for example into a map) - * @param valueType value type or {@code null} if not known (for example into a map) - * @param context destination context stack (possibly empty) - * @param destination destination object instance or {@code null} for none (for example empty - * context stack) - * @param customizeParser customize parser or {@code null} for none - * @param handlePolymorphic whether or not to check for polymorphic schema - * @return parsed value - */ - private final Object parseValue(Field fieldContext, - Type valueType, - ArrayList context, - Object destination, - CustomizeJsonParser customizeParser, - boolean handlePolymorphic) throws IOException { - - valueType = Data.resolveWildcardTypeOrTypeVariable(context, valueType); - // resolve a parameterized type to a class - Class valueClass = valueType instanceof Class ? (Class) valueType : null; - if (valueType instanceof ParameterizedType) { - valueClass = Types.getRawClass((ParameterizedType) valueType); - } - // Void means skip - if (valueClass == Void.class) { - skipChildren(); - return null; - } - // value type is now null, class, parameterized type, or generic array type - JsonToken token = getCurrentToken(); - try { - switch (getCurrentToken()) { - case START_ARRAY: - case END_ARRAY: - boolean isArray = Types.isArray(valueType); - Preconditions.checkArgument(valueType == null || isArray || valueClass != null - && Types.isAssignableToOrFrom(valueClass, Collection.class), - "expected collection or array type but got %s", valueType); - Collection collectionValue = null; - if (customizeParser != null && fieldContext != null) { - collectionValue = customizeParser.newInstanceForArray(destination, fieldContext); - } - if (collectionValue == null) { - collectionValue = Data.newCollectionInstance(valueType); - } - Type subType = null; - if (isArray) { - subType = Types.getArrayComponentType(valueType); - } else if (valueClass != null && Iterable.class.isAssignableFrom(valueClass)) { - subType = Types.getIterableParameter(valueType); - } - subType = Data.resolveWildcardTypeOrTypeVariable(context, subType); - parseArray(fieldContext, collectionValue, subType, context, customizeParser); - if (isArray) { - return Types.toArray(collectionValue, Types.getRawArrayComponentType(context, subType)); - } - return collectionValue; - case FIELD_NAME: - case START_OBJECT: - case END_OBJECT: - Preconditions.checkArgument( - !Types.isArray(valueType), "expected object or map type but got %s", valueType); - // Check if we're parsing into a polymorphic datatype. - Field typemapField = handlePolymorphic ? getCachedTypemapFieldFor(valueClass) : null; - Object newInstance = null; - if (valueClass != null && customizeParser != null) { - newInstance = customizeParser.newInstanceForObject(destination, valueClass); - } - boolean isMap = valueClass != null && Types.isAssignableToOrFrom(valueClass, Map.class); - if (typemapField != null) { - newInstance = new GenericJson(); - } else if (newInstance == null) { - // check if it is a map to avoid ClassCastException to Map - if (isMap || valueClass == null) { - newInstance = Data.newMapInstance(valueClass); - } else { - newInstance = Types.newInstance(valueClass); - } - } - int contextSize = context.size(); - if (valueType != null) { - context.add(valueType); - } - if (isMap && !GenericData.class.isAssignableFrom(valueClass)) { - Type subValueType = Map.class.isAssignableFrom(valueClass) - ? Types.getMapValueParameter(valueType) : null; - if (subValueType != null) { - @SuppressWarnings("unchecked") - Map destinationMap = (Map) newInstance; - parseMap(fieldContext, destinationMap, subValueType, context, customizeParser); - return newInstance; - } - } - parse(context, newInstance, customizeParser); - if (valueType != null) { - context.remove(contextSize); - } - if (typemapField == null) { - return newInstance; - } - - // Get the correct type out of the naively parsed data. - Object typeValueObject = ((GenericJson) newInstance).get(typemapField.getName()); - Preconditions.checkArgument( - typeValueObject != null, "No value specified for @JsonPolymorphicTypeMap field"); - String typeValue = typeValueObject.toString(); - JsonPolymorphicTypeMap typeMap = typemapField.getAnnotation(JsonPolymorphicTypeMap.class); - Class typeClass = null; - for (TypeDef typeDefinition : typeMap.typeDefinitions()) { - if (typeDefinition.key().equals(typeValue)) { - typeClass = typeDefinition.ref(); - break; - } - } - Preconditions.checkArgument( - typeClass != null, "No TypeDef annotation found with key: " + typeValue); - JsonFactory factory = getFactory(); - // TODO(ngmiceli): Avoid having to parse JSON content twice. Optimize when type is first. - JsonParser parser = factory.createJsonParser(factory.toString(newInstance)); - parser.startParsing(); - return parser.parseValue(fieldContext, typeClass, context, null, null, false); - case VALUE_TRUE: - case VALUE_FALSE: - Preconditions.checkArgument(valueType == null || valueClass == boolean.class - || valueClass != null && valueClass.isAssignableFrom(Boolean.class), - "expected type Boolean or boolean but got %s", valueType); - return token == JsonToken.VALUE_TRUE ? Boolean.TRUE : Boolean.FALSE; - case VALUE_NUMBER_FLOAT: - case VALUE_NUMBER_INT: - Preconditions.checkArgument( - fieldContext == null || fieldContext.getAnnotation(JsonString.class) == null, - "number type formatted as a JSON number cannot use @JsonString annotation"); - if (valueClass == null || valueClass.isAssignableFrom(BigDecimal.class)) { - return getDecimalValue(); - } - if (valueClass == BigInteger.class) { - return getBigIntegerValue(); - } - if (valueClass == Double.class || valueClass == double.class) { - return getDoubleValue(); - } - if (valueClass == Long.class || valueClass == long.class) { - return getLongValue(); - } - if (valueClass == Float.class || valueClass == float.class) { - return getFloatValue(); - } - if (valueClass == Integer.class || valueClass == int.class) { - return getIntValue(); - } - if (valueClass == Short.class || valueClass == short.class) { - return getShortValue(); - } - if (valueClass == Byte.class || valueClass == byte.class) { - return getByteValue(); - } - throw new IllegalArgumentException("expected numeric type but got " + valueType); - case VALUE_STRING: - //TODO(user): Maybe refactor this method in multiple mini-methods for readability? - String text = getText().trim().toLowerCase(Locale.US); - // If we are expecting a Float / Double and the Text is NaN (case insensitive) - // Then: Accept, even if the Annotation is JsonString. - // Otherwise: Check that the Annotation is not JsonString. - if (!(((valueClass == float.class || valueClass == Float.class) - || (valueClass == double.class || valueClass == Double.class)) - && (text.equals("nan") || text.equals("infinity") || text.equals("-infinity")))) { - Preconditions.checkArgument(valueClass == null - || !Number.class.isAssignableFrom(valueClass) || fieldContext != null - && fieldContext.getAnnotation(JsonString.class) != null, - "number field formatted as a JSON string must use the @JsonString annotation"); - } - return Data.parsePrimitiveValue(valueType, getText()); - case VALUE_NULL: - Preconditions.checkArgument(valueClass == null || !valueClass.isPrimitive(), - "primitive number field but found a JSON null"); - if (valueClass != null - && 0 != (valueClass.getModifiers() & (Modifier.ABSTRACT | Modifier.INTERFACE))) { - if (Types.isAssignableToOrFrom(valueClass, Collection.class)) { - return Data.nullOf(Data.newCollectionInstance(valueType).getClass()); - } - if (Types.isAssignableToOrFrom(valueClass, Map.class)) { - return Data.nullOf(Data.newMapInstance(valueClass).getClass()); - } - } - return Data.nullOf(Types.getRawArrayComponentType(context, valueType)); - default: - throw new IllegalArgumentException("unexpected JSON node type: " + token); - } - } catch (IllegalArgumentException e) { - // build context string - StringBuilder contextStringBuilder = new StringBuilder(); - String currentName = getCurrentName(); - if (currentName != null) { - contextStringBuilder.append("key ").append(currentName); - } - if (fieldContext != null) { - if (currentName != null) { - contextStringBuilder.append(", "); - } - contextStringBuilder.append("field ").append(fieldContext); - } - throw new IllegalArgumentException(contextStringBuilder.toString(), e); - } - } - - /** - * Finds the {@link Field} on the given {@link Class} that has the {@link JsonPolymorphicTypeMap} - * annotation, or {@code null} if there is none. - * - *

- * The class must contain exactly zero or one {@link JsonPolymorphicTypeMap} annotation. - *

- * - * @param key The {@link Class} to search in, or {@code null} - * @return The {@link Field} with the {@link JsonPolymorphicTypeMap} annotation, or {@code null} - * either if there is none or if the key is {@code null} - */ - private static Field getCachedTypemapFieldFor(Class key) { - if (key == null) { - return null; - } - lock.lock(); - try { - // Must use containsKey because we do store null values for when the class has no - // JsonPolymorphicTypeMap field. - if (cachedTypemapFields.containsKey(key)) { - return cachedTypemapFields.get(key); - } - // Find the field that determines the type and cache it. - Field value = null; - Collection fieldInfos = ClassInfo.of(key).getFieldInfos(); - for (FieldInfo fieldInfo : fieldInfos) { - Field field = fieldInfo.getField(); - JsonPolymorphicTypeMap typemapAnnotation = - field.getAnnotation(JsonPolymorphicTypeMap.class); - if (typemapAnnotation != null) { - Preconditions.checkArgument(value == null, - "Class contains more than one field with @JsonPolymorphicTypeMap annotation: %s", - key); - Preconditions.checkArgument(Data.isPrimitive(field.getType()), - "Field which has the @JsonPolymorphicTypeMap, %s, is not a supported type: %s", key, - field.getType()); - value = field; - // Check for duplicate typeDef keys - TypeDef[] typeDefs = typemapAnnotation.typeDefinitions(); - HashSet typeDefKeys = Sets.newHashSet(); - Preconditions.checkArgument( - typeDefs.length > 0, "@JsonPolymorphicTypeMap must have at least one @TypeDef"); - for (TypeDef typeDef : typeDefs) { - Preconditions.checkArgument(typeDefKeys.add(typeDef.key()), - "Class contains two @TypeDef annotations with identical key: %s", typeDef.key()); - } - } - } - cachedTypemapFields.put(key, value); - return value; - } finally { - lock.unlock(); - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/json/JsonPolymorphicTypeMap.java b/src/autosaveworld/zlibs/com/google/api/client/json/JsonPolymorphicTypeMap.java deleted file mode 100644 index 3047a5de..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/json/JsonPolymorphicTypeMap.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.json; - - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.lang.reflect.Type; - -import autosaveworld.zlibs.com.google.api.client.util.Beta; -import autosaveworld.zlibs.com.google.api.client.util.Data; - -/** - * {@link Beta}
- * Declares that the data type enclosing this field is polymorphic, and that the value of this field - * in a heterogeneous JSON schema will determine what type the data should be parsed into. - * - *

- * A data structure must have no more than one field with this annotation present. The annotated - * field's type must be considered "primitive" by {@link Data#isPrimitive(Type)}. The field's value - * will be compared against the {@link TypeDef#key()} using {@link Object#toString()}. - *

- * - * @author Nick Miceli - * @since 1.16 - */ -@Target(ElementType.FIELD) -@Retention(RetentionPolicy.RUNTIME) -@Beta -public @interface JsonPolymorphicTypeMap { - - /** The list of mappings from key value to a referenced {@link Class}. */ - TypeDef[] typeDefinitions(); - - /** - * Declares a mapping between a key value and a referenced class. - */ - @Target(ElementType.FIELD) - @Retention(RetentionPolicy.RUNTIME) - public @interface TypeDef { - - /** The string value to represent a specific type. */ - String key(); - - /** The {@link Class} that is referenced by this key value. */ - Class ref(); - } - -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/json/JsonString.java b/src/autosaveworld/zlibs/com/google/api/client/json/JsonString.java deleted file mode 100644 index 0f414d0c..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/json/JsonString.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.json; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Use this annotation to specify that a declared numeric Java field should map to a JSON string. - * - *

- * By default declared Java numeric fields are stored as JSON numbers. For example: - * - *

- * 
-class A {
-  @Key BigInteger value;
-}
- * 
- * 
- * - * can be used for this JSON content: - * - *
- * 
-{"value" : 12345768901234576890123457689012345768901234576890}
- * 
- * 
- * - * However, if instead the JSON content uses a JSON String to store the value, one needs to use the - * {@link JsonString} annotation. For example: - * - *
- * 
-class B {
-  @Key @JsonString BigInteger value;
-}
- * 
- * 
- * - * can be used for this JSON content: - * - *
- * 
-{"value" : "12345768901234576890123457689012345768901234576890"}
- * 
- * 
- *

- * - * @since 1.3 - * @author Yaniv Inbar - */ -// TODO(yanivi): remove JsonString and instead declare new primitives BigIntegerString and -// BigDecimalString? -@Target(ElementType.FIELD) -@Retention(RetentionPolicy.RUNTIME) -public @interface JsonString { -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/json/JsonToken.java b/src/autosaveworld/zlibs/com/google/api/client/json/JsonToken.java deleted file mode 100644 index 43e6b3c3..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/json/JsonToken.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.json; - -/** - * JSON token in the low-level JSON library. - * - * @since 1.3 - * @author Yaniv Inbar - */ -public enum JsonToken { - - /** Start of a JSON array ('['). */ - START_ARRAY, - - /** End of a JSON array (']'). */ - END_ARRAY, - - /** Start of a JSON object ('{'). */ - START_OBJECT, - - /** End of a JSON object ('}'). */ - END_OBJECT, - - /** JSON field name. */ - FIELD_NAME, - - /** JSON field string value. */ - VALUE_STRING, - - /** - * JSON field number value of an integer with an arbitrary number of digits and no fractional - * part. - */ - VALUE_NUMBER_INT, - - /** JSON field number value of an arbitrary-precision decimal number. */ - VALUE_NUMBER_FLOAT, - - /** JSON field {@code true} value. */ - VALUE_TRUE, - - /** JSON field {@code false} value. */ - VALUE_FALSE, - - /** JSON {@code null}. */ - VALUE_NULL, - - /** Some other token. */ - NOT_AVAILABLE -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/json/jackson2/JacksonFactory.java b/src/autosaveworld/zlibs/com/google/api/client/json/jackson2/JacksonFactory.java deleted file mode 100644 index b62ef3b7..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/json/jackson2/JacksonFactory.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.json.jackson2; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; -import java.nio.charset.Charset; - -import autosaveworld.zlibs.com.google.api.client.json.JsonFactory; -import autosaveworld.zlibs.com.google.api.client.json.JsonGenerator; -import autosaveworld.zlibs.com.google.api.client.json.JsonParser; -import autosaveworld.zlibs.com.google.api.client.json.JsonToken; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * Low-level JSON library implementation based on Jackson 2. - * - *

- * Implementation is thread-safe, and sub-classes must be thread-safe. For maximum efficiency, - * applications should use a single globally-shared instance of the JSON factory. - *

- * - * @since 1.11 - * @author Yaniv Inbar - */ -public final class JacksonFactory extends JsonFactory { - - /** JSON factory. */ - private final autosaveworld.zlibs.com.fasterxml.jackson.core.JsonFactory factory = - new autosaveworld.zlibs.com.fasterxml.jackson.core.JsonFactory(); - { - // don't auto-close JSON content in order to ensure consistent behavior across JSON factories - // TODO(rmistry): Should we disable the JsonGenerator.Feature.AUTO_CLOSE_TARGET feature? - factory.configure( - autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator.Feature.AUTO_CLOSE_JSON_CONTENT, false); - } - - /** - * Returns a global thread-safe instance. - * - * @since 1.16 - */ - public static JacksonFactory getDefaultInstance() { - return InstanceHolder.INSTANCE; - } - - /** Holder for the result of {@link #getDefaultInstance()}. */ - static class InstanceHolder { - static final JacksonFactory INSTANCE = new JacksonFactory(); - } - - @SuppressWarnings("deprecation") -@Override - public JsonGenerator createJsonGenerator(OutputStream out, Charset enc) throws IOException { - return new JacksonGenerator( - this, factory.createJsonGenerator(out, autosaveworld.zlibs.com.fasterxml.jackson.core.JsonEncoding.UTF8)); - } - - @SuppressWarnings("deprecation") -@Override - public JsonGenerator createJsonGenerator(Writer writer) throws IOException { - return new JacksonGenerator(this, factory.createJsonGenerator(writer)); - } - - @SuppressWarnings("deprecation") -@Override - public JsonParser createJsonParser(Reader reader) throws IOException { - Preconditions.checkNotNull(reader); - return new JacksonParser(this, factory.createJsonParser(reader)); - } - - @SuppressWarnings("deprecation") -@Override - public JsonParser createJsonParser(InputStream in) throws IOException { - Preconditions.checkNotNull(in); - return new JacksonParser(this, factory.createJsonParser(in)); - } - - @SuppressWarnings("deprecation") -@Override - public JsonParser createJsonParser(InputStream in, Charset charset) throws IOException { - Preconditions.checkNotNull(in); - return new JacksonParser(this, factory.createJsonParser(in)); - } - - @SuppressWarnings("deprecation") -@Override - public JsonParser createJsonParser(String value) throws IOException { - Preconditions.checkNotNull(value); - return new JacksonParser(this, factory.createJsonParser(value)); - } - - static JsonToken convert(autosaveworld.zlibs.com.fasterxml.jackson.core.JsonToken token) { - if (token == null) { - return null; - } - switch (token) { - case END_ARRAY: - return JsonToken.END_ARRAY; - case START_ARRAY: - return JsonToken.START_ARRAY; - case END_OBJECT: - return JsonToken.END_OBJECT; - case START_OBJECT: - return JsonToken.START_OBJECT; - case VALUE_FALSE: - return JsonToken.VALUE_FALSE; - case VALUE_TRUE: - return JsonToken.VALUE_TRUE; - case VALUE_NULL: - return JsonToken.VALUE_NULL; - case VALUE_STRING: - return JsonToken.VALUE_STRING; - case VALUE_NUMBER_FLOAT: - return JsonToken.VALUE_NUMBER_FLOAT; - case VALUE_NUMBER_INT: - return JsonToken.VALUE_NUMBER_INT; - case FIELD_NAME: - return JsonToken.FIELD_NAME; - default: - return JsonToken.NOT_AVAILABLE; - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/json/jackson2/JacksonGenerator.java b/src/autosaveworld/zlibs/com/google/api/client/json/jackson2/JacksonGenerator.java deleted file mode 100644 index 6efae6dc..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/json/jackson2/JacksonGenerator.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.json.jackson2; - -import java.io.IOException; -import java.math.BigDecimal; -import java.math.BigInteger; - -import autosaveworld.zlibs.com.google.api.client.json.JsonGenerator; - -/** - * Low-level JSON serializer implementation based on Jackson. - * - *

- * Implementation is not thread-safe. - *

- * - * @author Yaniv Inbar - */ -final class JacksonGenerator extends JsonGenerator { - private final autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator generator; - private final JacksonFactory factory; - - @Override - public JacksonFactory getFactory() { - return factory; - } - - JacksonGenerator(JacksonFactory factory, autosaveworld.zlibs.com.fasterxml.jackson.core.JsonGenerator generator) { - this.factory = factory; - this.generator = generator; - } - - @Override - public void flush() throws IOException { - generator.flush(); - } - - @Override - public void close() throws IOException { - generator.close(); - } - - @Override - public void writeBoolean(boolean state) throws IOException { - generator.writeBoolean(state); - } - - @Override - public void writeEndArray() throws IOException { - generator.writeEndArray(); - } - - @Override - public void writeEndObject() throws IOException { - generator.writeEndObject(); - } - - @Override - public void writeFieldName(String name) throws IOException { - generator.writeFieldName(name); - } - - @Override - public void writeNull() throws IOException { - generator.writeNull(); - } - - @Override - public void writeNumber(int v) throws IOException { - generator.writeNumber(v); - } - - @Override - public void writeNumber(long v) throws IOException { - generator.writeNumber(v); - } - - @Override - public void writeNumber(BigInteger v) throws IOException { - generator.writeNumber(v); - } - - @Override - public void writeNumber(double v) throws IOException { - generator.writeNumber(v); - } - - @Override - public void writeNumber(float v) throws IOException { - generator.writeNumber(v); - } - - @Override - public void writeNumber(BigDecimal v) throws IOException { - generator.writeNumber(v); - } - - @Override - public void writeNumber(String encodedValue) throws IOException { - generator.writeNumber(encodedValue); - } - - @Override - public void writeStartArray() throws IOException { - generator.writeStartArray(); - } - - @Override - public void writeStartObject() throws IOException { - generator.writeStartObject(); - } - - @Override - public void writeString(String value) throws IOException { - generator.writeString(value); - } - - @Override - public void enablePrettyPrint() throws IOException { - generator.useDefaultPrettyPrinter(); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/json/jackson2/JacksonParser.java b/src/autosaveworld/zlibs/com/google/api/client/json/jackson2/JacksonParser.java deleted file mode 100644 index e7abdaaf..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/json/jackson2/JacksonParser.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.json.jackson2; - -import java.io.IOException; -import java.math.BigDecimal; -import java.math.BigInteger; - -import autosaveworld.zlibs.com.google.api.client.json.JsonParser; -import autosaveworld.zlibs.com.google.api.client.json.JsonToken; - -/** - * Low-level JSON serializer implementation based on Jackson. - * - *

- * Implementation is not thread-safe. - *

- * - * @author Yaniv Inbar - */ -final class JacksonParser extends JsonParser { - - private final autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser parser; - private final JacksonFactory factory; - - @Override - public JacksonFactory getFactory() { - return factory; - } - - JacksonParser(JacksonFactory factory, autosaveworld.zlibs.com.fasterxml.jackson.core.JsonParser parser) { - this.factory = factory; - this.parser = parser; - } - - @Override - public void close() throws IOException { - parser.close(); - } - - @Override - public JsonToken nextToken() throws IOException { - return JacksonFactory.convert(parser.nextToken()); - } - - @Override - public String getCurrentName() throws IOException { - return parser.getCurrentName(); - } - - @Override - public JsonToken getCurrentToken() { - return JacksonFactory.convert(parser.getCurrentToken()); - } - - @Override - public JsonParser skipChildren() throws IOException { - parser.skipChildren(); - return this; - } - - @Override - public String getText() throws IOException { - return parser.getText(); - } - - @Override - public byte getByteValue() throws IOException { - return parser.getByteValue(); - } - - @Override - public float getFloatValue() throws IOException { - return parser.getFloatValue(); - } - - @Override - public int getIntValue() throws IOException { - return parser.getIntValue(); - } - - @Override - public short getShortValue() throws IOException { - return parser.getShortValue(); - } - - @Override - public BigInteger getBigIntegerValue() throws IOException { - return parser.getBigIntegerValue(); - } - - @Override - public BigDecimal getDecimalValue() throws IOException { - return parser.getDecimalValue(); - } - - @Override - public double getDoubleValue() throws IOException { - return parser.getDoubleValue(); - } - - @Override - public long getLongValue() throws IOException { - return parser.getLongValue(); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/json/webtoken/JsonWebSignature.java b/src/autosaveworld/zlibs/com/google/api/client/json/webtoken/JsonWebSignature.java deleted file mode 100644 index b4b98245..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/json/webtoken/JsonWebSignature.java +++ /dev/null @@ -1,641 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.json.webtoken; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.Signature; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.List; - -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; - -import autosaveworld.zlibs.com.google.api.client.json.JsonFactory; -import autosaveworld.zlibs.com.google.api.client.util.Base64; -import autosaveworld.zlibs.com.google.api.client.util.Beta; -import autosaveworld.zlibs.com.google.api.client.util.Key; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; -import autosaveworld.zlibs.com.google.api.client.util.SecurityUtils; -import autosaveworld.zlibs.com.google.api.client.util.StringUtils; - -/** - * JSON Web Signature - * (JWS). - * - *

- * Sample usage: - *

- * - *
-  public static void printPayload(JsonFactory jsonFactory, String tokenString) throws IOException {
-    JsonWebSignature jws = JsonWebSignature.parse(jsonFactory, tokenString);
-    System.out.println(jws.getPayload());
-  }
- * 
- * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.14 (since 1.7 as com.google.api.client.auth.jsontoken.JsonWebSignature) - * @author Yaniv Inbar - */ -public class JsonWebSignature extends JsonWebToken { - - /** Bytes of the signature. */ - private final byte[] signatureBytes; - - /** Bytes of the signature content. */ - private final byte[] signedContentBytes; - - /** - * @param header header - * @param payload payload - * @param signatureBytes bytes of the signature - * @param signedContentBytes bytes of the signature content - */ - public JsonWebSignature( - Header header, Payload payload, byte[] signatureBytes, byte[] signedContentBytes) { - super(header, payload); - this.signatureBytes = Preconditions.checkNotNull(signatureBytes); - this.signedContentBytes = Preconditions.checkNotNull(signedContentBytes); - } - - /** - * Header as specified in Reserved - * Header Parameter Names. - */ - public static class Header extends JsonWebToken.Header { - - /** - * Algorithm header parameter that identifies the cryptographic algorithm used to secure the JWS - * or {@code null} for none. - */ - @Key("alg") - private String algorithm; - - /** - * JSON Web Key URL header parameter that is an absolute URL that refers to a resource for a set - * of JSON-encoded public keys, one of which corresponds to the key that was used to digitally - * sign the JWS or {@code null} for none. - */ - @Key("jku") - private String jwkUrl; - - /** - * JSON Web Key header parameter that is a public key that corresponds to the key used to - * digitally sign the JWS or {@code null} for none. - */ - @Key("jwk") - private String jwk; - - /** - * Key ID header parameter that is a hint indicating which specific key owned by the signer - * should be used to validate the digital signature or {@code null} for none. - */ - @Key("kid") - private String keyId; - - /** - * X.509 URL header parameter that is an absolute URL that refers to a resource for the X.509 - * public key certificate or certificate chain corresponding to the key used to digitally sign - * the JWS or {@code null} for none. - */ - @Key("x5u") - private String x509Url; - - /** - * X.509 certificate thumbprint header parameter that provides a base64url encoded SHA-1 - * thumbprint (a.k.a. digest) of the DER encoding of an X.509 certificate that can be used to - * match the certificate or {@code null} for none. - */ - @Key("x5t") - private String x509Thumbprint; - - /** - * X.509 certificate chain header parameter contains the X.509 public key certificate or - * certificate chain corresponding to the key used to digitally sign the JWS or {@code null} for - * none. - * - * @since 1.19.1. - */ - @Key("x5c") - private List x509Certificates; - - /** - * Array listing the header parameter names that define extensions that are used in the JWS - * header that MUST be understood and processed or {@code null} for none. - */ - @Key("crit") - private List critical; - - @Override - public Header setType(String type) { - super.setType(type); - return this; - } - - /** - * Returns the algorithm header parameter that identifies the cryptographic algorithm used to - * secure the JWS or {@code null} for none. - */ - public final String getAlgorithm() { - return algorithm; - } - - /** - * Sets the algorithm header parameter that identifies the cryptographic algorithm used to - * secure the JWS or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Header setAlgorithm(String algorithm) { - this.algorithm = algorithm; - return this; - } - - /** - * Returns the JSON Web Key URL header parameter that is an absolute URL that refers to a - * resource for a set of JSON-encoded public keys, one of which corresponds to the key that was - * used to digitally sign the JWS or {@code null} for none. - */ - public final String getJwkUrl() { - return jwkUrl; - } - - /** - * Sets the JSON Web Key URL header parameter that is an absolute URL that refers to a resource - * for a set of JSON-encoded public keys, one of which corresponds to the key that was used to - * digitally sign the JWS or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Header setJwkUrl(String jwkUrl) { - this.jwkUrl = jwkUrl; - return this; - } - - /** - * Returns the JSON Web Key header parameter that is a public key that corresponds to the key - * used to digitally sign the JWS or {@code null} for none. - */ - public final String getJwk() { - return jwk; - } - - /** - * Sets the JSON Web Key header parameter that is a public key that corresponds to the key used - * to digitally sign the JWS or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Header setJwk(String jwk) { - this.jwk = jwk; - return this; - } - - /** - * Returns the key ID header parameter that is a hint indicating which specific key owned by the - * signer should be used to validate the digital signature or {@code null} for none. - */ - public final String getKeyId() { - return keyId; - } - - /** - * Sets the key ID header parameter that is a hint indicating which specific key owned by the - * signer should be used to validate the digital signature or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Header setKeyId(String keyId) { - this.keyId = keyId; - return this; - } - - /** - * Returns the X.509 URL header parameter that is an absolute URL that refers to a resource for - * the X.509 public key certificate or certificate chain corresponding to the key used to - * digitally sign the JWS or {@code null} for none. - */ - public final String getX509Url() { - return x509Url; - } - - /** - * Sets the X.509 URL header parameter that is an absolute URL that refers to a resource for the - * X.509 public key certificate or certificate chain corresponding to the key used to digitally - * sign the JWS or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Header setX509Url(String x509Url) { - this.x509Url = x509Url; - return this; - } - - /** - * Returns the X.509 certificate thumbprint header parameter that provides a base64url encoded - * SHA-1 thumbprint (a.k.a. digest) of the DER encoding of an X.509 certificate that can be used - * to match the certificate or {@code null} for none. - */ - public final String getX509Thumbprint() { - return x509Thumbprint; - } - - /** - * Sets the X.509 certificate thumbprint header parameter that provides a base64url encoded - * SHA-1 thumbprint (a.k.a. digest) of the DER encoding of an X.509 certificate that can be used - * to match the certificate or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Header setX509Thumbprint(String x509Thumbprint) { - this.x509Thumbprint = x509Thumbprint; - return this; - } - - /** - * Returns the X.509 certificate chain header parameter contains the X.509 public key - * certificate or corresponding to the key used to digitally sign the JWS or {@code null} for - * none. - * - *

@deprecated Since release 1.19.1, replaced by {@link #getX509Certificates()}. - */ - @Deprecated - public final String getX509Certificate() { - if (x509Certificates == null || x509Certificates.isEmpty()) { - return null; - } - return x509Certificates.get(0); - } - - /** - * Returns the X.509 certificate chain header parameter contains the X.509 public key - * certificate or certificate chain corresponding to the key used to digitally sign the JWS or - * {@code null} for none. - * - * @since 1.19.1. - */ - public final List getX509Certificates() { - return x509Certificates; - } - - /** - * Sets the X.509 certificate chain header parameter contains the X.509 public key certificate - * corresponding to the key used to digitally sign the JWS or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - *

@deprecated Since release 1.19.1, replaced by - * {@link #setX509Certificates(List x509Certificates)}. - */ - @Deprecated - public Header setX509Certificate(String x509Certificate) { - ArrayList x509Certificates = new ArrayList(); - x509Certificates.add(x509Certificate); - this.x509Certificates = x509Certificates; - return this; - } - - /** - * Sets the X.509 certificate chain header parameter contains the X.509 public key certificate - * or certificate chain corresponding to the key used to digitally sign the JWS or {@code null} - * for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.19.1. - */ - public Header setX509Certificates(List x509Certificates) { - this.x509Certificates = x509Certificates; - return this; - } - - /** - * Returns the array listing the header parameter names that define extensions that are used in - * the JWS header that MUST be understood and processed or {@code null} for none. - * - * @since 1.16 - */ - public final List getCritical() { - return critical; - } - - /** - * Sets the array listing the header parameter names that define extensions that are used in the - * JWS header that MUST be understood and processed or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- * - * @since 1.16 - */ - public Header setCritical(List critical) { - this.critical = critical; - return this; - } - - @Override - public Header set(String fieldName, Object value) { - return (Header) super.set(fieldName, value); - } - - @Override - public Header clone() { - return (Header) super.clone(); - } - } - - @Override - public Header getHeader() { - return (Header) super.getHeader(); - } - - /** - * Verifies the signature of the content. - * - *

- * Currently only {@code "RS256"} algorithm is verified, but others may be added in the future. - * For any other algorithm it returns {@code false}. - *

- * - * @param publicKey public key - * @return whether the algorithm is recognized and it is verified - * @throws GeneralSecurityException - */ - public final boolean verifySignature(PublicKey publicKey) throws GeneralSecurityException { - Signature signatureAlg = null; - String algorithm = getHeader().getAlgorithm(); - if ("RS256".equals(algorithm)) { - signatureAlg = SecurityUtils.getSha256WithRsaSignatureAlgorithm(); - } else { - return false; - } - return SecurityUtils.verify(signatureAlg, publicKey, signatureBytes, signedContentBytes); - } - - /** - * {@link Beta}
- * Verifies the signature of the content using the certificate chain embedded in the signature. - * - *

- * Currently only {@code "RS256"} algorithm is verified, but others may be added in the future. - * For any other algorithm it returns {@code null}. - *

- * - *

- * The leaf certificate of the certificate chain must be an SSL server certificate. - *

- * - * @param trustManager Trust manager used to verify the X509 certificate chain embedded in this - * message. - * @return The signature certificate if the signature could be verified, null otherwise. - * @throws GeneralSecurityException - * @since 1.19.1. - */ - @Beta - public final X509Certificate verifySignature(X509TrustManager trustManager) - throws GeneralSecurityException { - List x509Certificates = getHeader().getX509Certificates(); - if (x509Certificates == null || x509Certificates.isEmpty()) { - return null; - } - String algorithm = getHeader().getAlgorithm(); - Signature signatureAlg = null; - if ("RS256".equals(algorithm)) { - signatureAlg = SecurityUtils.getSha256WithRsaSignatureAlgorithm(); - } else { - return null; - } - return SecurityUtils.verify(signatureAlg, trustManager, x509Certificates, signatureBytes, - signedContentBytes); - } - - /** - * {@link Beta}
- * Verifies the signature of the content using the certificate chain embedded in the signature. - * - *

- * Currently only {@code "RS256"} algorithm is verified, but others may be added in the future. - * For any other algorithm it returns {@code null}. - *

- * - *

- * The certificate chain is verified using the system default trust manager. - *

- * - *

- * The leaf certificate of the certificate chain must be an SSL server certificate. - *

- * - * @return The signature certificate if the signature could be verified, null otherwise. - * @throws GeneralSecurityException - * @since 1.19.1. - */ - @Beta - public final X509Certificate verifySignature() throws GeneralSecurityException { - X509TrustManager trustManager = getDefaultX509TrustManager(); - if (trustManager == null) { - return null; - } - return verifySignature(trustManager); - } - - private static X509TrustManager getDefaultX509TrustManager() { - try { - TrustManagerFactory factory = - TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - factory.init((KeyStore) null); - for (TrustManager manager : factory.getTrustManagers()) { - if (manager instanceof X509TrustManager) { - return (X509TrustManager) manager; - } - } - return null; - } catch (NoSuchAlgorithmException e) { - return null; - } catch (KeyStoreException e) { - return null; - } - } - - /** Returns the modifiable array of bytes of the signature. */ - public final byte[] getSignatureBytes() { - return signatureBytes; - } - - /** Returns the modifiable array of bytes of the signature content. */ - public final byte[] getSignedContentBytes() { - return signedContentBytes; - } - - /** - * Parses the given JWS token string and returns the parsed {@link JsonWebSignature}. - * - * @param jsonFactory JSON factory - * @param tokenString JWS token string - * @return parsed JWS - */ - public static JsonWebSignature parse(JsonFactory jsonFactory, String tokenString) - throws IOException { - return parser(jsonFactory).parse(tokenString); - } - - /** Returns a new instance of a JWS parser. */ - public static Parser parser(JsonFactory jsonFactory) { - return new Parser(jsonFactory); - } - - /** - * JWS parser. - * - *

- * Implementation is not thread-safe. - *

- */ - public static final class Parser { - - /** JSON factory. */ - private final JsonFactory jsonFactory; - - /** Header class to use for parsing. */ - private Class headerClass = Header.class; - - /** Payload class to use for parsing. */ - private Class payloadClass = Payload.class; - - /** - * @param jsonFactory JSON factory - */ - public Parser(JsonFactory jsonFactory) { - this.jsonFactory = Preconditions.checkNotNull(jsonFactory); - } - - /** Returns the header class to use for parsing. */ - public Class getHeaderClass() { - return headerClass; - } - - /** Sets the header class to use for parsing. */ - public Parser setHeaderClass(Class headerClass) { - this.headerClass = headerClass; - return this; - } - - /** Returns the payload class to use for parsing. */ - public Class getPayloadClass() { - return payloadClass; - } - - /** Sets the payload class to use for parsing. */ - public Parser setPayloadClass(Class payloadClass) { - this.payloadClass = payloadClass; - return this; - } - - /** Returns the JSON factory. */ - public JsonFactory getJsonFactory() { - return jsonFactory; - } - - /** - * Parses a JWS token into a parsed {@link JsonWebSignature}. - * - * @param tokenString JWS token string - * @return parsed {@link JsonWebSignature} - */ - public JsonWebSignature parse(String tokenString) throws IOException { - // split on the dots - int firstDot = tokenString.indexOf('.'); - Preconditions.checkArgument(firstDot != -1); - byte[] headerBytes = Base64.decodeBase64(tokenString.substring(0, firstDot)); - int secondDot = tokenString.indexOf('.', firstDot + 1); - Preconditions.checkArgument(secondDot != -1); - Preconditions.checkArgument(tokenString.indexOf('.', secondDot + 1) == -1); - // decode the bytes - byte[] payloadBytes = Base64.decodeBase64(tokenString.substring(firstDot + 1, secondDot)); - byte[] signatureBytes = Base64.decodeBase64(tokenString.substring(secondDot + 1)); - byte[] signedContentBytes = StringUtils.getBytesUtf8(tokenString.substring(0, secondDot)); - // parse the header and payload - Header header = - jsonFactory.fromInputStream(new ByteArrayInputStream(headerBytes), headerClass); - Preconditions.checkArgument(header.getAlgorithm() != null); - Payload payload = - jsonFactory.fromInputStream(new ByteArrayInputStream(payloadBytes), payloadClass); - return new JsonWebSignature(header, payload, signatureBytes, signedContentBytes); - } - } - - /** - * Signs a given JWS header and payload based on the given private key using RSA and SHA-256 as - * described in JWS using - * RSA SHA-256. - * - * @param privateKey private key - * @param jsonFactory JSON factory - * @param header JWS header - * @param payload JWS payload - * @return signed JWS string - * @since 1.14 (since 1.7 as com.google.api.client.auth.jsontoken.RsaSHA256Signer) - */ - public static String signUsingRsaSha256(PrivateKey privateKey, JsonFactory jsonFactory, - JsonWebSignature.Header header, JsonWebToken.Payload payload) - throws GeneralSecurityException, IOException { - String content = Base64.encodeBase64URLSafeString(jsonFactory.toByteArray(header)) + "." - + Base64.encodeBase64URLSafeString(jsonFactory.toByteArray(payload)); - byte[] contentBytes = StringUtils.getBytesUtf8(content); - byte[] signature = SecurityUtils.sign( - SecurityUtils.getSha256WithRsaSignatureAlgorithm(), privateKey, contentBytes); - return content + "." + Base64.encodeBase64URLSafeString(signature); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/json/webtoken/JsonWebToken.java b/src/autosaveworld/zlibs/com/google/api/client/json/webtoken/JsonWebToken.java deleted file mode 100644 index f9887625..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/json/webtoken/JsonWebToken.java +++ /dev/null @@ -1,412 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.json.webtoken; - -import java.util.Collections; -import java.util.List; - -import autosaveworld.zlibs.com.google.api.client.json.GenericJson; -import autosaveworld.zlibs.com.google.api.client.util.Key; -import autosaveworld.zlibs.com.google.api.client.util.Objects; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * JSON Web Token (JWT). - * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.14 (since 1.7 as com.google.api.client.auth.jsontoken.JsonWebToken) - * @author Yaniv Inbar - */ -public class JsonWebToken { - - /** Header. */ - private final Header header; - - /** Payload. */ - private final Payload payload; - - /** - * @param header header - * @param payload payload - */ - public JsonWebToken(Header header, Payload payload) { - this.header = Preconditions.checkNotNull(header); - this.payload = Preconditions.checkNotNull(payload); - } - - /** - * Header as specified in JWT Header. - */ - public static class Header extends GenericJson { - - /** Type header parameter used to declare the type of this object or {@code null} for none. */ - @Key("typ") - private String type; - - /** - * Content type header parameter used to declare structural information about the JWT or - * {@code null} for none. - */ - @Key("cty") - private String contentType; - - /** - * Returns the type header parameter used to declare the type of this object or {@code null} for - * none. - */ - public final String getType() { - return type; - } - - /** - * Sets the type header parameter used to declare the type of this object or {@code null} for - * none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Header setType(String type) { - this.type = type; - return this; - } - - /** - * Returns the content type header parameter used to declare structural information about the - * JWT or {@code null} for none. - */ - public final String getContentType() { - return contentType; - } - - /** - * Sets the content type header parameter used to declare structural information about the JWT - * or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Header setContentType(String contentType) { - this.contentType = contentType; - return this; - } - - @Override - public Header set(String fieldName, Object value) { - return (Header) super.set(fieldName, value); - } - - @Override - public Header clone() { - return (Header) super.clone(); - } - } - - /** - * Payload as specified in Reserved Claim - * Names. - */ - public static class Payload extends GenericJson { - - /** - * Expiration time claim that identifies the expiration time (in seconds) on or after which the - * token MUST NOT be accepted for processing or {@code null} for none. - */ - @Key("exp") - private Long expirationTimeSeconds; - - /** - * Not before claim that identifies the time (in seconds) before which the token MUST NOT be - * accepted for processing or {@code null} for none. - */ - @Key("nbf") - private Long notBeforeTimeSeconds; - - /** - * Issued at claim that identifies the time (in seconds) at which the JWT was issued or - * {@code null} for none. - */ - @Key("iat") - private Long issuedAtTimeSeconds; - - /** Issuer claim that identifies the principal that issued the JWT or {@code null} for none. */ - @Key("iss") - private String issuer; - - /** - * Audience claim that identifies the audience that the JWT is intended for (should either be a - * {@code String} or a {@code List}) or {@code null} for none. - */ - @Key("aud") - private Object audience; - - /** - * JWT ID claim that provides a unique identifier for the JWT or {@code null} for none. - */ - @Key("jti") - private String jwtId; - - /** - * Type claim that is used to declare a type for the contents of this JWT Claims Set or - * {@code null} for none. - */ - @Key("typ") - private String type; - - /** - * Subject claim identifying the principal that is the subject of the JWT or {@code null} for - * none. - */ - @Key("sub") - private String subject; - - /** - * Returns the expiration time (in seconds) claim that identifies the expiration time on or - * after which the token MUST NOT be accepted for processing or {@code null} for none. - */ - public final Long getExpirationTimeSeconds() { - return expirationTimeSeconds; - } - - /** - * Sets the expiration time claim that identifies the expiration time (in seconds) on or after - * which the token MUST NOT be accepted for processing or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Payload setExpirationTimeSeconds(Long expirationTimeSeconds) { - this.expirationTimeSeconds = expirationTimeSeconds; - return this; - } - - /** - * Returns the not before claim that identifies the time (in seconds) before which the token - * MUST NOT be accepted for processing or {@code null} for none. - */ - public final Long getNotBeforeTimeSeconds() { - return notBeforeTimeSeconds; - } - - /** - * Sets the not before claim that identifies the time (in seconds) before which the token MUST - * NOT be accepted for processing or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Payload setNotBeforeTimeSeconds(Long notBeforeTimeSeconds) { - this.notBeforeTimeSeconds = notBeforeTimeSeconds; - return this; - } - - /** - * Returns the issued at claim that identifies the time (in seconds) at which the JWT was issued - * or {@code null} for none. - */ - public final Long getIssuedAtTimeSeconds() { - return issuedAtTimeSeconds; - } - - /** - * Sets the issued at claim that identifies the time (in seconds) at which the JWT was issued or - * {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Payload setIssuedAtTimeSeconds(Long issuedAtTimeSeconds) { - this.issuedAtTimeSeconds = issuedAtTimeSeconds; - return this; - } - - /** - * Returns the issuer claim that identifies the principal that issued the JWT or {@code null} - * for none. - */ - public final String getIssuer() { - return issuer; - } - - /** - * Sets the issuer claim that identifies the principal that issued the JWT or {@code null} for - * none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Payload setIssuer(String issuer) { - this.issuer = issuer; - return this; - } - - /** - * Returns the audience claim that identifies the audience that the JWT is intended for (should - * either be a {@code String} or a {@code List}) or {@code null} for none. - */ - public final Object getAudience() { - return audience; - } - - /** - * Returns the list of audience claim that identifies the audience that the JWT is intended for - * or empty for none. - */ - @SuppressWarnings("unchecked") - public final List getAudienceAsList() { - if (audience == null) { - return Collections.emptyList(); - } - if (audience instanceof String) { - return Collections.singletonList((String) audience); - } - return (List) audience; - } - - /** - * Sets the audience claim that identifies the audience that the JWT is intended for (should - * either be a {@code String} or a {@code List}) or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Payload setAudience(Object audience) { - this.audience = audience; - return this; - } - - /** - * Returns the JWT ID claim that provides a unique identifier for the JWT or {@code null} for - * none. - */ - public final String getJwtId() { - return jwtId; - } - - /** - * Sets the JWT ID claim that provides a unique identifier for the JWT or {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Payload setJwtId(String jwtId) { - this.jwtId = jwtId; - return this; - } - - /** - * Returns the type claim that is used to declare a type for the contents of this JWT Claims Set - * or {@code null} for none. - */ - public final String getType() { - return type; - } - - /** - * Sets the type claim that is used to declare a type for the contents of this JWT Claims Set or - * {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Payload setType(String type) { - this.type = type; - return this; - } - - /** - * Returns the subject claim identifying the principal that is the subject of the JWT or - * {@code null} for none. - */ - public final String getSubject() { - return subject; - } - - /** - * Sets the subject claim identifying the principal that is the subject of the JWT or - * {@code null} for none. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Payload setSubject(String subject) { - this.subject = subject; - return this; - } - - @Override - public Payload set(String fieldName, Object value) { - return (Payload) super.set(fieldName, value); - } - - @Override - public Payload clone() { - return (Payload) super.clone(); - } - } - - @Override - public String toString() { - return Objects.toStringHelper(this).add("header", header).add("payload", payload).toString(); - } - - /** - * Returns the header. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Header getHeader() { - return header; - } - - /** - * Returns the payload. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public Payload getPayload() { - return payload; - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/ArrayMap.java b/src/autosaveworld/zlibs/com/google/api/client/util/ArrayMap.java deleted file mode 100644 index 62627123..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/ArrayMap.java +++ /dev/null @@ -1,434 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.util.AbstractMap; -import java.util.AbstractSet; -import java.util.Iterator; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; - -/** - * Memory-efficient map of keys to values with list-style random-access semantics. - * - *

- * Supports null keys and values. Conceptually, the keys and values are stored in a simpler array in - * order to minimize memory use and provide for fast access to a key/value at a certain index (for - * example {@link #getKey(int)}). However, traditional mapping operations like {@link #get(Object)} - * and {@link #put(Object, Object)} are slower because they need to look up all key/value pairs in - * the worst case. - *

- * - *

- * Implementation is not thread-safe. For a thread-safe choice instead use an implementation of - * {@link ConcurrentMap}. - *

- * - * @param the type of keys maintained by this map - * @param the type of mapped values - * - * @since 1.0 - * @author Yaniv Inbar - */ -public class ArrayMap extends AbstractMap implements Cloneable { - int size; - private Object[] data; - - /** - * Returns a new instance of an array map with initial capacity of zero. Equivalent to calling the - * default constructor, except without the need to specify the type parameters. For example: - * {@code ArrayMap map = ArrayMap.create();}. - */ - public static ArrayMap create() { - return new ArrayMap(); - } - - /** - * Returns a new instance of an array map of the given initial capacity. For example: {@code - * ArrayMap map = ArrayMap.create(8);}. - */ - public static ArrayMap create(int initialCapacity) { - ArrayMap result = create(); - result.ensureCapacity(initialCapacity); - return result; - } - - /** - * Returns a new instance of an array map of the given key value pairs in alternating order. For - * example: {@code ArrayMap map = ArrayMap.of("key1", "value1", "key2", "value2", - * ...);}. - *

- * WARNING: there is no compile-time checking of the {@code keyValuePairs} parameter to ensure - * that the keys or values have the correct type, so if the wrong type is passed in, any problems - * will occur at runtime. Also, there is no checking that the keys are unique, which the caller - * must ensure is true. - */ - public static ArrayMap of(Object... keyValuePairs) { - ArrayMap result = create(1); - int length = keyValuePairs.length; - if (1 == length % 2) { - throw new IllegalArgumentException( - "missing value for last key: " + keyValuePairs[length - 1]); - } - result.size = keyValuePairs.length / 2; - Object[] data = result.data = new Object[length]; - System.arraycopy(keyValuePairs, 0, data, 0, length); - return result; - } - - /** Returns the number of key-value pairs set. */ - @Override - public final int size() { - return this.size; - } - - /** Returns the key at the given index or {@code null} if out of bounds. */ - public final K getKey(int index) { - if (index < 0 || index >= this.size) { - return null; - } - @SuppressWarnings("unchecked") - K result = (K) this.data[index << 1]; - return result; - } - - /** Returns the value at the given index or {@code null} if out of bounds. */ - public final V getValue(int index) { - if (index < 0 || index >= this.size) { - return null; - } - return valueAtDataIndex(1 + (index << 1)); - } - - /** - * Sets the key/value mapping at the given index, overriding any existing key/value mapping. - *

- * There is no checking done to ensure that the key does not already exist. Therefore, this method - * is dangerous to call unless the caller can be certain the key does not already exist in the - * map. - * - * @return previous value or {@code null} for none - * @throws IndexOutOfBoundsException if index is negative - */ - public final V set(int index, K key, V value) { - if (index < 0) { - throw new IndexOutOfBoundsException(); - } - int minSize = index + 1; - ensureCapacity(minSize); - int dataIndex = index << 1; - V result = valueAtDataIndex(dataIndex + 1); - setData(dataIndex, key, value); - if (minSize > this.size) { - this.size = minSize; - } - return result; - } - - /** - * Sets the value at the given index, overriding any existing value mapping. - * - * @return previous value or {@code null} for none - * @throws IndexOutOfBoundsException if index is negative or {@code >=} size - */ - public final V set(int index, V value) { - int size = this.size; - if (index < 0 || index >= size) { - throw new IndexOutOfBoundsException(); - } - int valueDataIndex = 1 + (index << 1); - V result = valueAtDataIndex(valueDataIndex); - this.data[valueDataIndex] = value; - return result; - } - - /** - * Adds the key/value mapping at the end of the list. Behaves identically to {@code set(size(), - * key, value)}. - * - * @throws IndexOutOfBoundsException if index is negative - */ - public final void add(K key, V value) { - set(this.size, key, value); - } - - /** - * Removes the key/value mapping at the given index, or ignored if the index is out of bounds. - * - * @return previous value or {@code null} for none - */ - public final V remove(int index) { - return removeFromDataIndexOfKey(index << 1); - } - - /** Returns whether there is a mapping for the given key. */ - @Override - public final boolean containsKey(Object key) { - return -2 != getDataIndexOfKey(key); - } - - /** Returns the index of the given key or {@code -1} if there is no such key. */ - public final int getIndexOfKey(K key) { - return getDataIndexOfKey(key) >> 1; - } - - /** - * Returns the value set for the given key or {@code null} if there is no such mapping or if the - * mapping value is {@code null}. - */ - @Override - public final V get(Object key) { - return valueAtDataIndex(getDataIndexOfKey(key) + 1); - } - - /** - * Sets the value for the given key, overriding any existing value. - * - * @return previous value or {@code null} for none - */ - @Override - public final V put(K key, V value) { - int index = getIndexOfKey(key); - if (index == -1) { - index = this.size; - } - return set(index, key, value); - } - - /** - * Removes the key-value pair of the given key, or ignore if the key cannot be found. - * - * @return previous value or {@code null} for none - */ - @Override - public final V remove(Object key) { - return removeFromDataIndexOfKey(getDataIndexOfKey(key)); - } - - /** Trims the internal array storage to minimize memory usage. */ - public final void trim() { - setDataCapacity(this.size << 1); - } - - /** - * Ensures that the capacity of the internal arrays is at least a given capacity. - */ - public final void ensureCapacity(int minCapacity) { - if (minCapacity < 0) { - throw new IndexOutOfBoundsException(); - } - Object[] data = this.data; - int minDataCapacity = minCapacity << 1; - int oldDataCapacity = data == null ? 0 : data.length; - if (minDataCapacity > oldDataCapacity) { - int newDataCapacity = oldDataCapacity / 2 * 3 + 1; - if (newDataCapacity % 2 != 0) { - newDataCapacity++; - } - if (newDataCapacity < minDataCapacity) { - newDataCapacity = minDataCapacity; - } - setDataCapacity(newDataCapacity); - } - } - - private void setDataCapacity(int newDataCapacity) { - if (newDataCapacity == 0) { - this.data = null; - return; - } - int size = this.size; - Object[] oldData = this.data; - if (size == 0 || newDataCapacity != oldData.length) { - Object[] newData = this.data = new Object[newDataCapacity]; - if (size != 0) { - System.arraycopy(oldData, 0, newData, 0, size << 1); - } - } - } - - private void setData(int dataIndexOfKey, K key, V value) { - Object[] data = this.data; - data[dataIndexOfKey] = key; - data[dataIndexOfKey + 1] = value; - } - - private V valueAtDataIndex(int dataIndex) { - if (dataIndex < 0) { - return null; - } - @SuppressWarnings("unchecked") - V result = (V) this.data[dataIndex]; - return result; - } - - /** - * Returns the data index of the given key or {@code -2} if there is no such key. - */ - private int getDataIndexOfKey(Object key) { - int dataSize = this.size << 1; - Object[] data = this.data; - for (int i = 0; i < dataSize; i += 2) { - Object k = data[i]; - if (key == null ? k == null : key.equals(k)) { - return i; - } - } - return -2; - } - - /** - * Removes the key/value mapping at the given data index of key, or ignored if the index is out of - * bounds. - */ - private V removeFromDataIndexOfKey(int dataIndexOfKey) { - int dataSize = this.size << 1; - if (dataIndexOfKey < 0 || dataIndexOfKey >= dataSize) { - return null; - } - V result = valueAtDataIndex(dataIndexOfKey + 1); - Object[] data = this.data; - int moved = dataSize - dataIndexOfKey - 2; - if (moved != 0) { - System.arraycopy(data, dataIndexOfKey + 2, data, dataIndexOfKey, moved); - } - this.size--; - setData(dataSize - 2, null, null); - return result; - } - - @Override - public void clear() { - this.size = 0; - this.data = null; - } - - @Override - public final boolean containsValue(Object value) { - int dataSize = this.size << 1; - Object[] data = this.data; - for (int i = 1; i < dataSize; i += 2) { - Object v = data[i]; - if (value == null ? v == null : value.equals(v)) { - return true; - } - } - return false; - } - - @Override - public final Set> entrySet() { - return new EntrySet(); - } - - @Override - public ArrayMap clone() { - try { - @SuppressWarnings("unchecked") - ArrayMap result = (ArrayMap) super.clone(); - Object[] data = this.data; - if (data != null) { - int length = data.length; - Object[] resultData = result.data = new Object[length]; - System.arraycopy(data, 0, resultData, 0, length); - } - return result; - } catch (CloneNotSupportedException e) { - // won't happen - return null; - } - } - - final class EntrySet extends AbstractSet> { - - @Override - public Iterator> iterator() { - return new EntryIterator(); - } - - @Override - public int size() { - return ArrayMap.this.size; - } - } - - final class EntryIterator implements Iterator> { - - private boolean removed; - private int nextIndex; - - public boolean hasNext() { - return this.nextIndex < ArrayMap.this.size; - } - - public Map.Entry next() { - int index = this.nextIndex; - if (index == ArrayMap.this.size) { - throw new NoSuchElementException(); - } - this.nextIndex++; - return new Entry(index); - } - - public void remove() { - int index = this.nextIndex - 1; - if (this.removed || index < 0) { - throw new IllegalArgumentException(); - } - ArrayMap.this.remove(index); - this.removed = true; - } - } - - final class Entry implements Map.Entry { - - private int index; - - Entry(int index) { - this.index = index; - } - - public K getKey() { - return ArrayMap.this.getKey(this.index); - } - - public V getValue() { - return ArrayMap.this.getValue(this.index); - } - - public V setValue(V value) { - return ArrayMap.this.set(this.index, value); - } - - @Override - public int hashCode() { - return getKey().hashCode() ^ getValue().hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof Map.Entry)) { - return false; - } - Map.Entry other = (Map.Entry) obj; - return Objects.equal(getKey(), other.getKey()) && Objects.equal(getValue(), other.getValue()); - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/ArrayValueMap.java b/src/autosaveworld/zlibs/com/google/api/client/util/ArrayValueMap.java deleted file mode 100644 index 9b908aa7..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/ArrayValueMap.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -package autosaveworld.zlibs.com.google.api.client.util; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Map; -import java.util.concurrent.ConcurrentMap; - -/** - * Collects the array values of a key/value data object, writing the fields or map values only after - * all values have been collected. - * - *

- * The typical application for this is when parsing JSON or XML when the value type is known to be - * an array. It stores the values in a collection during the parsing, and only when the parsing of - * an object is finished does it convert the collection into an array and stores it. - *

- * - *

- * Use {@link #put(String, Class, Object)} when the destination object is a map with string keys and - * whose values accept an array of objects. Use {@link #put(Field, Class, Object)} when setting the - * value of a field using reflection, assuming its type accepts an array of objects. One can - * potentially use both {@code put} methods for example on an instance of {@link GenericData}. - *

- * - *

- * Implementation is not thread-safe. For a thread-safe choice instead use an implementation of - * {@link ConcurrentMap}. - *

- * - * @since 1.4 - * @author Yaniv Inbar - */ -public final class ArrayValueMap { - - /** Array values on a particular field. */ - static class ArrayValue { - - /** Array component type. */ - final Class componentType; - - /** Values to be stored in the array. */ - final ArrayList values = new ArrayList(); - - /** - * @param componentType array component type - */ - ArrayValue(Class componentType) { - this.componentType = componentType; - } - - /** Creates a new array whose content matches that of the {@link #values}. */ - Object toArray() { - return Types.toArray(values, componentType); - } - - /** - * Adds a given value to the array, checking the given component type matches the previously - * stored component type. - */ - void addValue(Class componentType, Object value) { - Preconditions.checkArgument(componentType == this.componentType); - values.add(value); - } - } - - /** Map from key name to its array values. */ - private final Map keyMap = ArrayMap.create(); - - /** Map from field to its array values. */ - private final Map fieldMap = ArrayMap.create(); - - /** Destination object whose fields must be set, or destination map whose values must be set. */ - private final Object destination; - - /** - * @param destination destination object whose fields must be set, or destination map whose values - * must be set - */ - public ArrayValueMap(Object destination) { - this.destination = destination; - } - - /** - * Sets the fields of the given object using the values collected during parsing of the object's - * fields. - */ - public void setValues() { - for (Map.Entry entry : keyMap.entrySet()) { - @SuppressWarnings("unchecked") - Map destinationMap = (Map) destination; - destinationMap.put(entry.getKey(), entry.getValue().toArray()); - } - for (Map.Entry entry : fieldMap.entrySet()) { - FieldInfo.setFieldValue(entry.getKey(), destination, entry.getValue().toArray()); - } - } - - /** - * Puts an additional value for the given field, accumulating values on repeated calls on the same - * field. - * - * @param field field - * @param arrayComponentType array component type - * @param value value - */ - public void put(Field field, Class arrayComponentType, Object value) { - ArrayValueMap.ArrayValue arrayValue = fieldMap.get(field); - if (arrayValue == null) { - arrayValue = new ArrayValue(arrayComponentType); - fieldMap.put(field, arrayValue); - } - arrayValue.addValue(arrayComponentType, value); - } - - /** - * Puts an additional value for the given key name, accumulating values on repeated calls on the - * same key name. - * - * @param keyName key name - * @param arrayComponentType array component type - * @param value value - */ - public void put(String keyName, Class arrayComponentType, Object value) { - ArrayValueMap.ArrayValue arrayValue = keyMap.get(keyName); - if (arrayValue == null) { - arrayValue = new ArrayValue(arrayComponentType); - keyMap.put(keyName, arrayValue); - } - arrayValue.addValue(arrayComponentType, value); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/BackOff.java b/src/autosaveworld/zlibs/com/google/api/client/util/BackOff.java deleted file mode 100644 index 9eb01847..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/BackOff.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.io.IOException; - -/** - * Back-off policy when retrying an operation. - * - * @since 1.15 - * @author Ravi Mistry - */ -public interface BackOff { - - /** Indicates that no more retries should be made for use in {@link #nextBackOffMillis()}. */ - static final long STOP = -1L; - - /** Reset to initial state. */ - void reset() throws IOException; - - /** - * Gets the number of milliseconds to wait before retrying the operation or {@link #STOP} to - * indicate that no retries should be made. - * - *

- * Example usage: - *

- * - *
-   long backOffMillis = backoff.nextBackOffMillis();
-   if (backOffMillis == Backoff.STOP) {
-     // do not retry operation
-   } else {
-     // sleep for backOffMillis milliseconds and retry operation
-   }
-   * 
- */ - long nextBackOffMillis() throws IOException; - - /** - * Fixed back-off policy whose back-off time is always zero, meaning that the operation is retried - * immediately without waiting. - */ - BackOff ZERO_BACKOFF = new BackOff() { - - public void reset() throws IOException { - } - - public long nextBackOffMillis() throws IOException { - return 0; - } - }; - - /** - * Fixed back-off policy that always returns {@code #STOP} for {@link #nextBackOffMillis()}, - * meaning that the operation should not be retried. - */ - BackOff STOP_BACKOFF = new BackOff() { - - public void reset() throws IOException { - } - - public long nextBackOffMillis() throws IOException { - return STOP; - } - }; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/BackOffUtils.java b/src/autosaveworld/zlibs/com/google/api/client/util/BackOffUtils.java deleted file mode 100644 index daa6b137..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/BackOffUtils.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.io.IOException; - -/** - * {@link Beta}
- * Utilities for {@link BackOff}. - * - * @since 1.15 - * @author Yaniv Inbar - */ -@Beta -public final class BackOffUtils { - - /** - * Runs the next iteration of the back-off policy, and returns whether to continue to retry the - * operation. - * - *

- * If {@code true}, it will call {@link Sleeper#sleep(long)} with the specified number of - * milliseconds from {@link BackOff#nextBackOffMillis()}. - *

- * - * @param sleeper sleeper - * @param backOff back-off policy - * @return whether to continue to back off; in other words, whether - * {@link BackOff#nextBackOffMillis()} did not return {@link BackOff#STOP} - * @throws InterruptedException if any thread has interrupted the current thread - */ - public static boolean next(Sleeper sleeper, BackOff backOff) - throws InterruptedException, IOException { - long backOffTime = backOff.nextBackOffMillis(); - if (backOffTime == BackOff.STOP) { - return false; - } - sleeper.sleep(backOffTime); - return true; - } - - private BackOffUtils() { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/Base64.java b/src/autosaveworld/zlibs/com/google/api/client/util/Base64.java deleted file mode 100644 index 5f3c9d16..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/Base64.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -/** - * Proxy for version 1.6 (or newer) of the Apache Commons Codec - * {@link org.apache.commons.codec.binary.Base64} implementation. - * - *

- * This is needed in order to support platforms like Android which already include an older version - * of the Apache Commons Codec (Android includes version 1.3). To avoid a dependency library - * conflict, this library includes a reduced private copy of version 1.6 (or newer) of the Apache - * Commons Codec (using a tool like jarjar). - *

- * - * @since 1.8 - * @author Yaniv Inbar - */ -public class Base64 { - - /** - * Encodes binary data using the base64 algorithm but does not chunk the output. - * - * @param binaryData binary data to encode or {@code null} for {@code null} result - * @return byte[] containing Base64 characters in their UTF-8 representation or {@code null} for - * {@code null} input - * @see org.apache.commons.codec.binary.Base64#encodeBase64(byte[]) - */ - public static byte[] encodeBase64(byte[] binaryData) { - return org.apache.commons.codec.binary.Base64.encodeBase64(binaryData); - } - - /** - * Encodes binary data using the base64 algorithm but does not chunk the output. - * - * @param binaryData binary data to encode or {@code null} for {@code null} result - * @return String containing Base64 characters or {@code null} for {@code null} input - * @see org.apache.commons.codec.binary.Base64#encodeBase64String(byte[]) - */ - public static String encodeBase64String(byte[] binaryData) { - return org.apache.commons.codec.binary.Base64.encodeBase64String(binaryData); - } - - - /** - * Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the - * output. The url-safe variation emits - and _ instead of + and / characters. - * - * @param binaryData binary data to encode or {@code null} for {@code null} result - * @return byte[] containing Base64 characters in their UTF-8 representation or {@code null} for - * {@code null} input - * @see org.apache.commons.codec.binary.Base64#encodeBase64URLSafe(byte[]) - */ - public static byte[] encodeBase64URLSafe(byte[] binaryData) { - return org.apache.commons.codec.binary.Base64.encodeBase64URLSafe(binaryData); - } - - /** - * Encodes binary data using a URL-safe variation of the base64 algorithm but does not chunk the - * output. The url-safe variation emits - and _ instead of + and / characters. - * - * @param binaryData binary data to encode or {@code null} for {@code null} result - * @return String containing Base64 characters or {@code null} for {@code null} input - * @see org.apache.commons.codec.binary.Base64#encodeBase64URLSafeString(byte[]) - */ - public static String encodeBase64URLSafeString(byte[] binaryData) { - return org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(binaryData); - } - - /** - * Decodes Base64 data into octets. - * - * @param base64Data Byte array containing Base64 data or {@code null} for {@code null} result - * @return Array containing decoded data or {@code null} for {@code null} input - * @see org.apache.commons.codec.binary.Base64#decodeBase64(byte[]) - */ - public static byte[] decodeBase64(byte[] base64Data) { - return org.apache.commons.codec.binary.Base64.decodeBase64(base64Data); - } - - /** - * Decodes a Base64 String into octets. - * - * @param base64String String containing Base64 data or {@code null} for {@code null} result - * @return Array containing decoded data or {@code null} for {@code null} input - * @see org.apache.commons.codec.binary.Base64#decodeBase64(String) - */ - public static byte[] decodeBase64(String base64String) { - return org.apache.commons.codec.binary.Base64.decodeBase64(base64String); - } - - private Base64() { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/Beta.java b/src/autosaveworld/zlibs/com/google/api/client/util/Beta.java deleted file mode 100644 index 1ef90322..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/Beta.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Target; - -/** - * Use this annotation to indicate that a public API (class, method or field) is beta. - * - *

- * Beta API is subject to incompatible changes or removal in the future. It may also mean - * that the server features it depends on are potentially subject to breakage at any time. - *

- * - *

- * That API is exempt from any compatibility guarantees made by its containing library. Read - * carefully the JavaDoc of the API bearing this annotation for better understanding of the risk. - *

- * - *

- * To provide a smoother upgrade path when we make incompatible changes to beta API, - * whenever possible we try to deprecate the old beta API in the first minor release, and - * then remove it in the second minor release. - *

- * - *

- * It is generally inadvisable for other non-beta libraries to use beta API from - * this library. The problem is that other libraries don't have control over the version of this - * library being used in client applications, and if the wrong version of this library is used, it - * has the potential to break client applications. - *

- * - *

- * You may use the google-http-client-findbugs plugin to find usages of API bearing this annotation. - *

- * - * @since 1.15 - * @author Eyal Peled - */ -@Target(value = { - ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, - ElementType.TYPE, ElementType.PACKAGE}) -@Documented -public @interface Beta { - -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/ByteArrayStreamingContent.java b/src/autosaveworld/zlibs/com/google/api/client/util/ByteArrayStreamingContent.java deleted file mode 100644 index e6b145b3..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/ByteArrayStreamingContent.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * Streaming content whose source is a byte array. - * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.14 - * @author Yaniv Inbar - */ -public class ByteArrayStreamingContent implements StreamingContent { - - /** Byte array content. */ - private final byte[] byteArray; - - /** Starting offset into the byte array. */ - private final int offset; - - /** Length of bytes to read from byte array. */ - private final int length; - - /** - * @param byteArray byte array content - */ - public ByteArrayStreamingContent(byte[] byteArray) { - this(byteArray, 0, byteArray.length); - } - - /** - * @param byteArray byte array content - * @param offset starting offset into the byte array - * @param length of bytes to read from byte array - */ - public ByteArrayStreamingContent(byte[] byteArray, int offset, int length) { - this.byteArray = Preconditions.checkNotNull(byteArray); - Preconditions.checkArgument(offset >= 0 && length >= 0 && offset + length <= byteArray.length); - this.offset = offset; - this.length = length; - } - - public void writeTo(OutputStream out) throws IOException { - out.write(byteArray, offset, length); - out.flush(); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/ByteCountingOutputStream.java b/src/autosaveworld/zlibs/com/google/api/client/util/ByteCountingOutputStream.java deleted file mode 100644 index fc92805d..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/ByteCountingOutputStream.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * Output stream that throws away any content and only retains the count of bytes written to the - * stream. - * - * @author Yaniv Inbar - */ -final class ByteCountingOutputStream extends OutputStream { - - /** Number of bytes written. */ - long count; - - @Override - public void write(byte[] b, int off, int len) throws IOException { - count += len; - } - - @Override - public void write(int b) throws IOException { - count++; - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/ByteStreams.java b/src/autosaveworld/zlibs/com/google/api/client/util/ByteStreams.java deleted file mode 100644 index edff989c..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/ByteStreams.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -/** - * Provides utility methods for working with byte arrays and I/O streams. - * - *

- * NOTE: this is a copy of a subset of Guava's {@link com.google.common.io.ByteStreams}. The - * implementation must match as closely as possible to Guava's implementation. - *

- * - * @since 1.14 - * @author Yaniv Inbar - */ -public final class ByteStreams { - - private static final int BUF_SIZE = 0x1000; // 4K - - /** - * Copies all bytes from the input stream to the output stream. Does not close or flush either - * stream. - * - * @param from the input stream to read from - * @param to the output stream to write to - * @return the number of bytes copied - */ - public static long copy(InputStream from, OutputStream to) throws IOException { - Preconditions.checkNotNull(from); - Preconditions.checkNotNull(to); - byte[] buf = new byte[BUF_SIZE]; - long total = 0; - while (true) { - int r = from.read(buf); - if (r == -1) { - break; - } - to.write(buf, 0, r); - total += r; - } - return total; - } - - /** - * Wraps an input stream, limiting the number of bytes which can be read. - * - * @param in the input stream to be wrapped - * @param limit the maximum number of bytes to be read - * @return a length-limited {@link InputStream} - */ - public static InputStream limit(InputStream in, long limit) { - return new LimitedInputStream(in, limit); - } - - private static final class LimitedInputStream extends FilterInputStream { - - private long left; - private long mark = -1; - - LimitedInputStream(InputStream in, long limit) { - super(in); - Preconditions.checkNotNull(in); - Preconditions.checkArgument(limit >= 0, "limit must be non-negative"); - left = limit; - } - - @Override - public int available() throws IOException { - return (int) Math.min(in.available(), left); - } - - // it's okay to mark even if mark isn't supported, as reset won't work - @Override - public synchronized void mark(int readLimit) { - in.mark(readLimit); - mark = left; - } - - @Override - public int read() throws IOException { - if (left == 0) { - return -1; - } - - int result = in.read(); - if (result != -1) { - --left; - } - return result; - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - if (left == 0) { - return -1; - } - - len = (int) Math.min(len, left); - int result = in.read(b, off, len); - if (result != -1) { - left -= result; - } - return result; - } - - @Override - public synchronized void reset() throws IOException { - if (!in.markSupported()) { - throw new IOException("Mark not supported"); - } - if (mark == -1) { - throw new IOException("Mark not set"); - } - - in.reset(); - left = mark; - } - - @Override - public long skip(long n) throws IOException { - n = Math.min(n, left); - long skipped = in.skip(n); - left -= skipped; - return skipped; - } - } - - /** - * Reads some bytes from an input stream and stores them into the buffer array {@code b}. - * - *

- * This method blocks until {@code len} bytes of input data have been read into the array, or end - * of file is detected. The number of bytes read is returned, possibly zero. Does not close the - * stream. - *

- * - *

- * A caller can detect EOF if the number of bytes read is less than {@code len}. All subsequent - * calls on the same stream will return zero. - *

- * - *

- * If {@code b} is null, a {@code NullPointerException} is thrown. If {@code off} is negative, or - * {@code len} is negative, or {@code off+len} is greater than the length of the array {@code b}, - * then an {@code IndexOutOfBoundsException} is thrown. If {@code len} is zero, then no bytes are - * read. Otherwise, the first byte read is stored into element {@code b[off]}, the next one into - * {@code b[off+1]}, and so on. The number of bytes read is, at most, equal to {@code len}. - *

- * - * @param in the input stream to read from - * @param b the buffer into which the data is read - * @param off an int specifying the offset into the data - * @param len an int specifying the number of bytes to read - * @return the number of bytes read - */ - public static int read(InputStream in, byte[] b, int off, int len) throws IOException { - Preconditions.checkNotNull(in); - Preconditions.checkNotNull(b); - if (len < 0) { - throw new IndexOutOfBoundsException("len is negative"); - } - int total = 0; - while (total < len) { - int result = in.read(b, off + total, len - total); - if (result == -1) { - break; - } - total += result; - } - return total; - } - - private ByteStreams() { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/Charsets.java b/src/autosaveworld/zlibs/com/google/api/client/util/Charsets.java deleted file mode 100644 index bd7db960..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/Charsets.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.nio.charset.Charset; - -/** - * Contains constant definitions for some standard {@link Charset} instances that are guaranteed to - * be supported by all Java platform implementations. - * - *

- * NOTE: this is a copy of a subset of Guava's {@link com.google.common.base.Charsets}. The - * implementation must match as closely as possible to Guava's implementation. - *

- * - * @since 1.14 - * @author Yaniv Inbar - */ -public final class Charsets { - - /** UTF-8 charset. */ - public static final Charset UTF_8 = Charset.forName("UTF-8"); - - /** ISO-8859-1 charset. */ - public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); - - private Charsets() { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/ClassInfo.java b/src/autosaveworld/zlibs/com/google/api/client/util/ClassInfo.java deleted file mode 100644 index 7da6fdea..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/ClassInfo.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeSet; -import java.util.WeakHashMap; - -/** - * Computes class information to determine data key name/value pairs associated with the class. - * - *

- * Implementation is thread-safe. - *

- * - * @since 1.0 - * @author Yaniv Inbar - */ -public final class ClassInfo { - - /** Class information cache, with case-sensitive field names. */ - private static final Map, ClassInfo> CACHE = new WeakHashMap, ClassInfo>(); - - /** Class information cache, with case-insensitive fields names. */ - private static final Map, ClassInfo> CACHE_IGNORE_CASE = - new WeakHashMap, ClassInfo>(); - - /** Class. */ - private final Class clazz; - - /** Whether field names are case sensitive. */ - private final boolean ignoreCase; - - /** Map from {@link FieldInfo#getName()} to the field information. */ - private final IdentityHashMap nameToFieldInfoMap = - new IdentityHashMap(); - - /** - * Unmodifiable sorted (with any possible {@code null} member first) list (without duplicates) of - * {@link FieldInfo#getName()}. - */ - final List names; - - /** - * Returns the class information for the given underlying class. - * - * @param underlyingClass underlying class or {@code null} for {@code null} result - * @return class information or {@code null} for {@code null} input - */ - public static ClassInfo of(Class underlyingClass) { - return of(underlyingClass, false); - } - - /** - * Returns the class information for the given underlying class. - * - * @param underlyingClass underlying class or {@code null} for {@code null} result - * @param ignoreCase whether field names are case sensitive - * @return class information or {@code null} for {@code null} input - * @since 1.10 - */ - public static ClassInfo of(Class underlyingClass, boolean ignoreCase) { - if (underlyingClass == null) { - return null; - } - final Map, ClassInfo> cache = ignoreCase ? CACHE_IGNORE_CASE : CACHE; - ClassInfo classInfo; - synchronized (cache) { - classInfo = cache.get(underlyingClass); - if (classInfo == null) { - classInfo = new ClassInfo(underlyingClass, ignoreCase); - cache.put(underlyingClass, classInfo); - } - } - return classInfo; - } - - /** - * Returns the underlying class. - * - * @since 1.4 - */ - public Class getUnderlyingClass() { - return clazz; - } - - /** - * Returns whether field names are case sensitive. - * - * @since 1.10 - */ - public final boolean getIgnoreCase() { - return ignoreCase; - } - - /** - * Returns the information for the given {@link FieldInfo#getName()}. - * - * @param name {@link FieldInfo#getName()} or {@code null} - * @return field information or {@code null} for none - */ - public FieldInfo getFieldInfo(String name) { - if (name != null) { - if (ignoreCase) { - name = name.toLowerCase(); - } - name = name.intern(); - } - return nameToFieldInfoMap.get(name); - } - - /** - * Returns the field for the given {@link FieldInfo#getName()}. - * - * @param name {@link FieldInfo#getName()} or {@code null} - * @return field or {@code null} for none - */ - public Field getField(String name) { - FieldInfo fieldInfo = getFieldInfo(name); - return fieldInfo == null ? null : fieldInfo.getField(); - } - - /** - * Returns the underlying class is an enum. - * - * @since 1.4 - */ - public boolean isEnum() { - return clazz.isEnum(); - } - - /** - * Returns an unmodifiable sorted set (with any possible {@code null} member first) of - * {@link FieldInfo#getName() names}. - */ - public Collection getNames() { - return names; - } - - private ClassInfo(Class srcClass, boolean ignoreCase) { - clazz = srcClass; - this.ignoreCase = ignoreCase; - Preconditions.checkArgument( - !ignoreCase || !srcClass.isEnum(), "cannot ignore case on an enum: " + srcClass); - // name set has a special comparator to keep null first - TreeSet nameSet = new TreeSet(new Comparator() { - public int compare(String s0, String s1) { - return s0 == s1 ? 0 : s0 == null ? -1 : s1 == null ? 1 : s0.compareTo(s1); - } - }); - // iterate over declared fields - for (Field field : srcClass.getDeclaredFields()) { - FieldInfo fieldInfo = FieldInfo.of(field); - if (fieldInfo == null) { - continue; - } - String fieldName = fieldInfo.getName(); - if (ignoreCase) { - fieldName = fieldName.toLowerCase().intern(); - } - FieldInfo conflictingFieldInfo = nameToFieldInfoMap.get(fieldName); - Preconditions.checkArgument(conflictingFieldInfo == null, - "two fields have the same %sname <%s>: %s and %s", - ignoreCase ? "case-insensitive " : "", - fieldName, - field, - conflictingFieldInfo == null ? null : conflictingFieldInfo.getField()); - nameToFieldInfoMap.put(fieldName, fieldInfo); - nameSet.add(fieldName); - } - // inherit from super class and add only fields not already in nameToFieldInfoMap - Class superClass = srcClass.getSuperclass(); - if (superClass != null) { - ClassInfo superClassInfo = ClassInfo.of(superClass, ignoreCase); - nameSet.addAll(superClassInfo.names); - for (Map.Entry e : superClassInfo.nameToFieldInfoMap.entrySet()) { - String name = e.getKey(); - if (!nameToFieldInfoMap.containsKey(name)) { - nameToFieldInfoMap.put(name, e.getValue()); - } - } - } - names = nameSet.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList( - new ArrayList(nameSet)); - } - - /** - * Returns an unmodifiable collection of the {@code FieldInfo}s for this class, without any - * guarantee of order. - * - *

- * If you need sorted order, instead use {@link #getNames()} with {@link #getFieldInfo(String)}. - *

- * - * @since 1.16 - */ - public Collection getFieldInfos() { - return Collections.unmodifiableCollection(nameToFieldInfoMap.values()); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/Clock.java b/src/autosaveworld/zlibs/com/google/api/client/util/Clock.java deleted file mode 100644 index e602fefb..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/Clock.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -/** - * Clock which can be used to get the amount of elapsed milliseconds in system time. - * - *

- * The default system implementation can be accessed at {@link #SYSTEM}. Alternative implementations - * may be used for testing. - *

- * - * @since 1.9 - * @author mlinder@google.com (Matthias Linder) - */ -public interface Clock { - /** - * Returns the current time in milliseconds since midnight, January 1, 1970 UTC, to match the - * behavior of {@link System#currentTimeMillis()}. - */ - long currentTimeMillis(); - - /** - * Provides the default System implementation of a Clock by using - * {@link System#currentTimeMillis()}. - */ - Clock SYSTEM = new Clock() { - public long currentTimeMillis() { - return System.currentTimeMillis(); - } - }; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/Collections2.java b/src/autosaveworld/zlibs/com/google/api/client/util/Collections2.java deleted file mode 100644 index 80fac08f..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/Collections2.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.util.Collection; - -/** - * Static utility methods pertaining to {@link Collection} instances. - * - *

- * NOTE: this is a copy of a subset of Guava's {@link com.google.common.collect.Collections2}. The - * implementation must match as closely as possible to Guava's implementation. - *

- * - * @since 1.14 - * @author Yaniv Inbar - */ -public final class Collections2 { - - /** Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557. */ - static Collection cast(Iterable iterable) { - return (Collection) iterable; - } - - private Collections2() { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/Data.java b/src/autosaveworld/zlibs/com/google/api/client/util/Data.java deleted file mode 100644 index 19de5e5f..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/Data.java +++ /dev/null @@ -1,557 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.lang.reflect.Array; -import java.lang.reflect.GenericArrayType; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.lang.reflect.WildcardType; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.SortedMap; -import java.util.TreeMap; -import java.util.TreeSet; -import java.util.concurrent.ConcurrentHashMap; - -/** - * Utilities for working with key/value data based on the {@link Key} annotation. - * - * @since 1.4 - * @author Yaniv Inbar - */ -public class Data { - - // NOTE: create new instances to avoid cache, e.g. new String() - - /** The single instance of the magic null object for a {@link Boolean}. */ - public static final Boolean NULL_BOOLEAN = new Boolean(true); - - /** The single instance of the magic null object for a {@link String}. */ - public static final String NULL_STRING = new String(); - - /** The single instance of the magic null object for a {@link Character}. */ - public static final Character NULL_CHARACTER = new Character((char) 0); - - /** The single instance of the magic null object for a {@link Byte}. */ - public static final Byte NULL_BYTE = new Byte((byte) 0); - - /** The single instance of the magic null object for a {@link Short}. */ - public static final Short NULL_SHORT = new Short((short) 0); - - /** The single instance of the magic null object for a {@link Integer}. */ - public static final Integer NULL_INTEGER = new Integer(0); - - /** The single instance of the magic null object for a {@link Float}. */ - public static final Float NULL_FLOAT = new Float(0); - - /** The single instance of the magic null object for a {@link Long}. */ - public static final Long NULL_LONG = new Long(0); - - /** The single instance of the magic null object for a {@link Double}. */ - public static final Double NULL_DOUBLE = new Double(0); - - /** The single instance of the magic null object for a {@link BigInteger}. */ - public static final BigInteger NULL_BIG_INTEGER = new BigInteger("0"); - - /** The single instance of the magic null object for a {@link BigDecimal}. */ - public static final BigDecimal NULL_BIG_DECIMAL = new BigDecimal("0"); - - /** The single instance of the magic null object for a {@link DateTime}. */ - public static final DateTime NULL_DATE_TIME = new DateTime(0); - - /** Cache of the magic null object for the given Java class. */ - private static final ConcurrentHashMap, Object> NULL_CACHE = - new ConcurrentHashMap, Object>(); - static { - // special cases for some primitives - NULL_CACHE.put(Boolean.class, NULL_BOOLEAN); - NULL_CACHE.put(String.class, NULL_STRING); - NULL_CACHE.put(Character.class, NULL_CHARACTER); - NULL_CACHE.put(Byte.class, NULL_BYTE); - NULL_CACHE.put(Short.class, NULL_SHORT); - NULL_CACHE.put(Integer.class, NULL_INTEGER); - NULL_CACHE.put(Float.class, NULL_FLOAT); - NULL_CACHE.put(Long.class, NULL_LONG); - NULL_CACHE.put(Double.class, NULL_DOUBLE); - NULL_CACHE.put(BigInteger.class, NULL_BIG_INTEGER); - NULL_CACHE.put(BigDecimal.class, NULL_BIG_DECIMAL); - NULL_CACHE.put(DateTime.class, NULL_DATE_TIME); - } - - /** - * Returns the single instance of the magic object that represents the "null" value for the given - * Java class (including array or enum). - * - * @param objClass class of the object needed - * @return magic object instance that represents the "null" value (not Java {@code null}) - * @throws IllegalArgumentException if unable to create a new instance - */ - public static T nullOf(Class objClass) { - Object result = NULL_CACHE.get(objClass); - if (result == null) { - synchronized (NULL_CACHE) { - result = NULL_CACHE.get(objClass); - if (result == null) { - if (objClass.isArray()) { - // arrays are special because we need to compute both the dimension and component type - int dims = 0; - Class componentType = objClass; - do { - componentType = componentType.getComponentType(); - dims++; - } while (componentType.isArray()); - result = Array.newInstance(componentType, new int[dims]); - } else if (objClass.isEnum()) { - // enum requires look for constant with @NullValue - FieldInfo fieldInfo = ClassInfo.of(objClass).getFieldInfo(null); - Preconditions.checkNotNull( - fieldInfo, "enum missing constant with @NullValue annotation: %s", objClass); - @SuppressWarnings({"unchecked", "rawtypes"}) - Enum e = fieldInfo.enumValue(); - result = e; - } else { - // other classes are simpler - result = Types.newInstance(objClass); - } - NULL_CACHE.put(objClass, result); - } - } - } - @SuppressWarnings("unchecked") - T tResult = (T) result; - return tResult; - } - - /** - * Returns whether the given object is the magic object that represents the null value of its - * class. - * - * @param object object or {@code null} - * @return whether it is the magic null value or {@code false} for {@code null} input - */ - public static boolean isNull(Object object) { - // don't call nullOf because will throw IllegalArgumentException if cannot create instance - return object != null && object == NULL_CACHE.get(object.getClass()); - } - - /** - * Returns the map to use for the given data that is treated as a map from string key to some - * value. - * - *

- * If the input is {@code null}, it returns an empty map. If the input is a map, it simply returns - * the input. Otherwise, it will create a map view using reflection that is backed by the object, - * so that any changes to the map will be reflected on the object. The map keys of that map view - * are based on the {@link Key} annotation, and null is not a possible map value, although the - * magic null instance is possible (see {@link #nullOf(Class)} and {@link #isNull(Object)}). - * Iteration order of the data keys is based on the sorted (ascending) key names of the declared - * fields. Note that since the map view is backed by the object, and that the object may change, - * many methods in the map view must recompute the field values using reflection, for example - * {@link Map#size()} must check the number of non-null fields. - *

- * - * @param data any key value data, represented by an object or a map, or {@code null} - * @return key/value map to use - */ - public static Map mapOf(Object data) { - if (data == null || isNull(data)) { - return Collections.emptyMap(); - } - if (data instanceof Map) { - @SuppressWarnings("unchecked") - Map result = (Map) data; - return result; - } - Map result = new DataMap(data, false); - return result; - } - - /** - * Returns a deep clone of the given key/value data, such that the result is a completely - * independent copy. - *

- * This should not be used directly in the implementation of {@code Object.clone()}. Instead use - * {@link #deepCopy(Object, Object)} for that purpose. - *

- *

- * Final fields cannot be changed and therefore their value won't be copied. - *

- * - * @param data key/value data object or map to clone or {@code null} for a {@code null} return - * value - * @return deep clone or {@code null} for {@code null} input - */ - @SuppressWarnings("unchecked") - public static T clone(T data) { - // don't need to clone primitive - if (data == null || Data.isPrimitive(data.getClass())) { - return data; - } - if (data instanceof GenericData) { - return (T) ((GenericData) data).clone(); - } - T copy; - Class dataClass = data.getClass(); - if (dataClass.isArray()) { - copy = (T) Array.newInstance(dataClass.getComponentType(), Array.getLength(data)); - } else if (data instanceof ArrayMap) { - copy = (T) ((ArrayMap) data).clone(); - } else if ("java.util.Arrays$ArrayList".equals(dataClass.getName())) { - // Arrays$ArrayList does not have a zero-arg constructor, so it has to handled specially. - // Arrays.asList(x).toArray() may or may not have the same runtime type as x. - // https://bugs.openjdk.java.net/browse/JDK-6260652 - Object[] arrayCopy = ((List) data).toArray(); - deepCopy(arrayCopy, arrayCopy); - copy = (T) Arrays.asList(arrayCopy); - return copy; - } else { - copy = (T) Types.newInstance(dataClass); - } - deepCopy(data, copy); - return copy; - } - - /** - * Makes a deep copy of the given source object into the destination object that is assumed to be - * constructed using {@code Object.clone()}. - * - *

- * Example usage of this method in {@code Object.clone()}: - *

- * - *
-  @Override
-  public MyObject clone() {
-    try {
-      @SuppressWarnings("unchecked")
-      MyObject result = (MyObject) super.clone();
-      Data.deepCopy(this, result);
-      return result;
-    } catch (CloneNotSupportedException e) {
-      throw new IllegalStateException(e);
-    }
-  }
-   * 
- *

- * Final fields cannot be changed and therefore their value won't be copied. - *

- * - * @param src source object - * @param dest destination object of identical type as source object, and any contained arrays - * must be the same length - */ - public static void deepCopy(Object src, Object dest) { - Class srcClass = src.getClass(); - Preconditions.checkArgument(srcClass == dest.getClass()); - if (srcClass.isArray()) { - // clone array - Preconditions.checkArgument(Array.getLength(src) == Array.getLength(dest)); - int index = 0; - for (Object value : Types.iterableOf(src)) { - Array.set(dest, index++, clone(value)); - } - } else if (Collection.class.isAssignableFrom(srcClass)) { - // clone collection - @SuppressWarnings("unchecked") - Collection srcCollection = (Collection) src; - if (ArrayList.class.isAssignableFrom(srcClass)) { - @SuppressWarnings("unchecked") - ArrayList destArrayList = (ArrayList) dest; - destArrayList.ensureCapacity(srcCollection.size()); - } - @SuppressWarnings("unchecked") - Collection destCollection = (Collection) dest; - for (Object srcValue : srcCollection) { - destCollection.add(clone(srcValue)); - } - } else { - // clone generic data or a non-map Object - boolean isGenericData = GenericData.class.isAssignableFrom(srcClass); - if (isGenericData || !Map.class.isAssignableFrom(srcClass)) { - ClassInfo classInfo = - isGenericData ? ((GenericData) src).classInfo : ClassInfo.of(srcClass); - for (String fieldName : classInfo.names) { - FieldInfo fieldInfo = classInfo.getFieldInfo(fieldName); - // skip final fields - if (!fieldInfo.isFinal()) { - // generic data already has primitive types copied by clone() - if (!isGenericData || !fieldInfo.isPrimitive()) { - Object srcValue = fieldInfo.getValue(src); - if (srcValue != null) { - fieldInfo.setValue(dest, clone(srcValue)); - } - } - } - } - } else if (ArrayMap.class.isAssignableFrom(srcClass)) { - // clone array map - @SuppressWarnings("unchecked") - ArrayMap destMap = (ArrayMap) dest; - @SuppressWarnings("unchecked") - ArrayMap srcMap = (ArrayMap) src; - int size = srcMap.size(); - for (int i = 0; i < size; i++) { - Object srcValue = srcMap.getValue(i); - destMap.set(i, clone(srcValue)); - } - } else { - // clone map - @SuppressWarnings("unchecked") - Map destMap = (Map) dest; - @SuppressWarnings("unchecked") - Map srcMap = (Map) src; - for (Map.Entry srcEntry : srcMap.entrySet()) { - destMap.put(srcEntry.getKey(), clone(srcEntry.getValue())); - } - } - } - } - - /** - * Returns whether the given type is one of the supported primitive classes like number and - * date/time, or is a wildcard of one. - * - *

- * A primitive class is any class for whom {@link Class#isPrimitive()} is true, as well as any - * classes of type: {@link Character}, {@link String}, {@link Integer}, {@link Long}, - * {@link Short}, {@link Byte}, {@link Float}, {@link Double}, {@link BigInteger}, - * {@link BigDecimal}, {@link Boolean}, and {@link DateTime}. - *

- * - * @param type type or {@code null} for {@code false} result - * @return whether it is a primitive - */ - public static boolean isPrimitive(Type type) { - // TODO(yanivi): support java.net.URI as primitive type? - if (type instanceof WildcardType) { - type = Types.getBound((WildcardType) type); - } - if (!(type instanceof Class)) { - return false; - } - Class typeClass = (Class) type; - return typeClass.isPrimitive() || typeClass == Character.class || typeClass == String.class - || typeClass == Integer.class || typeClass == Long.class || typeClass == Short.class - || typeClass == Byte.class || typeClass == Float.class || typeClass == Double.class - || typeClass == BigInteger.class || typeClass == BigDecimal.class - || typeClass == DateTime.class || typeClass == Boolean.class; - } - - /** - * Returns whether to given value is {@code null} or its class is primitive as defined by - * {@link Data#isPrimitive(Type)}. - */ - public static boolean isValueOfPrimitiveType(Object fieldValue) { - return fieldValue == null || Data.isPrimitive(fieldValue.getClass()); - } - - /** - * Parses the given string value based on the given primitive type. - *

- * Types are parsed as follows: - *

- *
    - *
  • {@link Void}: null
  • - *
  • {@code null} or is assignable from {@link String} (like {@link Object}): no parsing
  • - *
  • {@code char} or {@link Character}: {@link String#charAt(int) String.charAt}(0) (requires - * length to be exactly 1)
  • - *
  • {@code boolean} or {@link Boolean}: {@link Boolean#valueOf(String)}
  • - *
  • {@code byte} or {@link Byte}: {@link Byte#valueOf(String)}
  • - *
  • {@code short} or {@link Short}: {@link Short#valueOf(String)}
  • - *
  • {@code int} or {@link Integer}: {@link Integer#valueOf(String)}
  • - *
  • {@code long} or {@link Long}: {@link Long#valueOf(String)}
  • - *
  • {@code float} or {@link Float}: {@link Float#valueOf(String)}
  • - *
  • {@code double} or {@link Double}: {@link Double#valueOf(String)}
  • - *
  • {@link BigInteger}: {@link BigInteger#BigInteger(String) BigInteger(String)}
  • - *
  • {@link BigDecimal}: {@link BigDecimal#BigDecimal(String) BigDecimal(String)}
  • - *
  • {@link DateTime}: {@link DateTime#parseRfc3339(String)}
  • - *
- * - *

- * Note that this may not be the right behavior for some use cases. - *

- * - * @param type primitive type or {@code null} to parse as a string - * @param stringValue string value to parse or {@code null} for {@code null} result - * @return parsed object or {@code null} for {@code null} input - * @throws IllegalArgumentException if the given class is not a primitive class - */ - public static Object parsePrimitiveValue(Type type, String stringValue) { - Class primitiveClass = type instanceof Class ? (Class) type : null; - if (type == null || primitiveClass != null) { - if (primitiveClass == Void.class) { - return null; - } - if (stringValue == null || primitiveClass == null - || primitiveClass.isAssignableFrom(String.class)) { - return stringValue; - } - if (primitiveClass == Character.class || primitiveClass == char.class) { - if (stringValue.length() != 1) { - throw new IllegalArgumentException( - "expected type Character/char but got " + primitiveClass); - } - return stringValue.charAt(0); - } - if (primitiveClass == Boolean.class || primitiveClass == boolean.class) { - return Boolean.valueOf(stringValue); - } - if (primitiveClass == Byte.class || primitiveClass == byte.class) { - return Byte.valueOf(stringValue); - } - if (primitiveClass == Short.class || primitiveClass == short.class) { - return Short.valueOf(stringValue); - } - if (primitiveClass == Integer.class || primitiveClass == int.class) { - return Integer.valueOf(stringValue); - } - if (primitiveClass == Long.class || primitiveClass == long.class) { - return Long.valueOf(stringValue); - } - if (primitiveClass == Float.class || primitiveClass == float.class) { - return Float.valueOf(stringValue); - } - if (primitiveClass == Double.class || primitiveClass == double.class) { - return Double.valueOf(stringValue); - } - if (primitiveClass == DateTime.class) { - return DateTime.parseRfc3339(stringValue); - } - if (primitiveClass == BigInteger.class) { - return new BigInteger(stringValue); - } - if (primitiveClass == BigDecimal.class) { - return new BigDecimal(stringValue); - } - if (primitiveClass.isEnum()) { - @SuppressWarnings({"unchecked", "rawtypes"}) - Enum result = ClassInfo.of(primitiveClass).getFieldInfo(stringValue).enumValue(); - return result; - } - } - throw new IllegalArgumentException("expected primitive class, but got: " + type); - } - - /** - * Returns a new collection instance for the given type. - *

- * Creates a new collection instance specified for the first input collection class that matches - * as follows: - *

    - *
  • {@code null} or an array or assignable from {@link ArrayList} (like {@link List} or - * {@link Collection} or {@link Object}): returns an {@link ArrayList}
  • - *
  • assignable from {@link HashSet}: returns a {@link HashSet}
  • - *
  • assignable from {@link TreeSet}: returns a {@link TreeSet}
  • - *
  • else: calls {@link Types#newInstance(Class)}
  • - *
- * - * @param type type or {@code null} for {@link ArrayList}. - * @return new collection instance - * @throws ClassCastException if result is does not extend {@link Collection} - */ - public static Collection newCollectionInstance(Type type) { - if (type instanceof WildcardType) { - type = Types.getBound((WildcardType) type); - } - if (type instanceof ParameterizedType) { - type = ((ParameterizedType) type).getRawType(); - } - Class collectionClass = type instanceof Class ? (Class) type : null; - if (type == null || type instanceof GenericArrayType || collectionClass != null - && (collectionClass.isArray() || collectionClass.isAssignableFrom(ArrayList.class))) { - return new ArrayList(); - } - if (collectionClass == null) { - throw new IllegalArgumentException("unable to create new instance of type: " + type); - } - if (collectionClass.isAssignableFrom(HashSet.class)) { - return new HashSet(); - } - if (collectionClass.isAssignableFrom(TreeSet.class)) { - return new TreeSet(); - } - @SuppressWarnings("unchecked") - Collection result = (Collection) Types.newInstance(collectionClass); - return result; - } - - /** - * Returns a new instance of a map based on the given field class. - *

- * Creates a new map instance specified for the first input map class that matches as follows: - *

- *
    - *
  • {@code null} or assignable from {@link ArrayMap} (like {@link Map} or {@link Object}): - * returns an {@link ArrayMap}
  • - *
  • assignable from {@link TreeMap} (like {@link SortedMap}): returns a {@link TreeMap}
  • - *
  • else: calls {@link Types#newInstance(Class)}
  • - *
- * - * @param mapClass field class - * @throws ClassCastException if result is does not extend {@link Map} - */ - public static Map newMapInstance(Class mapClass) { - if (mapClass == null || mapClass.isAssignableFrom(ArrayMap.class)) { - return ArrayMap.create(); - } - if (mapClass.isAssignableFrom(TreeMap.class)) { - return new TreeMap(); - } - @SuppressWarnings("unchecked") - Map result = (Map) Types.newInstance(mapClass); - return result; - } - - /** - * Aggressively resolves the given type in such a way that the resolved type is not a wildcard - * type or a type variable, returning {@code Object.class} if the type variable cannot be - * resolved. - * - * @param context context list, ordering from least specific to most specific type context, for - * example container class and then its field - * @param type type or {@code null} for {@code null} result - * @return resolved type (which may be class, parameterized type, or generic array type, but not - * wildcard type or type variable) or {@code null} for {@code null} input - */ - public static Type resolveWildcardTypeOrTypeVariable(List context, Type type) { - // first deal with a wildcard, e.g. ? extends Number - if (type instanceof WildcardType) { - type = Types.getBound((WildcardType) type); - } - // next deal with a type variable T - while (type instanceof TypeVariable) { - // resolve the type variable - Type resolved = Types.resolveTypeVariable(context, (TypeVariable) type); - if (resolved != null) { - type = resolved; - } - // if unable to fully resolve the type variable, use its bounds, e.g. T extends Number - if (type instanceof TypeVariable) { - type = ((TypeVariable) type).getBounds()[0]; - } - // loop in case T extends U and U is also a type variable - } - return type; - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/DataMap.java b/src/autosaveworld/zlibs/com/google/api/client/util/DataMap.java deleted file mode 100644 index da70728a..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/DataMap.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.util.AbstractMap; -import java.util.AbstractSet; -import java.util.Iterator; -import java.util.Map; -import java.util.NoSuchElementException; - -/** - * Map that uses {@link ClassInfo} to parse the key/value pairs into a map for use in - * {@link Data#mapOf(Object)}. - * - * @author Yaniv Inbar - */ -final class DataMap extends AbstractMap { - - // TODO(yanivi): implement more methods for faster implementation! - - /** Object being reflected. */ - final Object object; - - /** Object's class info. */ - final ClassInfo classInfo; - - /** - * @param object object being reflected - */ - DataMap(Object object, boolean ignoreCase) { - this.object = object; - classInfo = ClassInfo.of(object.getClass(), ignoreCase); - Preconditions.checkArgument(!classInfo.isEnum()); - } - - @Override - public EntrySet entrySet() { - return new EntrySet(); - } - - @Override - public boolean containsKey(Object key) { - return get(key) != null; - } - - @Override - public Object get(Object key) { - if (!(key instanceof String)) { - return null; - } - FieldInfo fieldInfo = classInfo.getFieldInfo((String) key); - if (fieldInfo == null) { - return null; - } - return fieldInfo.getValue(object); - } - - @Override - public Object put(String key, Object value) { - FieldInfo fieldInfo = classInfo.getFieldInfo(key); - Preconditions.checkNotNull(fieldInfo, "no field of key " + key); - Object oldValue = fieldInfo.getValue(object); - fieldInfo.setValue(object, Preconditions.checkNotNull(value)); - return oldValue; - } - - /** Set of object data key/value map entries. */ - final class EntrySet extends AbstractSet> { - - @Override - public EntryIterator iterator() { - return new EntryIterator(); - } - - @Override - public int size() { - int result = 0; - for (String name : classInfo.names) { - if (classInfo.getFieldInfo(name).getValue(object) != null) { - result++; - } - } - return result; - } - - @Override - public void clear() { - for (String name : classInfo.names) { - classInfo.getFieldInfo(name).setValue(object, null); - } - } - - @Override - public boolean isEmpty() { - for (String name : classInfo.names) { - if (classInfo.getFieldInfo(name).getValue(object) != null) { - return false; - } - } - return true; - } - } - - /** Iterator over the object data key/value map entries. */ - final class EntryIterator implements Iterator> { - - /** - * Next index into key names array computed in {@link #hasNext()} or {@code -1} before - * {@link #hasNext()} has been called. - */ - private int nextKeyIndex = -1; - - /** - * Next field info computed in {@link #hasNext()} or {@code null} before {@link #hasNext()} has - * been called since the last {@link #next()}. - */ - private FieldInfo nextFieldInfo; - - /** - * Next field value computed in {@link #hasNext()} or {@code null} before {@link #hasNext()} has - * been called since the last {@link #next()}. - */ - private Object nextFieldValue; - - /** Whether {@link #remove()} has been called since last time {@link #next()} was called. */ - private boolean isRemoved; - - /** Whether the next field has been computed. */ - private boolean isComputed; - - /** - * Current field info found by {@link #next()} or {@code null} before {@link #next()} has been - * called. - */ - private FieldInfo currentFieldInfo; - - public boolean hasNext() { - if (!isComputed) { - isComputed = true; - nextFieldValue = null; - while (nextFieldValue == null && ++nextKeyIndex < classInfo.names.size()) { - nextFieldInfo = classInfo.getFieldInfo(classInfo.names.get(nextKeyIndex)); - nextFieldValue = nextFieldInfo.getValue(object); - } - } - return nextFieldValue != null; - } - - public Map.Entry next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - currentFieldInfo = nextFieldInfo; - Object currentFieldValue = nextFieldValue; - isComputed = false; - isRemoved = false; - nextFieldInfo = null; - nextFieldValue = null; - return new Entry(currentFieldInfo, currentFieldValue); - } - - public void remove() { - Preconditions.checkState(currentFieldInfo != null && !isRemoved); - isRemoved = true; - currentFieldInfo.setValue(object, null); - } - } - - /** - * Entry in the reflection map. - *

- * Null key or value is not allowed. - *

- */ - final class Entry implements Map.Entry { - - /** - * Current field value, possibly modified only by {@link #setValue(Object)}. As specified - * {@link java.util.Map.Entry}, behavior is undefined if the field value is modified by other - * means. - */ - private Object fieldValue; - - /** Field info. */ - private final FieldInfo fieldInfo; - - Entry(FieldInfo fieldInfo, Object fieldValue) { - this.fieldInfo = fieldInfo; - this.fieldValue = Preconditions.checkNotNull(fieldValue); - } - - public String getKey() { - String result = fieldInfo.getName(); - if (classInfo.getIgnoreCase()) { - result = result.toLowerCase(); - } - return result; - } - - public Object getValue() { - return fieldValue; - } - - public Object setValue(Object value) { - Object oldValue = fieldValue; - fieldValue = Preconditions.checkNotNull(value); - fieldInfo.setValue(object, value); - return oldValue; - } - - @Override - public int hashCode() { - return getKey().hashCode() ^ getValue().hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof Map.Entry)) { - return false; - } - Map.Entry other = (Map.Entry) obj; - return getKey().equals(other.getKey()) && getValue().equals(other.getValue()); - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/DateTime.java b/src/autosaveworld/zlibs/com/google/api/client/util/DateTime.java deleted file mode 100644 index 594881cd..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/DateTime.java +++ /dev/null @@ -1,361 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.io.Serializable; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Immutable representation of a date with an optional time and an optional time zone based on RFC 3339. - * - *

- * Implementation is immutable and therefore thread-safe. - *

- * - * @since 1.0 - * @author Yaniv Inbar - */ -public final class DateTime implements Serializable { - - private static final long serialVersionUID = 1L; - - private static final TimeZone GMT = TimeZone.getTimeZone("GMT"); - - /** Regular expression for parsing RFC3339 date/times. */ - private static final Pattern RFC3339_PATTERN = Pattern.compile( - "^(\\d{4})-(\\d{2})-(\\d{2})" // yyyy-MM-dd - + "([Tt](\\d{2}):(\\d{2}):(\\d{2})(\\.\\d+)?)?" // 'T'HH:mm:ss.milliseconds - + "([Zz]|([+-])(\\d{2}):(\\d{2}))?"); // 'Z' or time zone shift HH:mm following '+' or '-' - - /** - * Date/time value expressed as the number of ms since the Unix epoch. - * - *

- * If the time zone is specified, this value is normalized to UTC, so to format this date/time - * value, the time zone shift has to be applied. - *

- */ - private final long value; - - /** Specifies whether this is a date-only value. */ - private final boolean dateOnly; - - /** Time zone shift from UTC in minutes or {@code 0} for date-only value. */ - private final int tzShift; - - /** - * Instantiates {@link DateTime} from a {@link Date} and {@link TimeZone}. - * - * @param date date and time - * @param zone time zone; if {@code null}, it is interpreted as {@code TimeZone.getDefault()}. - */ - public DateTime(Date date, TimeZone zone) { - this(false, date.getTime(), zone == null ? null : zone.getOffset(date.getTime()) / 60000); - } - - /** - * Instantiates {@link DateTime} from the number of milliseconds since the Unix epoch. - * - *

- * The time zone is interpreted as {@code TimeZone.getDefault()}, which may vary with - * implementation. - *

- * - * @param value number of milliseconds since the Unix epoch (January 1, 1970, 00:00:00 GMT) - */ - public DateTime(long value) { - this(false, value, null); - } - - /** - * Instantiates {@link DateTime} from a {@link Date}. - * - *

- * The time zone is interpreted as {@code TimeZone.getDefault()}, which may vary with - * implementation. - *

- * - * @param value date and time - */ - public DateTime(Date value) { - this(value.getTime()); - } - - /** - * Instantiates {@link DateTime} from the number of milliseconds since the Unix epoch, and a shift - * from UTC in minutes. - * - * @param value number of milliseconds since the Unix epoch (January 1, 1970, 00:00:00 GMT) - * @param tzShift time zone, represented by the number of minutes off of UTC. - */ - public DateTime(long value, int tzShift) { - this(false, value, tzShift); - } - - /** - * Instantiates {@link DateTime}, which may represent a date-only value, from the number of - * milliseconds since the Unix epoch, and a shift from UTC in minutes. - * - * @param dateOnly specifies if this should represent a date-only value - * @param value number of milliseconds since the Unix epoch (January 1, 1970, 00:00:00 GMT) - * @param tzShift time zone, represented by the number of minutes off of UTC, or {@code null} for - * {@code TimeZone.getDefault()}. - */ - public DateTime(boolean dateOnly, long value, Integer tzShift) { - this.dateOnly = dateOnly; - this.value = value; - this.tzShift = - dateOnly ? 0 : tzShift == null ? TimeZone.getDefault().getOffset(value) / 60000 : tzShift; - } - - /** - * Instantiates {@link DateTime} from an RFC 3339 - * date/time value. - * - *

- * Upgrade warning: in prior version 1.17, this method required milliseconds to be exactly 3 - * digits (if included), and did not throw an exception for all types of invalid input values, but - * starting in version 1.18, the parsing done by this method has become more strict to enforce - * that only valid RFC3339 strings are entered, and if not, it throws a - * {@link NumberFormatException}. Also, in accordance with the RFC3339 standard, any number of - * milliseconds digits is now allowed. - *

- * - * @param value an RFC 3339 date/time value. - * @since 1.11 - */ - public DateTime(String value) { - // Note, the following refactoring is being considered: Move the implementation of parseRfc3339 - // into this constructor. Implementation of parseRfc3339 can then do - // "return new DateTime(str);". - DateTime dateTime = parseRfc3339(value); - this.dateOnly = dateTime.dateOnly; - this.value = dateTime.value; - this.tzShift = dateTime.tzShift; - } - - /** - * Returns the date/time value expressed as the number of milliseconds since the Unix epoch. - * - *

- * If the time zone is specified, this value is normalized to UTC, so to format this date/time - * value, the time zone shift has to be applied. - *

- * - * @since 1.5 - */ - public long getValue() { - return value; - } - - /** - * Returns whether this is a date-only value. - * - * @since 1.5 - */ - public boolean isDateOnly() { - return dateOnly; - } - - /** - * Returns the time zone shift from UTC in minutes or {@code 0} for date-only value. - * - * @since 1.5 - */ - public int getTimeZoneShift() { - return tzShift; - } - - /** Formats the value as an RFC 3339 date/time string. */ - public String toStringRfc3339() { - StringBuilder sb = new StringBuilder(); - Calendar dateTime = new GregorianCalendar(GMT); - long localTime = value + (tzShift * 60000L); - dateTime.setTimeInMillis(localTime); - // date - appendInt(sb, dateTime.get(Calendar.YEAR), 4); - sb.append('-'); - appendInt(sb, dateTime.get(Calendar.MONTH) + 1, 2); - sb.append('-'); - appendInt(sb, dateTime.get(Calendar.DAY_OF_MONTH), 2); - if (!dateOnly) { - // time - sb.append('T'); - appendInt(sb, dateTime.get(Calendar.HOUR_OF_DAY), 2); - sb.append(':'); - appendInt(sb, dateTime.get(Calendar.MINUTE), 2); - sb.append(':'); - appendInt(sb, dateTime.get(Calendar.SECOND), 2); - - if (dateTime.isSet(Calendar.MILLISECOND)) { - sb.append('.'); - appendInt(sb, dateTime.get(Calendar.MILLISECOND), 3); - } - // time zone - if (tzShift == 0) { - sb.append('Z'); - } else { - int absTzShift = tzShift; - if (tzShift > 0) { - sb.append('+'); - } else { - sb.append('-'); - absTzShift = -absTzShift; - } - - int tzHours = absTzShift / 60; - int tzMinutes = absTzShift % 60; - appendInt(sb, tzHours, 2); - sb.append(':'); - appendInt(sb, tzMinutes, 2); - } - } - return sb.toString(); - } - - @Override - public String toString() { - return toStringRfc3339(); - } - - /** - * {@inheritDoc} - * - *

- * A check is added that the time zone is the same. If you ONLY want to check equality of time - * value, check equality on the {@link #getValue()}. - *

- */ - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } - if (!(o instanceof DateTime)) { - return false; - } - DateTime other = (DateTime) o; - return dateOnly == other.dateOnly && value == other.value && tzShift == other.tzShift; - } - - @Override - public int hashCode() { - return Arrays.hashCode(new long[] {value, dateOnly ? 1 : 0, tzShift}); - } - - /** - * Parses an RFC3339 date/time value. - * - *

- * Upgrade warning: in prior version 1.17, this method required milliseconds to be exactly 3 - * digits (if included), and did not throw an exception for all types of invalid input values, but - * starting in version 1.18, the parsing done by this method has become more strict to enforce - * that only valid RFC3339 strings are entered, and if not, it throws a - * {@link NumberFormatException}. Also, in accordance with the RFC3339 standard, any number of - * milliseconds digits is now allowed. - *

- * - *

- * For the date-only case, the time zone is ignored and the hourOfDay, minute, second, and - * millisecond parameters are set to zero. - *

- * - * @param str Date/time string in RFC3339 format - * @throws NumberFormatException if {@code str} doesn't match the RFC3339 standard format; an - * exception is thrown if {@code str} doesn't match {@code RFC3339_REGEX} or if it - * contains a time zone shift but no time. - */ - public static DateTime parseRfc3339(String str) throws NumberFormatException { - Matcher matcher = RFC3339_PATTERN.matcher(str); - if (!matcher.matches()) { - throw new NumberFormatException("Invalid date/time format: " + str); - } - - int year = Integer.parseInt(matcher.group(1)); // yyyy - int month = Integer.parseInt(matcher.group(2)) - 1; // MM - int day = Integer.parseInt(matcher.group(3)); // dd - boolean isTimeGiven = matcher.group(4) != null; // 'T'HH:mm:ss.milliseconds - String tzShiftRegexGroup = matcher.group(9); // 'Z', or time zone shift HH:mm following '+'/'-' - boolean isTzShiftGiven = tzShiftRegexGroup != null; - int hourOfDay = 0; - int minute = 0; - int second = 0; - int milliseconds = 0; - Integer tzShiftInteger = null; - - if (isTzShiftGiven && !isTimeGiven) { - throw new NumberFormatException("Invalid date/time format, cannot specify time zone shift" + - " without specifying time: " + str); - } - - if (isTimeGiven) { - hourOfDay = Integer.parseInt(matcher.group(5)); // HH - minute = Integer.parseInt(matcher.group(6)); // mm - second = Integer.parseInt(matcher.group(7)); // ss - if (matcher.group(8) != null) { // contains .milliseconds? - milliseconds = Integer.parseInt(matcher.group(8).substring(1)); // milliseconds - // The number of digits after the dot may not be 3. Need to renormalize. - int fractionDigits = matcher.group(8).substring(1).length() - 3; - milliseconds = (int) ((float) milliseconds / Math.pow(10, fractionDigits)); - } - } - Calendar dateTime = new GregorianCalendar(GMT); - dateTime.set(year, month, day, hourOfDay, minute, second); - dateTime.set(Calendar.MILLISECOND, milliseconds); - long value = dateTime.getTimeInMillis(); - - if (isTimeGiven && isTzShiftGiven) { - int tzShift; - if (Character.toUpperCase(tzShiftRegexGroup.charAt(0)) == 'Z') { - tzShift = 0; - } else { - tzShift = Integer.parseInt(matcher.group(11)) * 60 // time zone shift HH - + Integer.parseInt(matcher.group(12)); // time zone shift mm - if (matcher.group(10).charAt(0) == '-') { // time zone shift + or - - tzShift = -tzShift; - } - value -= tzShift * 60000L; // e.g. if 1 hour ahead of UTC, subtract an hour to get UTC time - } - tzShiftInteger = tzShift; - } - return new DateTime(!isTimeGiven, value, tzShiftInteger); - } - - /** Appends a zero-padded number to a string builder. */ - private static void appendInt(StringBuilder sb, int num, int numDigits) { - if (num < 0) { - sb.append('-'); - num = -num; - } - int x = num; - while (x > 0) { - x /= 10; - numDigits--; - } - for (int i = 0; i < numDigits; i++) { - sb.append('0'); - } - if (num != 0) { - sb.append(num); - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/FieldInfo.java b/src/autosaveworld/zlibs/com/google/api/client/util/FieldInfo.java deleted file mode 100644 index 7557e511..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/FieldInfo.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.lang.reflect.Type; -import java.util.Map; -import java.util.WeakHashMap; - -/** - * Parses field information to determine data key name/value pair associated with the field. - * - *

- * Implementation is thread-safe. - *

- * - * @since 1.0 - * @author Yaniv Inbar - */ -public class FieldInfo { - - /** Cached field information. */ - private static final Map CACHE = new WeakHashMap(); - - /** - * Returns the field information for the given enum value. - * - * @param enumValue enum value - * @return field information - * @throws IllegalArgumentException if the enum value has no value annotation - * @since 1.4 - */ - public static FieldInfo of(Enum enumValue) { - try { - FieldInfo result = FieldInfo.of(enumValue.getClass().getField(enumValue.name())); - Preconditions.checkArgument( - result != null, "enum constant missing @Value or @NullValue annotation: %s", enumValue); - return result; - } catch (NoSuchFieldException e) { - // not possible - throw new RuntimeException(e); - } - } - - /** - * Returns the field information for the given field. - * - * @param field field or {@code null} for {@code null} result - * @return field information or {@code null} if the field has no {@link #name} or for {@code null} - * input - */ - public static FieldInfo of(Field field) { - if (field == null) { - return null; - } - synchronized (CACHE) { - FieldInfo fieldInfo = CACHE.get(field); - boolean isEnumContant = field.isEnumConstant(); - if (fieldInfo == null && (isEnumContant || !Modifier.isStatic(field.getModifiers()))) { - String fieldName; - if (isEnumContant) { - // check for @Value annotation - Value value = field.getAnnotation(Value.class); - if (value != null) { - fieldName = value.value(); - } else { - // check for @NullValue annotation - NullValue nullValue = field.getAnnotation(NullValue.class); - if (nullValue != null) { - fieldName = null; - } else { - // else ignore - return null; - } - } - } else { - // check for @Key annotation - Key key = field.getAnnotation(Key.class); - if (key == null) { - // else ignore - return null; - } - fieldName = key.value(); - field.setAccessible(true); - } - if ("##default".equals(fieldName)) { - fieldName = field.getName(); - } - fieldInfo = new FieldInfo(field, fieldName); - CACHE.put(field, fieldInfo); - } - return fieldInfo; - } - } - - /** Whether the field class is "primitive" as defined by {@link Data#isPrimitive(Type)}. */ - private final boolean isPrimitive; - - /** Field. */ - private final Field field; - - /** - * Data key name associated with the field for a non-enum-constant with a {@link Key} annotation, - * or data key value associated with the enum constant with a {@link Value} annotation or {@code - * null} for an enum constant with a {@link NullValue} annotation. - * - *

- * This string is interned. - *

- */ - private final String name; - - FieldInfo(Field field, String name) { - this.field = field; - this.name = name == null ? null : name.intern(); - isPrimitive = Data.isPrimitive(getType()); - } - - /** - * Returns the field. - * - * @since 1.4 - */ - public Field getField() { - return field; - } - - /** - * Returns the data key name associated with the field for a non-enum-constant with a {@link Key} - * annotation, or data key value associated with the enum constant with a {@link Value} annotation - * or {@code null} for an enum constant with a {@link NullValue} annotation. - * - *

- * This string is interned. - *

- * - * @since 1.4 - */ - public String getName() { - return name; - } - - /** - * Returns the field's type. - * - * @since 1.4 - */ - public Class getType() { - return field.getType(); - } - - /** - * Returns the field's generic type, which is a class, parameterized type, generic array type, or - * type variable, but not a wildcard type. - * - * @since 1.4 - */ - public Type getGenericType() { - return field.getGenericType(); - } - - /** - * Returns whether the field is final. - * - * @since 1.4 - */ - public boolean isFinal() { - return Modifier.isFinal(field.getModifiers()); - } - - /** - * Returns whether the field is primitive as defined by {@link Data#isPrimitive(Type)}. - * - * @since 1.4 - */ - public boolean isPrimitive() { - return isPrimitive; - } - - /** - * Returns the value of the field in the given object instance using reflection. - */ - public Object getValue(Object obj) { - return getFieldValue(field, obj); - } - - /** - * Sets to the given value of the field in the given object instance using reflection. - *

- * If the field is final, it checks that value being set is identical to the existing value. - */ - public void setValue(Object obj, Object value) { - setFieldValue(field, obj, value); - } - - /** Returns the class information of the field's declaring class. */ - public ClassInfo getClassInfo() { - return ClassInfo.of(field.getDeclaringClass()); - } - - @SuppressWarnings("unchecked") - public > T enumValue() { - return Enum.valueOf((Class) field.getDeclaringClass(), field.getName()); - } - - /** - * Returns the value of the given field in the given object instance using reflection. - */ - public static Object getFieldValue(Field field, Object obj) { - try { - return field.get(obj); - } catch (IllegalAccessException e) { - throw new IllegalArgumentException(e); - } - } - - /** - * Sets to the given value of the given field in the given object instance using reflection. - *

- * If the field is final, it checks that value being set is identical to the existing value. - */ - public static void setFieldValue(Field field, Object obj, Object value) { - if (Modifier.isFinal(field.getModifiers())) { - Object finalValue = getFieldValue(field, obj); - if (value == null ? finalValue != null : !value.equals(finalValue)) { - throw new IllegalArgumentException( - "expected final value <" + finalValue + "> but was <" + value + "> on " - + field.getName() + " field in " + obj.getClass().getName()); - } - } else { - try { - field.set(obj, value); - } catch (SecurityException e) { - throw new IllegalArgumentException(e); - } catch (IllegalAccessException e) { - throw new IllegalArgumentException(e); - } - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/GenericData.java b/src/autosaveworld/zlibs/com/google/api/client/util/GenericData.java deleted file mode 100644 index 1ce3a752..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/GenericData.java +++ /dev/null @@ -1,273 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.util.AbstractMap; -import java.util.AbstractSet; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentMap; - -/** - * Generic data that stores all unknown data key name/value pairs. - * - *

- * Subclasses can declare fields for known data keys using the {@link Key} annotation. Each field - * can be of any visibility (private, package private, protected, or public) and must not be static. - * {@code null} unknown data key names are not allowed, but {@code null} data values are allowed. - *

- * - *

- * Iteration order of the data keys is based on the sorted (ascending) key names of the declared - * fields, followed by the iteration order of all of the unknown data key name/value pairs. - *

- * - *

- * Implementation is not thread-safe. For a thread-safe choice instead use an implementation of - * {@link ConcurrentMap}. - *

- * - * @since 1.0 - * @author Yaniv Inbar - */ -public class GenericData extends AbstractMap implements Cloneable { - - /** Map of unknown fields. */ - Map unknownFields = ArrayMap.create(); - - // TODO(yanivi): implement more methods for faster implementation - - /** Class information. */ - final ClassInfo classInfo; - - /** - * Constructs with case-insensitive keys. - */ - public GenericData() { - this(EnumSet.noneOf(Flags.class)); - } - - /** - * Flags that impact behavior of generic data. - * @since 1.10 - */ - public enum Flags { - - /** Whether keys are case sensitive. */ - IGNORE_CASE - } - - /** - * @param flags flags that impact behavior of generic data - * @since 1.10 - */ - public GenericData(EnumSet flags) { - classInfo = ClassInfo.of(getClass(), flags.contains(Flags.IGNORE_CASE)); - } - - @Override - public final Object get(Object name) { - if (!(name instanceof String)) { - return null; - } - String fieldName = (String) name; - FieldInfo fieldInfo = classInfo.getFieldInfo(fieldName); - if (fieldInfo != null) { - return fieldInfo.getValue(this); - } - if (classInfo.getIgnoreCase()) { - fieldName = fieldName.toLowerCase(); - } - return unknownFields.get(fieldName); - } - - @Override - public final Object put(String fieldName, Object value) { - FieldInfo fieldInfo = classInfo.getFieldInfo(fieldName); - if (fieldInfo != null) { - Object oldValue = fieldInfo.getValue(this); - fieldInfo.setValue(this, value); - return oldValue; - } - if (classInfo.getIgnoreCase()) { - fieldName = fieldName.toLowerCase(); - } - return unknownFields.put(fieldName, value); - } - - /** - * Sets the given field value (may be {@code null}) for the given field name. Any existing value - * for the field will be overwritten. It may be more slightly more efficient than - * {@link #put(String, Object)} because it avoids accessing the field's original value. - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public GenericData set(String fieldName, Object value) { - FieldInfo fieldInfo = classInfo.getFieldInfo(fieldName); - if (fieldInfo != null) { - fieldInfo.setValue(this, value); - } else { - if (classInfo.getIgnoreCase()) { - fieldName = fieldName.toLowerCase(); - } - unknownFields.put(fieldName, value); - } - return this; - } - - @Override - public final void putAll(Map map) { - for (Map.Entry entry : map.entrySet()) { - set(entry.getKey(), entry.getValue()); - } - } - - @Override - public final Object remove(Object name) { - if (!(name instanceof String)) { - return null; - } - String fieldName = (String) name; - FieldInfo fieldInfo = classInfo.getFieldInfo(fieldName); - if (fieldInfo != null) { - throw new UnsupportedOperationException(); - } - if (classInfo.getIgnoreCase()) { - fieldName = fieldName.toLowerCase(); - } - return unknownFields.remove(fieldName); - } - - @Override - public Set> entrySet() { - return new EntrySet(); - } - - /** - * Makes a "deep" clone of the generic data, in which the clone is completely independent of the - * original. - */ - @Override - public GenericData clone() { - try { - GenericData result = (GenericData) super.clone(); - Data.deepCopy(this, result); - result.unknownFields = Data.clone(unknownFields); - return result; - } catch (CloneNotSupportedException e) { - throw new IllegalStateException(e); - } - } - - /** - * Returns the map of unknown data key name to value. - * - * @since 1.5 - */ - public final Map getUnknownKeys() { - return unknownFields; - } - - /** - * Sets the map of unknown data key name to value. - * - * @since 1.5 - */ - public final void setUnknownKeys(Map unknownFields) { - this.unknownFields = unknownFields; - } - - /** - * Returns the class information. - * - * @since 1.10 - */ - public final ClassInfo getClassInfo() { - return classInfo; - } - - /** Set of object data key/value map entries. */ - final class EntrySet extends AbstractSet> { - - private final DataMap.EntrySet dataEntrySet; - - EntrySet() { - dataEntrySet = new DataMap(GenericData.this, classInfo.getIgnoreCase()).entrySet(); - } - - @Override - public Iterator> iterator() { - return new EntryIterator(dataEntrySet); - } - - @Override - public int size() { - return unknownFields.size() + dataEntrySet.size(); - } - - @Override - public void clear() { - unknownFields.clear(); - dataEntrySet.clear(); - } - } - - /** - * Iterator over the object data key/value map entries which iterates first over the fields and - * then over the unknown keys. - */ - final class EntryIterator implements Iterator> { - - /** Whether we've started iterating over the unknown keys. */ - private boolean startedUnknown; - - /** Iterator over the fields. */ - private final Iterator> fieldIterator; - - /** Iterator over the unknown keys. */ - private final Iterator> unknownIterator; - - EntryIterator(DataMap.EntrySet dataEntrySet) { - fieldIterator = dataEntrySet.iterator(); - unknownIterator = unknownFields.entrySet().iterator(); - } - - public boolean hasNext() { - return fieldIterator.hasNext() || unknownIterator.hasNext(); - } - - public Map.Entry next() { - if (!startedUnknown) { - if (fieldIterator.hasNext()) { - return fieldIterator.next(); - } - startedUnknown = true; - } - return unknownIterator.next(); - } - - public void remove() { - if (startedUnknown) { - unknownIterator.remove(); - } - fieldIterator.remove(); - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/IOUtils.java b/src/autosaveworld/zlibs/com/google/api/client/util/IOUtils.java deleted file mode 100644 index ad2f81e0..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/IOUtils.java +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.lang.reflect.InvocationTargetException; - -/** - * Utilities for I/O streams. - * - * @author Yaniv Inbar - * @since 1.14 - */ -public class IOUtils { - - /** - * Writes the content provided by the given source input stream into the given destination output - * stream. - * - *

- * The input stream is guaranteed to be closed at the end of this method. - *

- * - *

- * Sample use: - *

- * - *
-  static void copy(InputStream inputStream, File file) throws IOException {
-    FileOutputStream out = new FileOutputStream(file);
-    try {
-      IOUtils.copy(inputStream, out);
-    } finally {
-      out.close();
-    }
-  }
-   * 
- * - * @param inputStream source input stream - * @param outputStream destination output stream - */ - public static void copy(InputStream inputStream, OutputStream outputStream) throws IOException { - copy(inputStream, outputStream, true); - } - - - /** - * Writes the content provided by the given source input stream into the given destination output - * stream, optionally closing the input stream. - * - *

- * Sample use: - *

- * - *
-  static void copy(InputStream inputStream, File file) throws IOException {
-    FileOutputStream out = new FileOutputStream(file);
-    try {
-      IOUtils.copy(inputStream, out, true);
-    } finally {
-      out.close();
-    }
-  }
-   * 
- * - * @param inputStream source input stream - * @param outputStream destination output stream - * @param closeInputStream whether the input stream should be closed at the end of this method - */ - public static void copy( - InputStream inputStream, OutputStream outputStream, boolean closeInputStream) - throws IOException { - try { - ByteStreams.copy(inputStream, outputStream); - } finally { - if (closeInputStream) { - inputStream.close(); - } - } - } - - - /** - * Computes and returns the byte content length for a streaming content by calling - * {@link StreamingContent#writeTo(OutputStream)} on a fake output stream that only counts bytes - * written. - * - * @param content streaming content - */ - public static long computeLength(StreamingContent content) throws IOException { - ByteCountingOutputStream countingStream = new ByteCountingOutputStream(); - try { - content.writeTo(countingStream); - } finally { - countingStream.close(); - } - return countingStream.count; - } - - /** - * Serializes the given object value to a newly allocated byte array. - * - * @param value object value to serialize - * @since 1.16 - */ - public static byte[] serialize(Object value) throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - serialize(value, out); - return out.toByteArray(); - } - - /** - * Serializes the given object value to an output stream, and close the output stream. - * - * @param value object value to serialize - * @param outputStream output stream to serialize into - * @since 1.16 - */ - public static void serialize(Object value, OutputStream outputStream) throws IOException { - try { - new ObjectOutputStream(outputStream).writeObject(value); - } finally { - outputStream.close(); - } - } - - /** - * Deserializes the given byte array into to a newly allocated object. - * - * @param bytes byte array to deserialize or {@code null} for {@code null} result - * @return new allocated object or {@code null} for {@code null} input - * @since 1.16 - */ - public static S deserialize(byte[] bytes) throws IOException { - if (bytes == null) { - return null; - } - return deserialize(new ByteArrayInputStream(bytes)); - } - - /** - * Deserializes the given input stream into to a newly allocated object, and close the input - * stream. - * - * @param inputStream input stream to deserialize - * @since 1.16 - */ - @SuppressWarnings("unchecked") - public static S deserialize(InputStream inputStream) throws IOException { - try { - return (S) new ObjectInputStream(inputStream).readObject(); - } catch (ClassNotFoundException exception) { - IOException ioe = new IOException("Failed to deserialize object"); - ioe.initCause(exception); - throw ioe; - } finally { - inputStream.close(); - } - } - - /** - * Returns whether the given file is a symbolic link. - * - * @since 1.16 - */ - public static boolean isSymbolicLink(File file) throws IOException { - // first try using Java 7 - try { - // use reflection here - Class filesClass = Class.forName("java.nio.file.Files"); - Class pathClass = Class.forName("java.nio.file.Path"); - Object path = File.class.getMethod("toPath").invoke(file); - return ((Boolean) filesClass.getMethod("isSymbolicLink", pathClass).invoke(null, path)) - .booleanValue(); - } catch (InvocationTargetException exception) { - Throwable cause = exception.getCause(); - Throwables.propagateIfPossible(cause, IOException.class); - // shouldn't reach this point, but just in case... - throw new RuntimeException(cause); - } catch (ClassNotFoundException exception) { - // handled below - } catch (IllegalArgumentException exception) { - // handled below - } catch (SecurityException exception) { - // handled below - } catch (IllegalAccessException exception) { - // handled below - } catch (NoSuchMethodException exception) { - // handled below - } - // backup option compatible with earlier Java - // this won't work on Windows, which is where separator char is '\\' - if (File.separatorChar == '\\') { - return false; - } - File canonical = file; - if (file.getParent() != null) { - canonical = new File(file.getParentFile().getCanonicalFile(), file.getName()); - } - return !canonical.getCanonicalFile().equals(canonical.getAbsoluteFile()); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/Joiner.java b/src/autosaveworld/zlibs/com/google/api/client/util/Joiner.java deleted file mode 100644 index b8e6eaa1..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/Joiner.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.util.Map; - -/** - * An object which joins pieces of text (specified as an array, {@link Iterable}, varargs or even a - * {@link Map}) with a separator. - * - *

- * NOTE: proxy for the Guava implementation of {@link com.google.common.base.Joiner}. - *

- * - * @since 1.14 - * @author Yaniv Inbar - */ -public final class Joiner { - - /** Wrapped joiner. */ - private final com.google.common.base.Joiner wrapped; - - /** - * Returns a joiner which automatically places {@code separator} between consecutive elements. - */ - public static Joiner on(char separator) { - return new Joiner(com.google.common.base.Joiner.on(separator)); - } - - /** - * @param wrapped wrapped joiner - */ - private Joiner(com.google.common.base.Joiner wrapped) { - this.wrapped = wrapped; - } - - /** - * Returns a string containing the string representation of each of {@code parts}, using the - * previously configured separator between each. - */ - public final String join(Iterable parts) { - return wrapped.join(parts); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/Key.java b/src/autosaveworld/zlibs/com/google/api/client/util/Key.java deleted file mode 100644 index d90e7604..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/Key.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Use this annotation to specify that a field is a data key, optionally providing the data key name - * to use. - *

- * If the data key name is not specified, the default is the Java field's name. For example: - *

- * - *

-  public class A {
-
-    // uses data key name of "dataKeyNameMatchesFieldName"
-    @Key
-    public String dataKeyNameMatchesFieldName;
-
-    // uses data key name of "some_other_name"
-    @Key("some_other_name")
-    private String dataKeyNameIsOverriden;
-
-    // not a data key
-    private String notADataKey;
-  }
- * 
- * - * @since 1.0 - * @author Yaniv Inbar - */ -@Target(ElementType.FIELD) -@Retention(RetentionPolicy.RUNTIME) -public @interface Key { - - /** - * Override the data key name of the field or {@code "##default"} to use the Java field's name. - */ - String value() default "##default"; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/Lists.java b/src/autosaveworld/zlibs/com/google/api/client/util/Lists.java deleted file mode 100644 index 3eb00fa5..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/Lists.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -/** - * Static utility methods pertaining to {@link List} instances. - * - *

- * NOTE: this is a copy of a subset of Guava's {@link com.google.common.collect.Lists}. The - * implementation must match as closely as possible to Guava's implementation. - *

- * - * @since 1.14 - * @author Yaniv Inbar - */ -public final class Lists { - - /** Returns a new mutable, empty {@code ArrayList} instance. */ - public static ArrayList newArrayList() { - return new ArrayList(); - } - - /** - * Creates an {@code ArrayList} instance backed by an array of the exact size specified; - * equivalent to {@link ArrayList#ArrayList(int)}. - * - * @param initialArraySize the exact size of the initial backing array for the returned array list - * ({@code ArrayList} documentation calls this value the "capacity") - * @return a new, empty {@code ArrayList} which is guaranteed not to resize itself unless its size - * reaches {@code initialArraySize + 1} - * @throws IllegalArgumentException if {@code initialArraySize} is negative - */ - public static ArrayList newArrayListWithCapacity(int initialArraySize) { - return new ArrayList(initialArraySize); - } - - /** - * Returns a new mutable {@code ArrayList} instance containing the given elements. - * - * @param elements the elements that the list should contain, in order - * @return a new {@code ArrayList} containing those elements - */ - public static ArrayList newArrayList(Iterable elements) { - return (elements instanceof Collection) - ? new ArrayList(Collections2.cast(elements)) : newArrayList(elements.iterator()); - } - - /** - * Returns a new mutable {@code ArrayList} instance containing the given elements. - * - * @param elements the elements that the list should contain, in order - * @return a new {@code ArrayList} containing those elements - */ - public static ArrayList newArrayList(Iterator elements) { - ArrayList list = newArrayList(); - while (elements.hasNext()) { - list.add(elements.next()); - } - return list; - } - - private Lists() { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/LoggingByteArrayOutputStream.java b/src/autosaveworld/zlibs/com/google/api/client/util/LoggingByteArrayOutputStream.java deleted file mode 100644 index 28a0c5f0..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/LoggingByteArrayOutputStream.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.text.NumberFormat; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Thread-safe byte array output stream that logs what was written to it when the stream is closed. - * - *

- * Use this as a safe way to log a limited amount of content. As content is written to the stream, - * it is stored as a byte array, up to the maximum number of bytes limit that was set in the - * constructor. Note that if the maximum limit is set too high, it risks an {@link OutOfMemoryError} - * on low-memory devices. This class also keeps track of the total number of bytes written, - * regardless of whether they were logged. On {@link #close()}, it then logs two records to the - * specified logger and logging level: the total number of bytes written, and the bounded content - * logged (assuming charset "UTF-8"). Any control characters are stripped out of the content. - *

- * - * @since 1.9 - * @author Yaniv Inbar - */ -public class LoggingByteArrayOutputStream extends ByteArrayOutputStream { - - /** Bytes written to the stream (may or may not have been logged). */ - private int bytesWritten; - - /** Maximum number of bytes to log (may be {@code 0} to avoid logging content). */ - private final int maximumBytesToLog; - - /** Whether the stream has already been closed. */ - private boolean closed; - - /** Logging level. */ - private final Level loggingLevel; - - /** Logger. */ - private final Logger logger; - - /** - * @param logger logger - * @param loggingLevel logging level - * @param maximumBytesToLog maximum number of bytes to log (may be {@code 0} to avoid logging - * content) - */ - public LoggingByteArrayOutputStream(Logger logger, Level loggingLevel, int maximumBytesToLog) { - this.logger = Preconditions.checkNotNull(logger); - this.loggingLevel = Preconditions.checkNotNull(loggingLevel); - Preconditions.checkArgument(maximumBytesToLog >= 0); - this.maximumBytesToLog = maximumBytesToLog; - } - - @Override - public synchronized void write(int b) { - Preconditions.checkArgument(!closed); - bytesWritten++; - if (count < maximumBytesToLog) { - super.write(b); - } - } - - @Override - public synchronized void write(byte[] b, int off, int len) { - Preconditions.checkArgument(!closed); - bytesWritten += len; - if (count < maximumBytesToLog) { - int end = count + len; - if (end > maximumBytesToLog) { - len += maximumBytesToLog - end; - } - super.write(b, off, len); - } - } - - @Override - public synchronized void close() throws IOException { - // circumvent double close - if (!closed) { - // log the response - if (bytesWritten != 0) { - // log response size - StringBuilder buf = new StringBuilder().append("Total: "); - LoggingByteArrayOutputStream.appendBytes(buf, bytesWritten); - if (count != 0 && count < bytesWritten) { - buf.append(" (logging first "); - LoggingByteArrayOutputStream.appendBytes(buf, count); - buf.append(")"); - } - logger.config(buf.toString()); - // log response content - if (count != 0) { - // strip out some unprintable control chars - logger.log(loggingLevel, - toString("UTF-8").replaceAll("[\\x00-\\x09\\x0B\\x0C\\x0E-\\x1F\\x7F]", " ")); - } - } - closed = true; - } - } - - /** Returns the maximum number of bytes to log (may be {@code 0} to avoid logging content). */ - public final int getMaximumBytesToLog() { - return maximumBytesToLog; - } - - /** Returns the bytes written to the stream (may or may not have been logged). */ - public final synchronized int getBytesWritten() { - return bytesWritten; - } - - private static void appendBytes(StringBuilder buf, int x) { - if (x == 1) { - buf.append("1 byte"); - } else { - buf.append(NumberFormat.getInstance().format(x)).append(" bytes"); - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/LoggingInputStream.java b/src/autosaveworld/zlibs/com/google/api/client/util/LoggingInputStream.java deleted file mode 100644 index c5efdfcd..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/LoggingInputStream.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Thread-safe input stream wrapper that forwards all reads to a given input stream, while logging - * all reads to a {@link LoggingByteArrayOutputStream}. - * - * @since 1.9 - * @author Yaniv Inbar - */ -public class LoggingInputStream extends FilterInputStream { - - /** Log stream. */ - private final LoggingByteArrayOutputStream logStream; - - /** - * @param inputStream input stream to forward all reads to - * @param logger logger - * @param loggingLevel logging level - * @param contentLoggingLimit maximum number of bytes to log (may be {@code 0} to avoid logging - * content) - */ - public LoggingInputStream( - InputStream inputStream, Logger logger, Level loggingLevel, int contentLoggingLimit) { - super(inputStream); - logStream = new LoggingByteArrayOutputStream(logger, loggingLevel, contentLoggingLimit); - } - - @Override - public int read() throws IOException { - int read = super.read(); - logStream.write(read); - return read; - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - int read = super.read(b, off, len); - if (read > 0) { - logStream.write(b, off, read); - } - return read; - } - - @Override - public void close() throws IOException { - logStream.close(); - super.close(); - } - - /** Returns the log stream. */ - public final LoggingByteArrayOutputStream getLogStream() { - return logStream; - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/LoggingOutputStream.java b/src/autosaveworld/zlibs/com/google/api/client/util/LoggingOutputStream.java deleted file mode 100644 index 91787082..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/LoggingOutputStream.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - - -import java.io.FilterOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Thread-safe output stream wrapper that forwards all writes to a given output stream, while - * logging all writes to a {@link LoggingByteArrayOutputStream}. - * - * @since 1.9 - * @author Yaniv Inbar - */ -public class LoggingOutputStream extends FilterOutputStream { - - /** Log stream. */ - private final LoggingByteArrayOutputStream logStream; - - /** - * @param outputStream output stream to forward all writes to - * @param logger logger - * @param loggingLevel logging level - * @param contentLoggingLimit maximum number of bytes to log (may be {@code 0} to avoid logging - * content) - */ - public LoggingOutputStream( - OutputStream outputStream, Logger logger, Level loggingLevel, int contentLoggingLimit) { - super(outputStream); - logStream = new LoggingByteArrayOutputStream(logger, loggingLevel, contentLoggingLimit); - } - - @Override - public void write(int b) throws IOException { - out.write(b); - logStream.write(b); - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - out.write(b, off, len); - logStream.write(b, off, len); - } - - @Override - public void close() throws IOException { - logStream.close(); - super.close(); - } - - /** Returns the log stream. */ - public final LoggingByteArrayOutputStream getLogStream() { - return logStream; - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/LoggingStreamingContent.java b/src/autosaveworld/zlibs/com/google/api/client/util/LoggingStreamingContent.java deleted file mode 100644 index 4f9616cc..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/LoggingStreamingContent.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Wraps another streaming content without modifying the content, but also logging content using - * {@link LoggingOutputStream}. - * - *

- * Implementation is not thread-safe. - *

- * - * @author Yaniv Inbar - * @since 1.14 - */ -public final class LoggingStreamingContent implements StreamingContent { - - /** Streaming content. */ - private final StreamingContent content; - - /** Maximum number of bytes to log or {@code 0} to avoid logging content. */ - private final int contentLoggingLimit; - - /** Logging level. */ - private final Level loggingLevel; - - /** Logger. */ - private final Logger logger; - - /** - * @param content streaming content - * @param logger logger - * @param loggingLevel logging level - * @param contentLoggingLimit maximum number of bytes to log or {@code 0} to avoid logging content - */ - public LoggingStreamingContent( - StreamingContent content, Logger logger, Level loggingLevel, int contentLoggingLimit) { - this.content = content; - this.logger = logger; - this.loggingLevel = loggingLevel; - this.contentLoggingLimit = contentLoggingLimit; - } - - public void writeTo(OutputStream out) throws IOException { - LoggingOutputStream loggableOutputStream = - new LoggingOutputStream(out, logger, loggingLevel, contentLoggingLimit); - try { - content.writeTo(loggableOutputStream); - } finally { - // force the log stream to close - loggableOutputStream.getLogStream().close(); - } - out.flush(); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/Maps.java b/src/autosaveworld/zlibs/com/google/api/client/util/Maps.java deleted file mode 100644 index 8aaf7456..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/Maps.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.TreeMap; - -/** - * Static utility methods pertaining to {@link Map} instances. - * - *

- * NOTE: this is a copy of a subset of Guava's {@link com.google.common.collect.Maps}. The - * implementation must match as closely as possible to Guava's implementation. - *

- * - * @since 1.14 - * @author Yaniv Inbar - */ -public final class Maps { - - /** Returns a new mutable, empty {@code HashMap} instance. */ - public static HashMap newHashMap() { - return new HashMap(); - } - - /** Returns a new mutable, empty, insertion-ordered {@code LinkedHashMap} instance. */ - public static LinkedHashMap newLinkedHashMap() { - return new LinkedHashMap(); - } - - /** - * Returns a new mutable, empty {@code TreeMap} instance using the natural ordering of its - * elements. - */ - public static , V> TreeMap newTreeMap() { - return new TreeMap(); - } - - private Maps() { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/NanoClock.java b/src/autosaveworld/zlibs/com/google/api/client/util/NanoClock.java deleted file mode 100644 index 371a3585..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/NanoClock.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -/** - * Nano clock which can be used to measure elapsed time in nanoseconds. - * - *

- * The default system implementation can be accessed at {@link #SYSTEM}. Alternative implementations - * may be used for testing. - *

- * - * @since 1.14 - * @author Yaniv Inbar - */ -public interface NanoClock { - - /** - * Returns the current value of the most precise available system timer, in nanoseconds for use to - * measure elapsed time, to match the behavior of {@link System#nanoTime()}. - */ - long nanoTime(); - - /** - * Provides the default System implementation of a nano clock by using {@link System#nanoTime()}. - */ - NanoClock SYSTEM = new NanoClock() { - public long nanoTime() { - return System.nanoTime(); - } - }; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/NullValue.java b/src/autosaveworld/zlibs/com/google/api/client/util/NullValue.java deleted file mode 100644 index b86e4308..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/NullValue.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Use this annotation to specify that an enum constant is the "null" data value to use for - * {@link Data#nullOf(Class)}. - *

- * See {@link Value} for an example. - *

- * - * @since 1.4 - * @author Yaniv Inbar - */ -@Target(ElementType.FIELD) -@Retention(RetentionPolicy.RUNTIME) -public @interface NullValue { - -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/ObjectParser.java b/src/autosaveworld/zlibs/com/google/api/client/util/ObjectParser.java deleted file mode 100644 index 19c60795..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/ObjectParser.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.lang.reflect.Type; -import java.nio.charset.Charset; - -/** - * Parses a data source into the specified data type. - * - *

- * Implementations should normally be thread-safe. - *

- * - * @author Yaniv Inbar - * @since 1.10 - */ -public interface ObjectParser { - - /** - * Parses the given input stream into a new instance of the the given data class of key/value - * pairs and closes the input stream. - * - * @param in input stream which contains the data to parse - * @param charset charset which should be used to decode the input stream or {@code null} if - * unknown - * @param dataClass class into which the data is parsed - */ - T parseAndClose(InputStream in, Charset charset, Class dataClass) throws IOException; - - /** - * Parses the given input stream into a new instance of the the given data type of key/value pairs - * and closes the input stream. - * - * @param in input stream which contains the data to parse - * @param charset charset which should be used to decode the input stream or {@code null} if - * unknown - * @param dataType type into which the data is parsed - */ - Object parseAndClose(InputStream in, Charset charset, Type dataType) throws IOException; - - /** - * Parses the given reader into a new instance of the the given data class of key/value pairs and - * closes the reader. - * - * @param reader reader which contains the text data to parse - * @param dataClass class into which the data is parsed - */ - T parseAndClose(Reader reader, Class dataClass) throws IOException; - - /** - * Parses the given reader into a new instance of the the given data type of key/value pairs and - * closes the reader. - * - * @param reader reader which contains the text data to parse - * @param dataType type into which the data is parsed - */ - Object parseAndClose(Reader reader, Type dataType) throws IOException; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/Objects.java b/src/autosaveworld/zlibs/com/google/api/client/util/Objects.java deleted file mode 100644 index 583e53a7..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/Objects.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -/** - * Helper functions that can operate on any {@code Object}. - * - * @since 1.14 - * @author Yaniv Inbar - */ -public final class Objects { - - /** - * Determines whether two possibly-null objects are equal. Returns: - * - *
    - *
  • {@code true} if {@code a} and {@code b} are both null.
  • - *
  • {@code true} if {@code a} and {@code b} are both non-null and they are equal according to - * {@link Object#equals(Object)}.
  • - *
  • {@code false} in all other situations.
  • - *
- * - *

- * This assumes that any non-null objects passed to this function conform to the {@code equals()} - * contract. - *

- */ - public static boolean equal(Object a, Object b) { - return com.google.common.base.Objects.equal(a, b); - } - - /** - * Creates an instance of {@link ToStringHelper}. - * - *

- * This is helpful for implementing {@link Object#toString()}. Specification by example: - *

- * - *
-   // Returns "ClassName{}"
-   Objects.toStringHelper(this)
-       .toString();
-
-   // Returns "ClassName{x=1}"
-   Objects.toStringHelper(this)
-       .add("x", 1)
-       .toString();
-
-   // Returns "MyObject{x=1}"
-   Objects.toStringHelper("MyObject")
-       .add("x", 1)
-       .toString();
-
-   // Returns "ClassName{x=1, y=foo}"
-   Objects.toStringHelper(this)
-       .add("x", 1)
-       .add("y", "foo")
-       .toString();
-
-   // Returns "ClassName{x=1}"
-   Objects.toStringHelper(this)
-       .omitNullValues()
-       .add("x", 1)
-       .add("y", null)
-       .toString();
-   * 
- * - * @param self the object to generate the string for (typically {@code this}), used only for its - * class name - */ - public static ToStringHelper toStringHelper(Object self) { - return new ToStringHelper(self.getClass().getSimpleName()); - } - - // TODO(ejona): Swap to wrapping MoreObjects.ToStringHelper once depending on Guava 18. - /** Support class for {@link Objects#toStringHelper}. */ - public static final class ToStringHelper { - private final String className; - private ValueHolder holderHead = new ValueHolder(); - private ValueHolder holderTail = holderHead; - private boolean omitNullValues; - - /** - * @param wrapped wrapped object - */ - ToStringHelper(String className) { - this.className = className; - } - - /** - * Configures the {@link ToStringHelper} so {@link #toString()} will ignore properties with null - * value. The order of calling this method, relative to the {@code add()}/{@code addValue()} - * methods, is not significant. - */ - public ToStringHelper omitNullValues() { - omitNullValues = true; - return this; - } - - /** - * Adds a name/value pair to the formatted output in {@code name=value} format. If {@code value} - * is {@code null}, the string {@code "null"} is used, unless {@link #omitNullValues()} is - * called, in which case this name/value pair will not be added. - */ - public ToStringHelper add(String name, Object value) { - return addHolder(name, value); - } - - @Override - public String toString() { - // create a copy to keep it consistent in case value changes - boolean omitNullValuesSnapshot = omitNullValues; - String nextSeparator = ""; - StringBuilder builder = new StringBuilder(32).append(className).append('{'); - for (ValueHolder valueHolder = holderHead.next; - valueHolder != null; - valueHolder = valueHolder.next) { - if (!omitNullValuesSnapshot || valueHolder.value != null) { - builder.append(nextSeparator); - nextSeparator = ", "; - - if (valueHolder.name != null) { - builder.append(valueHolder.name).append('='); - } - builder.append(valueHolder.value); - } - } - return builder.append('}').toString(); - } - - private ValueHolder addHolder() { - ValueHolder valueHolder = new ValueHolder(); - holderTail = holderTail.next = valueHolder; - return valueHolder; - } - - private ToStringHelper addHolder(String name, Object value) { - ValueHolder valueHolder = addHolder(); - valueHolder.value = value; - valueHolder.name = Preconditions.checkNotNull(name); - return this; - } - - private static final class ValueHolder { - String name; - Object value; - ValueHolder next; - } - } - - private Objects() { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/PemReader.java b/src/autosaveworld/zlibs/com/google/api/client/util/PemReader.java deleted file mode 100644 index 34f61cd3..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/PemReader.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.Reader; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * {@link Beta}
- * PEM file reader. - * - *

- * Supports reading any PEM stream that contains Base64 encoded content stored inside - * {@code "-----BEGIN ...-----"} and {@code "-----END ...-----"} tags. Each call to - * {@link #readNextSection()} parses the next section in the PEM file. If you need a section of a - * certain title use {@link #readNextSection(String)}, for example - * {@code readNextSection("PRIVATE KEY")}. To ensure that the stream is closed properly, call - * {@link #close()} in a finally block. - *

- * - *

- * As a convenience, use {@link #readFirstSectionAndClose(Reader)} or - * {@link #readFirstSectionAndClose(Reader, String)} for the common case of only a single section in - * a PEM file (or only a single section of a given title). - *

- * - *

- * Limitations: - *

- * - *

    - *
  • Assumes the PEM file section content is not encrypted and cannot handle the case of any - * headers inside the BEGIN and END tag.
  • - *
  • It also ignores any attributes associated with any PEM file section.
  • - *
- * - * @since 1.14 - * @author Yaniv Inbar - */ -@Beta -public final class PemReader { - - private static final Pattern BEGIN_PATTERN = Pattern.compile("-----BEGIN ([A-Z ]+)-----"); - private static final Pattern END_PATTERN = Pattern.compile("-----END ([A-Z ]+)-----"); - - /** Reader. */ - private BufferedReader reader; - - /** - * @param reader reader - */ - public PemReader(Reader reader) { - this.reader = new BufferedReader(reader); - } - - /** Reads the next section in the PEM file or {@code null} for end of file. */ - public Section readNextSection() throws IOException { - return readNextSection(null); - } - - /** - * Reads the next section in the PEM file, optionally based on a title to look for. - * - * @param titleToLookFor title to look for or {@code null} for any title - * @return next section or {@code null} for end of file - */ - public Section readNextSection(String titleToLookFor) throws IOException { - String title = null; - StringBuilder keyBuilder = null; - while (true) { - String line = reader.readLine(); - if (line == null) { - Preconditions.checkArgument(title == null, "missing end tag (%s)", title); - return null; - } - if (keyBuilder == null) { - Matcher m = BEGIN_PATTERN.matcher(line); - if (m.matches()) { - String curTitle = m.group(1); - if (titleToLookFor == null || curTitle.equals(titleToLookFor)) { - keyBuilder = new StringBuilder(); - title = curTitle; - } - } - } else { - Matcher m = END_PATTERN.matcher(line); - if (m.matches()) { - String endTitle = m.group(1); - Preconditions.checkArgument(endTitle.equals(title), - "end tag (%s) doesn't match begin tag (%s)", endTitle, title); - return new Section(title, Base64.decodeBase64(keyBuilder.toString())); - } - keyBuilder.append(line); - } - } - } - - /** - * Reads the first section in the PEM file, and then closes the reader. - * - * @param reader reader - * @return first section found or {@code null} for none found - */ - public static Section readFirstSectionAndClose(Reader reader) throws IOException { - return readFirstSectionAndClose(reader, null); - } - - /** - * Reads the first section in the PEM file, optionally based on a title to look for, and then - * closes the reader. - * - * @param titleToLookFor title to look for or {@code null} for any title - * @param reader reader - * @return first section found or {@code null} for none found - */ - public static Section readFirstSectionAndClose(Reader reader, String titleToLookFor) - throws IOException { - PemReader pemReader = new PemReader(reader); - try { - return pemReader.readNextSection(titleToLookFor); - } finally { - pemReader.close(); - } - } - - /** - * Closes the reader. - * - *

- * To ensure that the stream is closed properly, call {@link #close()} in a finally block. - *

- */ - public void close() throws IOException { - reader.close(); - } - - /** Section in the PEM file. */ - public static final class Section { - - /** Title. */ - private final String title; - - /** Base64-decoded bytes. */ - private final byte[] base64decodedBytes; - - /** - * @param title title - * @param base64decodedBytes base64-decoded bytes - */ - Section(String title, byte[] base64decodedBytes) { - this.title = Preconditions.checkNotNull(title); - this.base64decodedBytes = Preconditions.checkNotNull(base64decodedBytes); - } - - /** Returns the title. */ - public String getTitle() { - return title; - } - - /** Returns the base64-decoded bytes (modifiable array). */ - public byte[] getBase64DecodedBytes() { - return base64decodedBytes; - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/Preconditions.java b/src/autosaveworld/zlibs/com/google/api/client/util/Preconditions.java deleted file mode 100644 index 1c4b77c1..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/Preconditions.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -/** - * Simple static methods to be called at the start of your own methods to verify correct arguments - * and state. - * - *

- * NOTE: proxy for the Guava implementation of {@link com.google.common.base.Preconditions}. - *

- * - * @since 1.14 - * @author Yaniv Inbar - */ -public final class Preconditions { - - /** - * Ensures the truth of an expression involving one or more parameters to the calling method. - * - * @param expression a boolean expression - * @throws IllegalArgumentException if {@code expression} is false - */ - public static void checkArgument(boolean expression) { - com.google.common.base.Preconditions.checkArgument(expression); - } - - /** - * Ensures the truth of an expression involving one or more parameters to the calling method. - * - * @param expression a boolean expression - * @param errorMessage the exception message to use if the check fails; will be converted to a - * string using {@link String#valueOf(Object)} - * @throws IllegalArgumentException if {@code expression} is false - */ - public static void checkArgument(boolean expression, Object errorMessage) { - com.google.common.base.Preconditions.checkArgument(expression, errorMessage); - } - - /** - * Ensures the truth of an expression involving one or more parameters to the calling method. - * - * @param expression a boolean expression - * @param errorMessageTemplate a template for the exception message should the check fail. The - * message is formed by replacing each {@code %s} placeholder in the template with an - * argument. These are matched by position - the first {@code %s} gets - * {@code errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted - * message in square braces. Unmatched placeholders will be left as-is. - * @param errorMessageArgs the arguments to be substituted into the message template. Arguments - * are converted to strings using {@link String#valueOf(Object)}. - * @throws IllegalArgumentException if {@code expression} is false - * @throws NullPointerException if the check fails and either {@code errorMessageTemplate} or - * {@code errorMessageArgs} is null (don't let this happen) - */ - public static void checkArgument( - boolean expression, String errorMessageTemplate, Object... errorMessageArgs) { - com.google.common.base.Preconditions.checkArgument( - expression, errorMessageTemplate, errorMessageArgs); - } - - /** - * Ensures the truth of an expression involving the state of the calling instance, but not - * involving any parameters to the calling method. - * - * @param expression a boolean expression - * @throws IllegalStateException if {@code expression} is false - */ - public static void checkState(boolean expression) { - com.google.common.base.Preconditions.checkState(expression); - } - - /** - * Ensures the truth of an expression involving the state of the calling instance, but not - * involving any parameters to the calling method. - * - * @param expression a boolean expression - * @param errorMessage the exception message to use if the check fails; will be converted to a - * string using {@link String#valueOf(Object)} - * @throws IllegalStateException if {@code expression} is false - */ - public static void checkState(boolean expression, Object errorMessage) { - com.google.common.base.Preconditions.checkState(expression, errorMessage); - } - - /** - * Ensures the truth of an expression involving the state of the calling instance, but not - * involving any parameters to the calling method. - * - * @param expression a boolean expression - * @param errorMessageTemplate a template for the exception message should the check fail. The - * message is formed by replacing each {@code %s} placeholder in the template with an - * argument. These are matched by position - the first {@code %s} gets - * {@code errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted - * message in square braces. Unmatched placeholders will be left as-is. - * @param errorMessageArgs the arguments to be substituted into the message template. Arguments - * are converted to strings using {@link String#valueOf(Object)}. - * @throws IllegalStateException if {@code expression} is false - * @throws NullPointerException if the check fails and either {@code errorMessageTemplate} or - * {@code errorMessageArgs} is null (don't let this happen) - */ - public static void checkState( - boolean expression, String errorMessageTemplate, Object... errorMessageArgs) { - com.google.common.base.Preconditions.checkState( - expression, errorMessageTemplate, errorMessageArgs); - } - - /** - * Ensures that an object reference passed as a parameter to the calling method is not null. - * - * @param reference an object reference - * @return the non-null reference that was validated - * @throws NullPointerException if {@code reference} is null - */ - public static T checkNotNull(T reference) { - return com.google.common.base.Preconditions.checkNotNull(reference); - } - - /** - * Ensures that an object reference passed as a parameter to the calling method is not null. - * - * @param reference an object reference - * @param errorMessage the exception message to use if the check fails; will be converted to a - * string using {@link String#valueOf(Object)} - * @return the non-null reference that was validated - * @throws NullPointerException if {@code reference} is null - */ - public static T checkNotNull(T reference, Object errorMessage) { - return com.google.common.base.Preconditions.checkNotNull(reference, errorMessage); - } - - /** - * Ensures that an object reference passed as a parameter to the calling method is not null. - * - * @param reference an object reference - * @param errorMessageTemplate a template for the exception message should the check fail. The - * message is formed by replacing each {@code %s} placeholder in the template with an - * argument. These are matched by position - the first {@code %s} gets - * {@code errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted - * message in square braces. Unmatched placeholders will be left as-is. - * @param errorMessageArgs the arguments to be substituted into the message template. Arguments - * are converted to strings using {@link String#valueOf(Object)}. - * @return the non-null reference that was validated - * @throws NullPointerException if {@code reference} is null - */ - public static T checkNotNull( - T reference, String errorMessageTemplate, Object... errorMessageArgs) { - return com.google.common.base.Preconditions.checkNotNull( - reference, errorMessageTemplate, errorMessageArgs); - } - - private Preconditions() { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/SecurityUtils.java b/src/autosaveworld/zlibs/com/google/api/client/util/SecurityUtils.java deleted file mode 100644 index f9eb9034..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/SecurityUtils.java +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.security.GeneralSecurityException; -import java.security.InvalidKeyException; -import java.security.KeyFactory; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.Signature; -import java.security.SignatureException; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.util.List; - -import javax.net.ssl.X509TrustManager; - -/** - * Utilities related to Java security. - * - * @since 1.14 - * @author Yaniv Inbar - */ -public final class SecurityUtils { - - /** Returns the default key store using {@link KeyStore#getDefaultType()}. */ - public static KeyStore getDefaultKeyStore() throws KeyStoreException { - return KeyStore.getInstance(KeyStore.getDefaultType()); - } - - /** Returns the Java KeyStore (JKS). */ - public static KeyStore getJavaKeyStore() throws KeyStoreException { - return KeyStore.getInstance("JKS"); - } - - /** Returns the PKCS12 key store. */ - public static KeyStore getPkcs12KeyStore() throws KeyStoreException { - return KeyStore.getInstance("PKCS12"); - } - - /** - * Loads a key store from a stream. - * - * - *

- * Example usage: - *

- * - *
-    KeyStore keyStore = SecurityUtils.getJavaKeyStore();
-    SecurityUtils.loadKeyStore(keyStore, new FileInputStream("certs.jks"), "password");
-   * 
- * - * @param keyStore key store - * @param keyStream input stream to the key store stream (closed at the end of this method in a - * finally block) - * @param storePass password protecting the key store file - */ - public static void loadKeyStore(KeyStore keyStore, InputStream keyStream, String storePass) - throws IOException, GeneralSecurityException { - try { - keyStore.load(keyStream, storePass.toCharArray()); - } finally { - keyStream.close(); - } - } - - /** - * Returns the private key from the key store. - * - * @param keyStore key store - * @param alias alias under which the key is stored - * @param keyPass password protecting the key - * @return private key - */ - public static PrivateKey getPrivateKey(KeyStore keyStore, String alias, String keyPass) - throws GeneralSecurityException { - return (PrivateKey) keyStore.getKey(alias, keyPass.toCharArray()); - } - - /** - * Retrieves a private key from the specified key store stream and specified key store. - * - * @param keyStore key store - * @param keyStream input stream to the key store (closed at the end of this method in a finally - * block) - * @param storePass password protecting the key store file - * @param alias alias under which the key is stored - * @param keyPass password protecting the key - * @return key from the key store - */ - public static PrivateKey loadPrivateKeyFromKeyStore( - KeyStore keyStore, InputStream keyStream, String storePass, String alias, String keyPass) - throws IOException, GeneralSecurityException { - loadKeyStore(keyStore, keyStream, storePass); - return getPrivateKey(keyStore, alias, keyPass); - } - - /** Returns the RSA key factory. */ - public static KeyFactory getRsaKeyFactory() throws NoSuchAlgorithmException { - return KeyFactory.getInstance("RSA"); - } - - /** Returns the SHA-1 with RSA signature algorithm. */ - public static Signature getSha1WithRsaSignatureAlgorithm() throws NoSuchAlgorithmException { - return Signature.getInstance("SHA1withRSA"); - } - - /** Returns the SHA-256 with RSA signature algorithm. */ - public static Signature getSha256WithRsaSignatureAlgorithm() throws NoSuchAlgorithmException { - return Signature.getInstance("SHA256withRSA"); - } - - /** - * Signs content using a private key. - * - * @param signatureAlgorithm signature algorithm - * @param privateKey private key - * @param contentBytes content to sign - * @return signed content - */ - public static byte[] sign( - Signature signatureAlgorithm, PrivateKey privateKey, byte[] contentBytes) - throws InvalidKeyException, SignatureException { - signatureAlgorithm.initSign(privateKey); - signatureAlgorithm.update(contentBytes); - return signatureAlgorithm.sign(); - } - - /** - * Verifies the signature of signed content based on a public key. - * - * @param signatureAlgorithm signature algorithm - * @param publicKey public key - * @param signatureBytes signature bytes - * @param contentBytes content bytes - * @return whether the signature was verified - */ - public static boolean verify( - Signature signatureAlgorithm, PublicKey publicKey, byte[] signatureBytes, byte[] contentBytes) - throws InvalidKeyException, SignatureException { - signatureAlgorithm.initVerify(publicKey); - signatureAlgorithm.update(contentBytes); - // SignatureException may be thrown if we are tring the wrong key. - try { - return signatureAlgorithm.verify(signatureBytes); - } catch (SignatureException e) { - return false; - } - } - - /** - * Verifies the signature of signed content based on a certificate chain. - * - * @param signatureAlgorithm signature algorithm - * @param trustManager trust manager used to verify the certificate chain - * @param certChainBase64 Certificate chain used for verification. The certificates must be base64 - * encoded DER, the leaf certificate must be the first element. - * @param signatureBytes signature bytes - * @param contentBytes content bytes - * @return The signature certificate if the signature could be verified, null otherwise. - * @since 1.19.1. - */ - public static X509Certificate verify(Signature signatureAlgorithm, X509TrustManager trustManager, - List certChainBase64, byte[] signatureBytes, byte[] contentBytes) - throws InvalidKeyException, SignatureException { - CertificateFactory certificateFactory; - try { - certificateFactory = getX509CertificateFactory(); - } catch (CertificateException e) { - return null; - } - X509Certificate[] certificates = new X509Certificate[certChainBase64.size()]; - int currentCert = 0; - for (String certBase64 : certChainBase64) { - byte[] certDer = Base64.decodeBase64(certBase64); - ByteArrayInputStream bis = new ByteArrayInputStream(certDer); - try { - Certificate cert = certificateFactory.generateCertificate(bis); - if (!(cert instanceof X509Certificate)) { - return null; - } - certificates[currentCert++] = (X509Certificate) cert; - } catch (CertificateException e) { - return null; - } - } - try { - trustManager.checkServerTrusted(certificates, "RSA"); - } catch (CertificateException e) { - return null; - } - PublicKey pubKey = certificates[0].getPublicKey(); - if (verify(signatureAlgorithm, pubKey, signatureBytes, contentBytes)) { - return certificates[0]; - } - return null; - } - - /** Returns the X.509 certificate factory. */ - public static CertificateFactory getX509CertificateFactory() throws CertificateException { - return CertificateFactory.getInstance("X.509"); - } - - /** - * Loads a key store with certificates generated from the specified stream using - * {@link CertificateFactory#generateCertificates(InputStream)}. - * - *

- * For each certificate, {@link KeyStore#setCertificateEntry(String, Certificate)} is called with - * an alias that is the string form of incrementing non-negative integers starting with 0 (0, 1, - * 2, 3, ...). - *

- * - *

- * Example usage: - *

- * - *
-    KeyStore keyStore = SecurityUtils.getJavaKeyStore();
-    SecurityUtils.loadKeyStoreFromCertificates(keyStore, SecurityUtils.getX509CertificateFactory(),
-        new FileInputStream(pemFile));
-   * 
- * - * @param keyStore key store (for example {@link #getJavaKeyStore()}) - * @param certificateFactory certificate factory (for example - * {@link #getX509CertificateFactory()}) - * @param certificateStream certificate stream - */ - public static void loadKeyStoreFromCertificates( - KeyStore keyStore, CertificateFactory certificateFactory, InputStream certificateStream) - throws GeneralSecurityException { - int i = 0; - for (Certificate cert : certificateFactory.generateCertificates(certificateStream)) { - keyStore.setCertificateEntry(String.valueOf(i), cert); - i++; - } - } - - private SecurityUtils() { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/Sets.java b/src/autosaveworld/zlibs/com/google/api/client/util/Sets.java deleted file mode 100644 index e2b20624..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/Sets.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.util.HashSet; -import java.util.Set; -import java.util.TreeSet; - -/** - * Static utility methods pertaining to {@link Set} instances. - * - *

- * NOTE: this is a copy of a subset of Guava's {@link com.google.common.collect.Sets}. The - * implementation must match as closely as possible to Guava's implementation. - *

- * - * @since 1.14 - * @author Yaniv Inbar - */ -public final class Sets { - - /** Returns a new mutable, empty {@code HashSet} instance. */ - public static HashSet newHashSet() { - return new HashSet(); - } - - /** - * Returns a new mutable, empty {@code TreeSet} instance sorted by the natural sort ordering of - * its elements. - */ - public static > TreeSet newTreeSet() { - return new TreeSet(); - } - - private Sets() { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/Sleeper.java b/src/autosaveworld/zlibs/com/google/api/client/util/Sleeper.java deleted file mode 100644 index daed1647..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/Sleeper.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -/** - * Sleeper interface to use for requesting the current thread to sleep as specified in - * {@link Thread#sleep(long)}. - * - *

- * The default implementation can be accessed at {@link #DEFAULT}. Primarily used for testing. - *

- * - * @since 1.14 - * @author Yaniv Inbar - */ -public interface Sleeper { - - /** - * Causes the currently executing thread to sleep (temporarily cease execution) for the specified - * number of milliseconds as specified in {@link Thread#sleep(long)}. - * - * @param millis length of time to sleep in milliseconds - * @throws InterruptedException if any thread has interrupted the current thread - */ - void sleep(long millis) throws InterruptedException; - - /** Provides the default implementation based on {@link Thread#sleep(long)}. */ - Sleeper DEFAULT = new Sleeper() { - - public void sleep(long millis) throws InterruptedException { - Thread.sleep(millis); - } - }; - -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/StreamingContent.java b/src/autosaveworld/zlibs/com/google/api/client/util/StreamingContent.java deleted file mode 100644 index fa772635..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/StreamingContent.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.io.IOException; -import java.io.OutputStream; - -/** - * Streaming content interface to write bytes to an output stream. - * - *

- * Implementations don't need to be thread-safe. - *

- * - * @since 1.14 - * @author Yaniv Inbar - */ -public interface StreamingContent { - - /** - * Writes the byte content to the given output stream. - * - *

- * Implementations must not close the output stream, and instead should flush the output stream. - * Some callers may assume that the the output stream has not been closed, and will fail to work - * if it has been closed. - *

- * - * @param out output stream - */ - void writeTo(OutputStream out) throws IOException; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/StringUtils.java b/src/autosaveworld/zlibs/com/google/api/client/util/StringUtils.java deleted file mode 100644 index 085e40d0..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/StringUtils.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2012 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.io.UnsupportedEncodingException; - - -/** - * Utilities for strings. - * - *

- * Some of these methods are a proxy for version 1.6 (or newer) of the Apache Commons Codec - * {@link StringUtils} implementation. This is needed in order to support platforms like Android - * which already include an older version of the Apache Commons Codec (Android includes version - * 1.3). To avoid a dependency library conflict, this library includes a reduced private copy of - * version 1.6 (or newer) of the Apache Commons Codec (using a tool like jarjar). - *

- * - * @since 1.8 - * @author Yaniv Inbar - */ -public class StringUtils { - - /** - * Line separator to use for this OS, i.e. {@code "\n"} or {@code "\r\n"}. - * - * @since 1.8 - */ - public static final String LINE_SEPARATOR = System.getProperty("line.separator"); - - /** - * Encodes the given string into a sequence of bytes using the UTF-8 charset, storing the result - * into a new byte array. - * - * @param string the String to encode, may be null - * @return encoded bytes, or null if the input string was null - * @throws IllegalStateException Thrown when the charset is missing, which should be never - * according the the Java specification. - * @see Standard charsets - * @see org.apache.commons.codec.binary.StringUtils#getBytesUtf8(String) - * @since 1.8 - */ - public static byte[] getBytesUtf8(String string) { - return org.apache.commons.codec.binary.StringUtils.getBytesUtf8(string); - } - - /** - * Constructs a new String by decoding the specified array of bytes using the UTF-8 - * charset. - * - * @param bytes The bytes to be decoded into characters - * @return A new String decoded from the specified array of bytes using the UTF-8 - * charset, or null if the input byte array was null. - * @throws IllegalStateException Thrown when a {@link UnsupportedEncodingException} is caught, - * which should never happen since the charset is required. - * @see org.apache.commons.codec.binary.StringUtils#newStringUtf8(byte[]) - * @since 1.8 - */ - public static String newStringUtf8(byte[] bytes) { - return org.apache.commons.codec.binary.StringUtils.newStringUtf8(bytes); - } - - private StringUtils() { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/Strings.java b/src/autosaveworld/zlibs/com/google/api/client/util/Strings.java deleted file mode 100644 index 6224da69..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/Strings.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -/** - * Static utility methods pertaining to {@code String} instances. - * - *

- * NOTE: proxy for the Guava implementation of {@link com.google.common.base.Strings}. - *

- * - * @since 1.14 - * @author Yaniv Inbar - */ -public final class Strings { - - /** - * Returns {@code true} if the given string is null or is the empty string. - * - * @param string a string reference to check (may be {@code null}) - * @return {@code true} if the string is null or is the empty string - */ - public static boolean isNullOrEmpty(String string) { - return com.google.common.base.Strings.isNullOrEmpty(string); - } - - private Strings() { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/Throwables.java b/src/autosaveworld/zlibs/com/google/api/client/util/Throwables.java deleted file mode 100644 index a6896749..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/Throwables.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -/** - * Static utility methods pertaining to instances of {@link Throwable}. - * - *

- * NOTE: proxy for the Guava implementation of {@link com.google.common.base.Throwables}. - *

- * - * @since 1.14 - * @author Yaniv Inbar - */ -public final class Throwables { - - /** - * Propagates {@code throwable} as-is if it is an instance of {@link RuntimeException} or - * {@link Error}, or else as a last resort, wraps it in a {@code RuntimeException} then - * propagates. - *

- * This method always throws an exception. The {@code RuntimeException} return type is only for - * client code to make Java type system happy in case a return value is required by the enclosing - * method. Example usage: - *

- * - *
-    T doSomething() {
-      try {
-        return someMethodThatCouldThrowAnything();
-      } catch (IKnowWhatToDoWithThisException e) {
-        return handle(e);
-      } catch (Throwable t) {
-        throw Throwables.propagate(t);
-      }
-    }
-   *
- * - * @param throwable the Throwable to propagate - * @return nothing will ever be returned; this return type is only for your convenience, as - * illustrated in the example above - */ - public static RuntimeException propagate(Throwable throwable) { - return com.google.common.base.Throwables.propagate(throwable); - } - - /** - * Propagates {@code throwable} exactly as-is, if and only if it is an instance of - * {@link RuntimeException} or {@link Error}. Example usage: - * - *
-    try {
-      someMethodThatCouldThrowAnything();
-    } catch (IKnowWhatToDoWithThisException e) {
-      handle(e);
-    } catch (Throwable t) {
-      Throwables.propagateIfPossible(t);
-      throw new RuntimeException("unexpected", t);
-    }
-   * 
- * - * @param throwable throwable (may be {@code null}) - */ - public static void propagateIfPossible(Throwable throwable) { - com.google.common.base.Throwables.propagateIfPossible(throwable); - } - - /** - * Propagates {@code throwable} exactly as-is, if and only if it is an instance of - * {@link RuntimeException}, {@link Error}, or {@code declaredType}. Example usage: - * - *
-    try {
-      someMethodThatCouldThrowAnything();
-    } catch (IKnowWhatToDoWithThisException e) {
-      handle(e);
-    } catch (Throwable t) {
-      Throwables.propagateIfPossible(t, OtherException.class);
-      throw new RuntimeException("unexpected", t);
-    }
-   *
- * - * @param throwable throwable (may be {@code null}) - * @param declaredType the single checked exception type declared by the calling method - */ - public static void propagateIfPossible( - Throwable throwable, Class declaredType) throws X { - com.google.common.base.Throwables.propagateIfPossible(throwable, declaredType); - } - - private Throwables() { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/Types.java b/src/autosaveworld/zlibs/com/google/api/client/util/Types.java deleted file mode 100644 index b8db0c1a..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/Types.java +++ /dev/null @@ -1,413 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - - -import java.lang.reflect.Array; -import java.lang.reflect.GenericArrayType; -import java.lang.reflect.GenericDeclaration; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.lang.reflect.WildcardType; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; - -/** - * Utilities for working with Java types. - * - * @since 1.4 - * @author Yaniv Inbar - */ -public class Types { - - /** - * Returns the parameterized type that is or extends the given type that matches the given super - * class. - * - *

- * For example, if the input type is {@code HashMap} and the input super class is - * {@code Map.class}, it will return the extended parameterized type {@link Map}, but which - * retains the actual type information from the original {@code HashMap}. - *

- * - * @param type class or parameterized type - * @param superClass super class - * @return matching parameterized type or {@code null} - */ - public static ParameterizedType getSuperParameterizedType(Type type, Class superClass) { - if (type instanceof Class || type instanceof ParameterizedType) { - outer: while (type != null && type != Object.class) { - Class rawType; - if (type instanceof Class) { - // type is a class - rawType = (Class) type; - } else { - // current is a parameterized type - ParameterizedType parameterizedType = (ParameterizedType) type; - rawType = getRawClass(parameterizedType); - // check if found Collection - if (rawType == superClass) { - // return the actual collection parameter - return parameterizedType; - } - if (superClass.isInterface()) { - for (Type interfaceType : rawType.getGenericInterfaces()) { - // interface type is class or parameterized type - Class interfaceClass = - interfaceType instanceof Class ? (Class) interfaceType : getRawClass( - (ParameterizedType) interfaceType); - if (superClass.isAssignableFrom(interfaceClass)) { - type = interfaceType; - continue outer; - } - } - } - } - // move on to the super class - type = rawType.getGenericSuperclass(); - } - } - return null; - } - - /** - * Returns whether a class is either assignable to or from another class. - * - * @param classToCheck class to check - * @param anotherClass another class - */ - public static boolean isAssignableToOrFrom(Class classToCheck, Class anotherClass) { - return classToCheck.isAssignableFrom(anotherClass) - || anotherClass.isAssignableFrom(classToCheck); - } - - /** - * Creates a new instance of the given class by invoking its default constructor. - * - *

- * The given class must be public and must have a public default constructor, and must not be an - * array or an interface or be abstract. If an enclosing class, it must be static. - *

- */ - public static T newInstance(Class clazz) { - // TODO(yanivi): investigate "sneaky" options for allocating the class that GSON uses, like - // setting the constructor to be accessible, or possibly provide a factory method of a special - // name - try { - return clazz.newInstance(); - } catch (IllegalAccessException e) { - throw handleExceptionForNewInstance(e, clazz); - } catch (InstantiationException e) { - throw handleExceptionForNewInstance(e, clazz); - } - } - - private static IllegalArgumentException handleExceptionForNewInstance( - Exception e, Class clazz) { - StringBuilder buf = - new StringBuilder("unable to create new instance of class ").append(clazz.getName()); - ArrayList reasons = new ArrayList(); - if (clazz.isArray()) { - reasons.add("because it is an array"); - } else if (clazz.isPrimitive()) { - reasons.add("because it is primitive"); - } else if (clazz == Void.class) { - reasons.add("because it is void"); - } else { - if (Modifier.isInterface(clazz.getModifiers())) { - reasons.add("because it is an interface"); - } else if (Modifier.isAbstract(clazz.getModifiers())) { - reasons.add("because it is abstract"); - } - if (clazz.getEnclosingClass() != null && !Modifier.isStatic(clazz.getModifiers())) { - reasons.add("because it is not static"); - } - // we don't know what visibility is necessary, but we can give a hint - if (!Modifier.isPublic(clazz.getModifiers())) { - reasons.add("possibly because it is not public"); - } else { - try { - clazz.getConstructor(); - } catch (NoSuchMethodException e1) { - reasons.add("because it has no accessible default constructor"); - } - } - } - // append reasons - boolean and = false; - for (String reason : reasons) { - if (and) { - buf.append(" and"); - } else { - and = true; - } - buf.append(" ").append(reason); - } - return new IllegalArgumentException(buf.toString(), e); - } - - /** Returns whether the given type is an array. */ - public static boolean isArray(Type type) { - return type instanceof GenericArrayType || type instanceof Class - && ((Class) type).isArray(); - } - - /** - * Returns the component type of the given array type, assuming {@link #isArray(Type)}. - * - *

- * Return type will either be class, parameterized type, generic array type, or type variable, but - * not a wildcard type. - *

- * - * @throws ClassCastException if {@link #isArray(Type)} is false - */ - public static Type getArrayComponentType(Type array) { - return array instanceof GenericArrayType ? ((GenericArrayType) array).getGenericComponentType() - : ((Class) array).getComponentType(); - } - - /** - * Returns the raw class for the given parameter type as defined in - * {@link ParameterizedType#getRawType()}. - * - * @param parameterType parameter type - * @return raw class - */ - public static Class getRawClass(ParameterizedType parameterType) { - return (Class) parameterType.getRawType(); - } - - /** - * Returns the only bound of the given wildcard type. - * - * @param wildcardType wildcard type - * @return only bound or {@code Object.class} for none - */ - public static Type getBound(WildcardType wildcardType) { - Type[] lowerBounds = wildcardType.getLowerBounds(); - if (lowerBounds.length != 0) { - return lowerBounds[0]; - } - return wildcardType.getUpperBounds()[0]; - } - - /** - * Resolves the actual type of the given type variable that comes from a field type based on the - * given context list. - *

- * In case the type variable can be resolved partially, it will return the partially resolved type - * variable. - *

- * - * @param context context list, ordering from least specific to most specific type context, for - * example container class and then its field - * @param typeVariable type variable - * @return resolved or partially resolved actual type (type variable, class, parameterized type, - * or generic array type, but not wildcard type) or {@code null} if unable to resolve at - * all - */ - public static Type resolveTypeVariable(List context, TypeVariable typeVariable) { - // determine where the type variable was declared - GenericDeclaration genericDeclaration = typeVariable.getGenericDeclaration(); - if (genericDeclaration instanceof Class) { - Class rawGenericDeclaration = (Class) genericDeclaration; - // check if the context extends that declaration - int contextIndex = context.size(); - ParameterizedType parameterizedType = null; - while (parameterizedType == null && --contextIndex >= 0) { - parameterizedType = - getSuperParameterizedType(context.get(contextIndex), rawGenericDeclaration); - } - if (parameterizedType != null) { - // find the type variable's index in the declaration's type parameters - TypeVariable[] typeParameters = genericDeclaration.getTypeParameters(); - int index = 0; - for (; index < typeParameters.length; index++) { - TypeVariable typeParameter = typeParameters[index]; - if (typeParameter.equals(typeVariable)) { - break; - } - } - // use that index to get the actual type argument - Type result = parameterizedType.getActualTypeArguments()[index]; - if (result instanceof TypeVariable) { - // attempt to resolve type variable - Type resolve = resolveTypeVariable(context, (TypeVariable) result); - if (resolve != null) { - return resolve; - } - // partially resolved type variable is okay - } - return result; - } - } - return null; - } - - /** - * Returns the raw array component type to use -- for example for the first parameter of - * {@link Array#newInstance(Class, int)} -- for the given component type. - * - * @param context context list, ordering from least specific to most specific type context, for - * example container class and then its field - * @param componentType array component type or {@code null} for {@code Object.class} result - * @return raw array component type - */ - public static Class getRawArrayComponentType(List context, Type componentType) { - if (componentType instanceof TypeVariable) { - componentType = Types.resolveTypeVariable(context, (TypeVariable) componentType); - } - if (componentType instanceof GenericArrayType) { - Class raw = getRawArrayComponentType(context, Types.getArrayComponentType(componentType)); - return Array.newInstance(raw, 0).getClass(); - } - if (componentType instanceof Class) { - return (Class) componentType; - } - if (componentType instanceof ParameterizedType) { - return Types.getRawClass((ParameterizedType) componentType); - } - Preconditions.checkArgument( - componentType == null, "wildcard type is not supported: %s", componentType); - return Object.class; - } - - /** - * Returns the type parameter of {@link Iterable} that is assignable from the given iterable type. - * - *

- * For example, for the type {@code ArrayList} -- or for a class that extends {@code - * ArrayList} -- it will return {@code Integer}. - *

- * - * @param iterableType iterable type (must extend {@link Iterable}) - * @return type parameter, which may be any type - */ - public static Type getIterableParameter(Type iterableType) { - return getActualParameterAtPosition(iterableType, Iterable.class, 0); - } - - /** - * Returns the value type parameter of {@link Map} that is assignable from the given map type. - * - *

- * For example, for the type {@code Map} -- or for a class that extends {@code - * Map} -- it will return {@code Integer}. - *

- * - * @param mapType map type (must extend {@link Map}) - * @return type parameter, which may be any type - */ - public static Type getMapValueParameter(Type mapType) { - return getActualParameterAtPosition(mapType, Map.class, 1); - } - - private static Type getActualParameterAtPosition(Type type, Class superClass, int position) { - ParameterizedType parameterizedType = Types.getSuperParameterizedType(type, superClass); - if (parameterizedType == null) { - return null; - } - Type valueType = parameterizedType.getActualTypeArguments()[position]; - // this is normally a type variable, except in the case where the class of iterableType is - // superClass, e.g. Iterable - if (valueType instanceof TypeVariable) { - Type resolve = Types.resolveTypeVariable(Arrays.asList(type), (TypeVariable) valueType); - if (resolve != null) { - return resolve; - } - } - return valueType; - } - - /** - * Returns an iterable for an input iterable or array value. - * - *

- * If the input value extends {@link Iterable}, it will just return the input value. Otherwise, it - * will return an iterable that can handle arrays of primitive and non-primitive component type. - *

- * - * @param value iterable (extends {@link Iterable}) or array value - * @return iterable - */ - @SuppressWarnings("unchecked") - public static Iterable iterableOf(final Object value) { - if (value instanceof Iterable) { - return (Iterable) value; - } - Class valueClass = value.getClass(); - Preconditions.checkArgument(valueClass.isArray(), "not an array or Iterable: %s", valueClass); - Class subClass = valueClass.getComponentType(); - if (!subClass.isPrimitive()) { - return Arrays.asList((T[]) value); - } - return new Iterable() { - - public Iterator iterator() { - return new Iterator() { - - final int length = Array.getLength(value); - int index = 0; - - public boolean hasNext() { - return index < length; - } - - public T next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - return (T) Array.get(value, index++); - } - - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - }; - } - - /** - * Returns a new array of the given component type (possibly a Java primitive) that is a copy of - * the content of the given collection. - * - * @param collection collection - * @param componentType component type (possibly a Java primitive) - * @return new array - */ - public static Object toArray(Collection collection, Class componentType) { - if (componentType.isPrimitive()) { - Object array = Array.newInstance(componentType, collection.size()); - int index = 0; - for (Object value : collection) { - Array.set(array, index++, value); - } - return array; - } - return collection.toArray((Object[]) Array.newInstance(componentType, collection.size())); - } - - private Types() { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/Value.java b/src/autosaveworld/zlibs/com/google/api/client/util/Value.java deleted file mode 100644 index 85e32a35..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/Value.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Use this annotation to specify that an enum constant is a string data value, optionally providing - * the string data value to use. - *

- * If the string data value is not specified, the default is the Java field's name. For example: - *

- * - *
-  public enum A {
-
-    // value is "USE_FIELD_NAME"
-    @Value
-    USE_FIELD_NAME,
-    
-    // value is "specifiedValue"
-    @Value("specifiedValue")
-    USE_SPECIFIED_VALUE, 
-    
-    // value is null
-    @NullValue
-    NULL_VALUE
-
-    // not a value
-    NOT_A_VALUE
-  }
- * 
- * - * @since 1.4 - * @author Yaniv Inbar - */ -@Target(ElementType.FIELD) -@Retention(RetentionPolicy.RUNTIME) -public @interface Value { - - /** - * Override the string data value of the field or {@code "##default"} to use the Java field's - * name. - */ - String value() default "##default"; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/escape/CharEscapers.java b/src/autosaveworld/zlibs/com/google/api/client/util/escape/CharEscapers.java deleted file mode 100644 index d037eacc..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/escape/CharEscapers.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util.escape; - -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; - -/** - * Utility functions for dealing with {@code CharEscaper}s, and some commonly used - * {@code CharEscaper} instances. - * - * @since 1.0 - */ -public final class CharEscapers { - - private static final Escaper URI_ESCAPER = - new PercentEscaper(PercentEscaper.SAFECHARS_URLENCODER, true); - - private static final Escaper URI_PATH_ESCAPER = - new PercentEscaper(PercentEscaper.SAFEPATHCHARS_URLENCODER, false); - - private static final Escaper URI_RESERVED_ESCAPER = - new PercentEscaper(PercentEscaper.SAFE_PLUS_RESERVED_CHARS_URLENCODER, false); - - private static final Escaper URI_USERINFO_ESCAPER = - new PercentEscaper(PercentEscaper.SAFEUSERINFOCHARS_URLENCODER, false); - - private static final Escaper URI_QUERY_STRING_ESCAPER = - new PercentEscaper(PercentEscaper.SAFEQUERYSTRINGCHARS_URLENCODER, false); - - /** - * Escapes the string value so it can be safely included in URIs. For details on escaping URIs, - * see RFC 3986 - section 2.4. - * - *

- * When encoding a String, the following rules apply: - *

    - *
  • The alphanumeric characters "a" through "z", "A" through "Z" and "0" through "9" remain the - * same. - *
  • The special characters ".", "-", "*", and "_" remain the same. - *
  • The space character " " is converted into a plus sign "+". - *
  • All other characters are converted into one or more bytes using UTF-8 encoding and each - * byte is then represented by the 3-character string "%XY", where "XY" is the two-digit, - * uppercase, hexadecimal representation of the byte value. - *
- *

- * - *

- * Note: Unlike other escapers, URI escapers produce uppercase hexadecimal sequences. From - * RFC 3986:
- * "URI producers and normalizers should use uppercase hexadecimal digits for all - * percent-encodings." - *

- * - *

- * This escaper has identical behavior to (but is potentially much faster than): - *

    - *
  • {@link java.net.URLEncoder#encode(String, String)} with the encoding name "UTF-8" - *
- *

- */ - public static String escapeUri(String value) { - return URI_ESCAPER.escape(value); - } - - /** - * Percent-decodes a US-ASCII string into a Unicode string. UTF-8 encoding is used to determine - * what characters are represented by any consecutive sequences of the form "%XX". - * - *

- * This replaces each occurrence of '+' with a space, ' '. So this method should not be used for - * non application/x-www-form-urlencoded strings such as host and path. - *

- * - * @param uri a percent-encoded US-ASCII string - * @return a Unicode string - */ - public static String decodeUri(String uri) { - try { - return URLDecoder.decode(uri, "UTF-8"); - } catch (UnsupportedEncodingException e) { - // UTF-8 encoding guaranteed to be supported by JVM - throw new RuntimeException(e); - } - } - - /** - * Escapes the string value so it can be safely included in URI path segments. For details on - * escaping URIs, see RFC 3986 - section - * 2.4. - * - *

- * When encoding a String, the following rules apply: - *

    - *
  • The alphanumeric characters "a" through "z", "A" through "Z" and "0" through "9" remain the - * same. - *
  • The unreserved characters ".", "-", "~", and "_" remain the same. - *
  • The general delimiters "@" and ":" remain the same. - *
  • The subdelimiters "!", "$", "&", "'", "(", ")", "*", ",", ";", and "=" remain the same. - *
  • The space character " " is converted into %20. - *
  • All other characters are converted into one or more bytes using UTF-8 encoding and each - * byte is then represented by the 3-character string "%XY", where "XY" is the two-digit, - * uppercase, hexadecimal representation of the byte value. - *
- *

- * - *

- * Note: Unlike other escapers, URI escapers produce uppercase hexadecimal sequences. From - * RFC 3986:
- * "URI producers and normalizers should use uppercase hexadecimal digits for all - * percent-encodings." - *

- */ - public static String escapeUriPath(String value) { - return URI_PATH_ESCAPER.escape(value); - } - - /** - * Escapes a URI path but retains all reserved characters, including all general delimiters. - * That is the same as {@link #escapeUriPath(String)} except that it keeps '?', '+', and '/' - * unescaped. - */ - public static String escapeUriPathWithoutReserved(String value) { - return URI_RESERVED_ESCAPER.escape(value); - } - - /** - * Escapes the string value so it can be safely included in URI user info part. For details on - * escaping URIs, see RFC 3986 - section - * 2.4. - * - *

- * When encoding a String, the following rules apply: - *

    - *
  • The alphanumeric characters "a" through "z", "A" through "Z" and "0" through "9" remain the - * same. - *
  • The unreserved characters ".", "-", "~", and "_" remain the same. - *
  • The general delimiter ":" remains the same. - *
  • The subdelimiters "!", "$", "&", "'", "(", ")", "*", ",", ";", and "=" remain the same. - *
  • The space character " " is converted into %20. - *
  • All other characters are converted into one or more bytes using UTF-8 encoding and each - * byte is then represented by the 3-character string "%XY", where "XY" is the two-digit, - * uppercase, hexadecimal representation of the byte value. - *
- *

- * - *

- * Note: Unlike other escapers, URI escapers produce uppercase hexadecimal sequences. From - * RFC 3986:
- * "URI producers and normalizers should use uppercase hexadecimal digits for all - * percent-encodings." - *

- * - * @since 1.15 - */ - public static String escapeUriUserInfo(String value) { - return URI_USERINFO_ESCAPER.escape(value); - } - - /** - * Escapes the string value so it can be safely included in URI query string segments. When the - * query string consists of a sequence of name=value pairs separated by &, the names and - * values should be individually encoded. If you escape an entire query string in one pass with - * this escaper, then the "=" and "&" characters used as separators will also be escaped. - * - *

- * This escaper is also suitable for escaping fragment identifiers. - *

- * - *

- * For details on escaping URIs, see RFC - * 3986 - section 2.4. - *

- * - *

- * When encoding a String, the following rules apply: - *

    - *
  • The alphanumeric characters "a" through "z", "A" through "Z" and "0" through "9" remain the - * same. - *
  • The unreserved characters ".", "-", "~", and "_" remain the same. - *
  • The general delimiters "@" and ":" remain the same. - *
  • The path delimiters "/" and "?" remain the same. - *
  • The subdelimiters "!", "$", "'", "(", ")", "*", ",", and ";", remain the same. - *
  • The space character " " is converted into %20. - *
  • The equals sign "=" is converted into %3D. - *
  • The ampersand "&" is converted into %26. - *
  • All other characters are converted into one or more bytes using UTF-8 encoding and each - * byte is then represented by the 3-character string "%XY", where "XY" is the two-digit, - * uppercase, hexadecimal representation of the byte value. - *
- *

- * - *

- * Note: Unlike other escapers, URI escapers produce uppercase hexadecimal sequences. From - * RFC 3986:
- * "URI producers and normalizers should use uppercase hexadecimal digits for all - * percent-encodings." - *

- */ - public static String escapeUriQuery(String value) { - return URI_QUERY_STRING_ESCAPER.escape(value); - } - - private CharEscapers() { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/escape/Escaper.java b/src/autosaveworld/zlibs/com/google/api/client/util/escape/Escaper.java deleted file mode 100644 index cb43d277..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/escape/Escaper.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util.escape; - -/** - * An object that converts literal text into a format safe for inclusion in a particular context - * (such as an XML document). Typically (but not always), the inverse process of "unescaping" the - * text is performed automatically by the relevant parser. - * - *

- * For example, an XML escaper would convert the literal string {@code "Foo"} into {@code - * "Foo<Bar>"} to prevent {@code ""} from being confused with an XML tag. When the - * resulting XML document is parsed, the parser API will return this text as the original literal - * string {@code "Foo"}. - * - *

- * An {@code Escaper} instance is required to be stateless, and safe when used concurrently by - * multiple threads. - * - *

- * Several popular escapers are defined as constants in the class {@link CharEscapers}. - * - * @since 1.0 - */ -public abstract class Escaper { - - /** - * Returns the escaped form of a given literal string. - * - *

- * Note that this method may treat input characters differently depending on the specific escaper - * implementation. - *

    - *
  • {@link UnicodeEscaper} handles UTF-16 - * correctly, including surrogate character pairs. If the input is badly formed the escaper should - * throw {@link IllegalArgumentException}. - *
- * - * @param string the literal string to be escaped - * @return the escaped form of {@code string} - * @throws NullPointerException if {@code string} is null - * @throws IllegalArgumentException if {@code string} contains badly formed UTF-16 or cannot be - * escaped for any other reason - */ - public abstract String escape(String string); -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/escape/PercentEscaper.java b/src/autosaveworld/zlibs/com/google/api/client/util/escape/PercentEscaper.java deleted file mode 100644 index 96301277..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/escape/PercentEscaper.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util.escape; - -/** - * A {@code UnicodeEscaper} that escapes some set of Java characters using the URI percent encoding - * scheme. The set of safe characters (those which remain unescaped) can be specified on - * construction. - * - *

- * For details on escaping URIs for use in web pages, see RFC 3986 - section 2.4 and RFC 3986 - appendix A - * - *

- * When encoding a String, the following rules apply: - *

    - *
  • The alphanumeric characters "a" through "z", "A" through "Z" and "0" through "9" remain the - * same. - *
  • Any additionally specified safe characters remain the same. - *
  • If {@code plusForSpace} was specified, the space character " " is converted into a plus sign - * "+". - *
  • All other characters are converted into one or more bytes using UTF-8 encoding and each byte - * is then represented by the 3-character string "%XY", where "XY" is the two-digit, uppercase, - * hexadecimal representation of the byte value. - *
- * - *

- * RFC 2396 specifies the set of unreserved characters as "-", "_", ".", "!", "~", "*", "'", "(" and - * ")". It goes on to state: - * - *

- * Unreserved characters can be escaped without changing the semantics of the URI, but this - * should not be done unless the URI is being used in a context that does not allow the unescaped - * character to appear. - * - *

- * For performance reasons the only currently supported character encoding of this class is UTF-8. - * - *

- * Note: This escaper produces uppercase hexadecimal sequences. From RFC 3986:
- * "URI producers and normalizers should use uppercase hexadecimal digits for all - * percent-encodings." - * - * @since 1.0 - */ -public class PercentEscaper extends UnicodeEscaper { - /** - * A string of safe characters that mimics the behavior of {@link java.net.URLEncoder}. - */ - public static final String SAFECHARS_URLENCODER = "-_.*"; - - /** - * A string of characters that do not need to be encoded when used in URI path segments, as - * specified in RFC 3986. Note that some of these characters do need to be escaped when used in - * other parts of the URI. - */ - public static final String SAFEPATHCHARS_URLENCODER = "-_.!~*'()@:$&,;="; - - /** - * Contains the save characters plus all reserved characters. This happens to be the safe path - * characters plus those characters which are reserved for URI segments, namely '+', '/', and - * '?'. - */ - public static final String SAFE_PLUS_RESERVED_CHARS_URLENCODER = SAFEPATHCHARS_URLENCODER + "+/?"; - - /** - * A string of characters that do not need to be encoded when used in URI user info part, as - * specified in RFC 3986. Note that some of these characters do need to be escaped when used in - * other parts of the URI. - * - * @since 1.15 - */ - public static final String SAFEUSERINFOCHARS_URLENCODER = "-_.!~*'():$&,;="; - - /** - * A string of characters that do not need to be encoded when used in URI query strings, as - * specified in RFC 3986. Note that some of these characters do need to be escaped when used in - * other parts of the URI. - */ - public static final String SAFEQUERYSTRINGCHARS_URLENCODER = "-_.!~*'()@:$,;/?:"; - - // In some uri escapers spaces are escaped to '+' - private static final char[] URI_ESCAPED_SPACE = {'+'}; - - private static final char[] UPPER_HEX_DIGITS = "0123456789ABCDEF".toCharArray(); - - /** - * If true we should convert space to the {@code +} character. - */ - private final boolean plusForSpace; - - /** - * An array of flags where for any {@code char c} if {@code safeOctets[c]} is true then {@code c} - * should remain unmodified in the output. If {@code c > safeOctets.length} then it should be - * escaped. - */ - private final boolean[] safeOctets; - - /** - * Constructs a URI escaper with the specified safe characters and optional handling of the space - * character. - * - * @param safeChars a non null string specifying additional safe characters for this escaper (the - * ranges 0..9, a..z and A..Z are always safe and should not be specified here) - * @param plusForSpace true if ASCII space should be escaped to {@code +} rather than {@code %20} - * @throws IllegalArgumentException if any of the parameters were invalid - */ - public PercentEscaper(String safeChars, boolean plusForSpace) { - // Avoid any misunderstandings about the behavior of this escaper - if (safeChars.matches(".*[0-9A-Za-z].*")) { - throw new IllegalArgumentException( - "Alphanumeric characters are always 'safe' and should not be " + "explicitly specified"); - } - // Avoid ambiguous parameters. Safe characters are never modified so if - // space is a safe character then setting plusForSpace is meaningless. - if (plusForSpace && safeChars.contains(" ")) { - throw new IllegalArgumentException( - "plusForSpace cannot be specified when space is a 'safe' character"); - } - if (safeChars.contains("%")) { - throw new IllegalArgumentException("The '%' character cannot be specified as 'safe'"); - } - this.plusForSpace = plusForSpace; - safeOctets = createSafeOctets(safeChars); - } - - /** - * Creates a boolean[] with entries corresponding to the character values for 0-9, A-Z, a-z and - * those specified in safeChars set to true. The array is as small as is required to hold the - * given character information. - */ - private static boolean[] createSafeOctets(String safeChars) { - int maxChar = 'z'; - char[] safeCharArray = safeChars.toCharArray(); - for (char c : safeCharArray) { - maxChar = Math.max(c, maxChar); - } - boolean[] octets = new boolean[maxChar + 1]; - for (int c = '0'; c <= '9'; c++) { - octets[c] = true; - } - for (int c = 'A'; c <= 'Z'; c++) { - octets[c] = true; - } - for (int c = 'a'; c <= 'z'; c++) { - octets[c] = true; - } - for (char c : safeCharArray) { - octets[c] = true; - } - return octets; - } - - /* - * Overridden for performance. For unescaped strings this improved the performance of the uri - * escaper from ~760ns to ~400ns as measured by {@link CharEscapersBenchmark}. - */ - @Override - protected int nextEscapeIndex(CharSequence csq, int index, int end) { - for (; index < end; index++) { - char c = csq.charAt(index); - if (c >= safeOctets.length || !safeOctets[c]) { - break; - } - } - return index; - } - - /* - * Overridden for performance. For unescaped strings this improved the performance of the uri - * escaper from ~400ns to ~170ns as measured by {@link CharEscapersBenchmark}. - */ - @Override - public String escape(String s) { - int slen = s.length(); - for (int index = 0; index < slen; index++) { - char c = s.charAt(index); - if (c >= safeOctets.length || !safeOctets[c]) { - return escapeSlow(s, index); - } - } - return s; - } - - /** - * Escapes the given Unicode code point in UTF-8. - */ - @Override - protected char[] escape(int cp) { - // We should never get negative values here but if we do it will throw an - // IndexOutOfBoundsException, so at least it will get spotted. - if (cp < safeOctets.length && safeOctets[cp]) { - return null; - } else if (cp == ' ' && plusForSpace) { - return URI_ESCAPED_SPACE; - } else if (cp <= 0x7F) { - // Single byte UTF-8 characters - // Start with "%--" and fill in the blanks - char[] dest = new char[3]; - dest[0] = '%'; - dest[2] = UPPER_HEX_DIGITS[cp & 0xF]; - dest[1] = UPPER_HEX_DIGITS[cp >>> 4]; - return dest; - } else if (cp <= 0x7ff) { - // Two byte UTF-8 characters [cp >= 0x80 && cp <= 0x7ff] - // Start with "%--%--" and fill in the blanks - char[] dest = new char[6]; - dest[0] = '%'; - dest[3] = '%'; - dest[5] = UPPER_HEX_DIGITS[cp & 0xF]; - cp >>>= 4; - dest[4] = UPPER_HEX_DIGITS[0x8 | cp & 0x3]; - cp >>>= 2; - dest[2] = UPPER_HEX_DIGITS[cp & 0xF]; - cp >>>= 4; - dest[1] = UPPER_HEX_DIGITS[0xC | cp]; - return dest; - } else if (cp <= 0xffff) { - // Three byte UTF-8 characters [cp >= 0x800 && cp <= 0xffff] - // Start with "%E-%--%--" and fill in the blanks - char[] dest = new char[9]; - dest[0] = '%'; - dest[1] = 'E'; - dest[3] = '%'; - dest[6] = '%'; - dest[8] = UPPER_HEX_DIGITS[cp & 0xF]; - cp >>>= 4; - dest[7] = UPPER_HEX_DIGITS[0x8 | cp & 0x3]; - cp >>>= 2; - dest[5] = UPPER_HEX_DIGITS[cp & 0xF]; - cp >>>= 4; - dest[4] = UPPER_HEX_DIGITS[0x8 | cp & 0x3]; - cp >>>= 2; - dest[2] = UPPER_HEX_DIGITS[cp]; - return dest; - } else if (cp <= 0x10ffff) { - char[] dest = new char[12]; - // Four byte UTF-8 characters [cp >= 0xffff && cp <= 0x10ffff] - // Start with "%F-%--%--%--" and fill in the blanks - dest[0] = '%'; - dest[1] = 'F'; - dest[3] = '%'; - dest[6] = '%'; - dest[9] = '%'; - dest[11] = UPPER_HEX_DIGITS[cp & 0xF]; - cp >>>= 4; - dest[10] = UPPER_HEX_DIGITS[0x8 | cp & 0x3]; - cp >>>= 2; - dest[8] = UPPER_HEX_DIGITS[cp & 0xF]; - cp >>>= 4; - dest[7] = UPPER_HEX_DIGITS[0x8 | cp & 0x3]; - cp >>>= 2; - dest[5] = UPPER_HEX_DIGITS[cp & 0xF]; - cp >>>= 4; - dest[4] = UPPER_HEX_DIGITS[0x8 | cp & 0x3]; - cp >>>= 2; - dest[2] = UPPER_HEX_DIGITS[cp & 0x7]; - return dest; - } else { - // If this ever happens it is due to bug in UnicodeEscaper, not bad input. - throw new IllegalArgumentException("Invalid unicode character value " + cp); - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/escape/Platform.java b/src/autosaveworld/zlibs/com/google/api/client/util/escape/Platform.java deleted file mode 100644 index 627490d6..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/escape/Platform.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util.escape; - -/** - * Methods factored out so that they can be emulated differently in GWT. - */ -final class Platform { - private Platform() { - } - - /** Returns a thread-local 1024-char array. */ - // DEST_TL.get() is not null because initialValue() below returns a non-null. - static char[] charBufferFromThreadLocal() { - return DEST_TL.get(); - } - - /** - * A thread-local destination buffer to keep us from creating new buffers. The starting size is - * 1024 characters. If we grow past this we don't put it back in the threadlocal, we just keep - * going and grow as needed. - */ - private static final ThreadLocal DEST_TL = new ThreadLocal() { - @Override - protected char[] initialValue() { - return new char[1024]; - } - }; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/escape/UnicodeEscaper.java b/src/autosaveworld/zlibs/com/google/api/client/util/escape/UnicodeEscaper.java deleted file mode 100644 index a2b5b089..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/escape/UnicodeEscaper.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util.escape; - -/** - * An {@link Escaper} that converts literal text into a format safe for inclusion in a particular - * context (such as an XML document). Typically (but not always), the inverse process of - * "unescaping" the text is performed automatically by the relevant parser. - * - *

- * For example, an XML escaper would convert the literal string {@code "Foo"} into {@code - * "Foo<Bar>"} to prevent {@code ""} from being confused with an XML tag. When the - * resulting XML document is parsed, the parser API will return this text as the original literal - * string {@code "Foo"}. - * - *

- * As there are important reasons, including potential security issues, to handle Unicode correctly - * if you are considering implementing a new escaper you should favor using UnicodeEscaper wherever - * possible. - * - *

- * A {@code UnicodeEscaper} instance is required to be stateless, and safe when used concurrently by - * multiple threads. - * - *

- * Several popular escapers are defined as constants in the class {@link CharEscapers}. To create - * your own escapers extend this class and implement the {@link #escape(int)} method. - * - * @since 1.0 - */ -public abstract class UnicodeEscaper extends Escaper { - /** The amount of padding (chars) to use when growing the escape buffer. */ - private static final int DEST_PAD = 32; - - /** - * Returns the escaped form of the given Unicode code point, or {@code null} if this code point - * does not need to be escaped. When called as part of an escaping operation, the given code point - * is guaranteed to be in the range {@code 0 <= cp <= Character#MAX_CODE_POINT}. - * - *

- * If an empty array is returned, this effectively strips the input character from the resulting - * text. - * - *

- * If the character does not need to be escaped, this method should return {@code null}, rather - * than an array containing the character representation of the code point. This enables the - * escaping algorithm to perform more efficiently. - * - *

- * If the implementation of this method cannot correctly handle a particular code point then it - * should either throw an appropriate runtime exception or return a suitable replacement - * character. It must never silently discard invalid input as this may constitute a security risk. - * - * @param cp the Unicode code point to escape if necessary - * @return the replacement characters, or {@code null} if no escaping was needed - */ - protected abstract char[] escape(int cp); - - /** - * Scans a sub-sequence of characters from a given {@link CharSequence}, returning the index of - * the next character that requires escaping. - * - *

- * Note: When implementing an escaper, it is a good idea to override this method for - * efficiency. The base class implementation determines successive Unicode code points and invokes - * {@link #escape(int)} for each of them. If the semantics of your escaper are such that code - * points in the supplementary range are either all escaped or all unescaped, this method can be - * implemented more efficiently using {@link CharSequence#charAt(int)}. - * - *

- * Note however that if your escaper does not escape characters in the supplementary range, you - * should either continue to validate the correctness of any surrogate characters encountered or - * provide a clear warning to users that your escaper does not validate its input. - * - *

- * See {@link PercentEscaper} for an example. - * - * @param csq a sequence of characters - * @param start the index of the first character to be scanned - * @param end the index immediately after the last character to be scanned - * @throws IllegalArgumentException if the scanned sub-sequence of {@code csq} contains invalid - * surrogate pairs - */ - protected abstract int nextEscapeIndex(CharSequence csq, int start, int end); - - /** - * Returns the escaped form of a given literal string. - * - *

- * If you are escaping input in arbitrary successive chunks, then it is not generally safe to use - * this method. If an input string ends with an unmatched high surrogate character, then this - * method will throw {@link IllegalArgumentException}. You should ensure your input is valid UTF-16 before calling this method. - * - * @param string the literal string to be escaped - * @return the escaped form of {@code string} - * @throws NullPointerException if {@code string} is null - * @throws IllegalArgumentException if invalid surrogate characters are encountered - */ - @Override - public abstract String escape(String string); - - /** - * Returns the escaped form of a given literal string, starting at the given index. This method is - * called by the {@link #escape(String)} method when it discovers that escaping is required. It is - * protected to allow subclasses to override the fastpath escaping function to inline their - * escaping test. - * - *

- * This method is not reentrant and may only be invoked by the top level {@link #escape(String)} - * method. - * - * @param s the literal string to be escaped - * @param index the index to start escaping from - * @return the escaped form of {@code string} - * @throws NullPointerException if {@code string} is null - * @throws IllegalArgumentException if invalid surrogate characters are encountered - */ - protected final String escapeSlow(String s, int index) { - int end = s.length(); - - // Get a destination buffer and setup some loop variables. - char[] dest = Platform.charBufferFromThreadLocal(); - int destIndex = 0; - int unescapedChunkStart = 0; - - while (index < end) { - int cp = codePointAt(s, index, end); - if (cp < 0) { - throw new IllegalArgumentException("Trailing high surrogate at end of input"); - } - // It is possible for this to return null because nextEscapeIndex() may - // (for performance reasons) yield some false positives but it must never - // give false negatives. - char[] escaped = escape(cp); - int nextIndex = index + (Character.isSupplementaryCodePoint(cp) ? 2 : 1); - if (escaped != null) { - int charsSkipped = index - unescapedChunkStart; - - // This is the size needed to add the replacement, not the full - // size needed by the string. We only regrow when we absolutely must. - int sizeNeeded = destIndex + charsSkipped + escaped.length; - if (dest.length < sizeNeeded) { - int destLength = sizeNeeded + end - index + DEST_PAD; - dest = growBuffer(dest, destIndex, destLength); - } - // If we have skipped any characters, we need to copy them now. - if (charsSkipped > 0) { - s.getChars(unescapedChunkStart, index, dest, destIndex); - destIndex += charsSkipped; - } - if (escaped.length > 0) { - System.arraycopy(escaped, 0, dest, destIndex, escaped.length); - destIndex += escaped.length; - } - // If we dealt with an escaped character, reset the unescaped range. - unescapedChunkStart = nextIndex; - } - index = nextEscapeIndex(s, nextIndex, end); - } - - // Process trailing unescaped characters - no need to account for escaped - // length or padding the allocation. - int charsSkipped = end - unescapedChunkStart; - if (charsSkipped > 0) { - int endIndex = destIndex + charsSkipped; - if (dest.length < endIndex) { - dest = growBuffer(dest, destIndex, endIndex); - } - s.getChars(unescapedChunkStart, end, dest, destIndex); - destIndex = endIndex; - } - return new String(dest, 0, destIndex); - } - - /** - * Returns the Unicode code point of the character at the given index. - * - *

- * Unlike {@link Character#codePointAt(CharSequence, int)} or {@link String#codePointAt(int)} this - * method will never fail silently when encountering an invalid surrogate pair. - * - *

- * The behaviour of this method is as follows: - *

    - *
  1. If {@code index >= end}, {@link IndexOutOfBoundsException} is thrown. - *
  2. If the character at the specified index is not a surrogate, it is returned. - *
  3. If the first character was a high surrogate value, then an attempt is made to read the next - * character. - *
      - *
    1. If the end of the sequence was reached, the negated value of the trailing high surrogate - * is returned. - *
    2. If the next character was a valid low surrogate, the code point value of the high/low - * surrogate pair is returned. - *
    3. If the next character was not a low surrogate value, then {@link IllegalArgumentException} - * is thrown. - *
    - *
  4. If the first character was a low surrogate value, {@link IllegalArgumentException} is - * thrown. - *
- * - * @param seq the sequence of characters from which to decode the code point - * @param index the index of the first character to decode - * @param end the index beyond the last valid character to decode - * @return the Unicode code point for the given index or the negated value of the trailing high - * surrogate character at the end of the sequence - */ - protected static int codePointAt(CharSequence seq, int index, int end) { - if (index < end) { - char c1 = seq.charAt(index++); - if (c1 < Character.MIN_HIGH_SURROGATE || c1 > Character.MAX_LOW_SURROGATE) { - // Fast path (first test is probably all we need to do) - return c1; - } else if (c1 <= Character.MAX_HIGH_SURROGATE) { - // If the high surrogate was the last character, return its inverse - if (index == end) { - return -c1; - } - // Otherwise look for the low surrogate following it - char c2 = seq.charAt(index); - if (Character.isLowSurrogate(c2)) { - return Character.toCodePoint(c1, c2); - } - throw new IllegalArgumentException( - "Expected low surrogate but got char '" + c2 + "' with value " + (int) c2 + " at index " - + index); - } else { - throw new IllegalArgumentException( - "Unexpected low surrogate character '" + c1 + "' with value " + (int) c1 + " at index " - + (index - 1)); - } - } - throw new IndexOutOfBoundsException("Index exceeds specified range"); - } - - /** - * Helper method to grow the character buffer as needed, this only happens once in a while so it's - * ok if it's in a method call. If the index passed in is 0 then no copying will be done. - */ - private static char[] growBuffer(char[] dest, int index, int size) { - char[] copy = new char[size]; - if (index > 0) { - System.arraycopy(dest, 0, copy, 0, index); - } - return copy; - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/store/AbstractDataStore.java b/src/autosaveworld/zlibs/com/google/api/client/util/store/AbstractDataStore.java deleted file mode 100644 index 44c98f65..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/store/AbstractDataStore.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util.store; - -import java.io.IOException; -import java.io.Serializable; -import java.util.Collection; -import java.util.Set; - -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * Abstract data store implementation. - * - * @param serializable type of the mapped value - * - * @author Yaniv Inbar - * @since 1.16 - */ -public abstract class AbstractDataStore implements DataStore { - - /** Data store factory. */ - private final DataStoreFactory dataStoreFactory; - - /** Data store ID. */ - private final String id; - - /** - * @param dataStoreFactory data store factory - * @param id data store ID - */ - protected AbstractDataStore(DataStoreFactory dataStoreFactory, String id) { - this.dataStoreFactory = Preconditions.checkNotNull(dataStoreFactory); - this.id = Preconditions.checkNotNull(id); - } - - /** - * {@inheritDoc} - * - *

- * Overriding is only supported for the purpose of calling the super implementation and changing - * the return type, but nothing else. - *

- */ - public DataStoreFactory getDataStoreFactory() { - return dataStoreFactory; - } - - public final String getId() { - return id; - } - - /** - * {@inheritDoc} - * - *

- * Default implementation is to call {@link #get(String)} and check if it is {@code null}. - *

- */ - public boolean containsKey(String key) throws IOException { - return get(key) != null; - } - - /** - * {@inheritDoc} - * - *

- * Default implementation is to call {@link Collection#contains(Object)} on {@link #values()}. - *

- */ - public boolean containsValue(V value) throws IOException { - return values().contains(value); - } - - /** - * {@inheritDoc} - * - *

- * Default implementation is to check if {@link #size()} is {@code 0}. - *

- */ - public boolean isEmpty() throws IOException { - return size() == 0; - } - - /** - * {@inheritDoc} - * - *

- * Default implementation is to call {@link Set#size()} on {@link #keySet()}. - *

- */ - public int size() throws IOException { - return keySet().size(); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/store/AbstractDataStoreFactory.java b/src/autosaveworld/zlibs/com/google/api/client/util/store/AbstractDataStoreFactory.java deleted file mode 100644 index 0977bb97..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/store/AbstractDataStoreFactory.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util.store; - -import java.io.IOException; -import java.io.Serializable; -import java.util.Map; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; -import java.util.regex.Pattern; - -import autosaveworld.zlibs.com.google.api.client.util.Maps; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * Abstract data store factory implementation. - * - * @author Yaniv Inbar - * @since 1.16 - */ -public abstract class AbstractDataStoreFactory implements DataStoreFactory { - - /** Lock on access to the data store map. */ - private final Lock lock = new ReentrantLock(); - - /** Map of data store ID to data store. */ - private final Map> dataStoreMap = Maps.newHashMap(); - - /** - * Pattern to control possible values for the {@code id} parameter of - * {@link #getDataStore(String)}. - */ - private static final Pattern ID_PATTERN = Pattern.compile("\\w{1,30}"); - - public final DataStore getDataStore(String id) throws IOException { - Preconditions.checkArgument( - ID_PATTERN.matcher(id).matches(), "%s does not match pattern %s", id, ID_PATTERN); - lock.lock(); - try { - @SuppressWarnings("unchecked") - DataStore dataStore = (DataStore) dataStoreMap.get(id); - if (dataStore == null) { - dataStore = createDataStore(id); - dataStoreMap.put(id, dataStore); - } - return dataStore; - } finally { - lock.unlock(); - } - } - - /** - * Returns a new instance of a type-specific data store based on the given unique ID. - * - *

- * The {@link DataStore#getId()} must match the {@code id} parameter from this method. - *

- * - * @param id unique ID to refer to typed data store - * @param serializable type of the mapped value - */ - protected abstract DataStore createDataStore(String id) - throws IOException; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/store/AbstractMemoryDataStore.java b/src/autosaveworld/zlibs/com/google/api/client/util/store/AbstractMemoryDataStore.java deleted file mode 100644 index 9da9a8d6..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/store/AbstractMemoryDataStore.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util.store; - -import java.io.IOException; -import java.io.Serializable; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Set; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import autosaveworld.zlibs.com.google.api.client.util.IOUtils; -import autosaveworld.zlibs.com.google.api.client.util.Lists; -import autosaveworld.zlibs.com.google.api.client.util.Maps; -import autosaveworld.zlibs.com.google.api.client.util.Preconditions; - -/** - * Abstract, thread-safe, in-memory implementation of a data store factory. - * - * @param serializable type of the mapped value - * - * @author Yaniv Inbar - */ -class AbstractMemoryDataStore extends AbstractDataStore { - - /** Lock on access to the store. */ - private final Lock lock = new ReentrantLock(); - - /** Data store map from the key to the value. */ - HashMap keyValueMap = Maps.newHashMap(); - - /** - * @param dataStoreFactory data store factory - * @param id data store ID - */ - protected AbstractMemoryDataStore(DataStoreFactory dataStoreFactory, String id) { - super(dataStoreFactory, id); - } - - public final Set keySet() throws IOException { - lock.lock(); - try { - return Collections.unmodifiableSet(keyValueMap.keySet()); - } finally { - lock.unlock(); - } - } - - public final Collection values() throws IOException { - lock.lock(); - try { - List result = Lists.newArrayList(); - for (byte[] bytes : keyValueMap.values()) { - result.add(IOUtils.deserialize(bytes)); - } - return Collections.unmodifiableList(result); - } finally { - lock.unlock(); - } - } - - public final V get(String key) throws IOException { - if (key == null) { - return null; - } - lock.lock(); - try { - return IOUtils.deserialize(keyValueMap.get(key)); - } finally { - lock.unlock(); - } - } - - public final DataStore set(String key, V value) throws IOException { - Preconditions.checkNotNull(key); - Preconditions.checkNotNull(value); - lock.lock(); - try { - keyValueMap.put(key, IOUtils.serialize(value)); - save(); - } finally { - lock.unlock(); - } - return this; - } - - public DataStore delete(String key) throws IOException { - if (key == null) { - return this; - } - lock.lock(); - try { - keyValueMap.remove(key); - save(); - } finally { - lock.unlock(); - } - return this; - } - - public final DataStore clear() throws IOException { - lock.lock(); - try { - keyValueMap.clear(); - save(); - } finally { - lock.unlock(); - } - return this; - } - - @Override - public boolean containsKey(String key) throws IOException { - if (key == null) { - return false; - } - lock.lock(); - try { - return keyValueMap.containsKey(key); - } finally { - lock.unlock(); - } - } - - @Override - public boolean containsValue(V value) throws IOException { - if (value == null) { - return false; - } - lock.lock(); - try { - byte[] serialized = IOUtils.serialize(value); - for (byte[] bytes : keyValueMap.values()) { - if (Arrays.equals(serialized, bytes)) { - return true; - } - } - return false; - } finally { - lock.unlock(); - } - } - - @Override - public boolean isEmpty() throws IOException { - lock.lock(); - try { - return keyValueMap.isEmpty(); - } finally { - lock.unlock(); - } - } - - @Override - public int size() throws IOException { - lock.lock(); - try { - return keyValueMap.size(); - } finally { - lock.unlock(); - } - } - - /** - * Persist the key-value map into storage at the end of {@link #set}, {@link #delete(String)}, and - * {@link #clear()}. - */ - void save() throws IOException { - } - - @Override - public String toString() { - return DataStoreUtils.toString(this); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/store/DataStore.java b/src/autosaveworld/zlibs/com/google/api/client/util/store/DataStore.java deleted file mode 100644 index 4840a829..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/store/DataStore.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util.store; - - -import java.io.IOException; -import java.io.Serializable; -import java.util.Collection; -import java.util.Set; - -/** - * Stores and manages serializable data of a specific type, where the key is a string and the value - * is a {@link Serializable} object. - * - *

- * {@code null} keys or values are not allowed. Implementation should be thread-safe. - *

- * - * @param serializable type of the mapped value - * - * @author Yaniv Inbar - * @since 1.16 - */ -public interface DataStore { - - /** Returns the data store factory. */ - DataStoreFactory getDataStoreFactory(); - - /** Returns the data store ID. */ - String getId(); - - /** Returns the number of stored keys. */ - int size() throws IOException; - - /** Returns whether there are any stored keys. */ - boolean isEmpty() throws IOException; - - /** Returns whether the store contains the given key. */ - boolean containsKey(String key) throws IOException; - - /** Returns whether the store contains the given value. */ - boolean containsValue(V value) throws IOException; - - /** - * Returns the unmodifiable set of all stored keys. - * - *

- * Order of the keys is not specified. - *

- */ - Set keySet() throws IOException; - - /** Returns the unmodifiable collection of all stored values. */ - Collection values() throws IOException; - - /** - * Returns the stored value for the given key or {@code null} if not found. - * - * @param key key or {@code null} for {@code null} result - */ - V get(String key) throws IOException; - - /** - * Stores the given value for the given key (replacing any existing value). - * - * @param key key - * @param value value object - */ - DataStore set(String key, V value) throws IOException; - - /** Deletes all of the stored keys and values. */ - DataStore clear() throws IOException; - - /** - * Deletes the stored key and value based on the given key, or ignored if the key doesn't already - * exist. - * - * @param key key or {@code null} to ignore - */ - DataStore delete(String key) throws IOException; - - // TODO(yanivi): implement entrySet()? -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/store/DataStoreFactory.java b/src/autosaveworld/zlibs/com/google/api/client/util/store/DataStoreFactory.java deleted file mode 100644 index 1f1d52ff..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/store/DataStoreFactory.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util.store; - - -import java.io.IOException; -import java.io.Serializable; - -/** - * Factory for a store that manages serializable data, where the key is a string and the value is a - * {@link Serializable} object. - * - *

- * Users should keep a single globally shared instance of the data store factory. Otherwise, some - * implementations may not share the internal copies of the data, and you'll end up with multiple - * data stores by the same IDs, each living in a separate implementation. Some implementations may - * also have some overhead, or may have caching implemented, and so multiple instances may defeat - * that. Finally, have multiple instances may defeat the thread-safety guarantee for some - * implementations. - *

- * - *

- * Implementation should store the data in a persistent storage such as a database. Implementation - * should be thread-safe. Read the JavaDoc of the implementation for those details. - *

- * - * @see MemoryDataStoreFactory - * @see FileDataStoreFactory - * @author Yaniv Inbar - * @since 1.16 - */ -public interface DataStoreFactory { - - /** - * Returns a type-specific data store based on the given unique ID. - * - *

- * If a data store by that ID does not already exist, it should be created now, stored for later - * access, and returned. Otherwise, if there is already a data store by that ID, it should be - * returned. The {@link DataStore#getId()} must match the {@code id} parameter from this method. - *

- * - *

- * The ID must be at least 1 and at most 30 characters long, and must contain only alphanumeric or - * underscore characters. - *

- * - * @param id unique ID to refer to typed data store - * @param serializable type of the mapped value - */ - DataStore getDataStore(String id) throws IOException; -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/store/DataStoreUtils.java b/src/autosaveworld/zlibs/com/google/api/client/util/store/DataStoreUtils.java deleted file mode 100644 index 028ec734..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/store/DataStoreUtils.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util.store; - - -import java.io.IOException; - -/** - * Utilities for data stores. - * - * @author Yaniv Inbar - * @since 1.16 - */ -public final class DataStoreUtils { - - /** - * Returns a debug string for the given data store to be used as an implementation of - * {@link Object#toString()}. - * - *

- * Implementation iterates over {@link DataStore#keySet()}, calling {@link DataStore#get(String)} - * on each key. - *

- * - * @param dataStore data store - * @return debug string - */ - public static String toString(DataStore dataStore) { - try { - StringBuilder sb = new StringBuilder(); - sb.append('{'); - boolean first = true; - for (String key : dataStore.keySet()) { - if (first) { - first = false; - } else { - sb.append(", "); - } - sb.append(key).append('=').append(dataStore.get(key)); - } - return sb.append('}').toString(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - private DataStoreUtils() { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/store/FileDataStoreFactory.java b/src/autosaveworld/zlibs/com/google/api/client/util/store/FileDataStoreFactory.java deleted file mode 100644 index 8058d783..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/store/FileDataStoreFactory.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util.store; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.Serializable; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.logging.Logger; - -import autosaveworld.zlibs.com.google.api.client.util.IOUtils; -import autosaveworld.zlibs.com.google.api.client.util.Maps; -import autosaveworld.zlibs.com.google.api.client.util.Throwables; - -/** - * Thread-safe file implementation of a credential store. - * - *

- * For security purposes, the file's permissions are set to be accessible only by the file's owner. - * Note that Java 1.5 does not support manipulating file permissions, and must be done manually or - * using the JNI. - *

- * - * @since 1.16 - * @author Yaniv Inbar - */ -public class FileDataStoreFactory extends AbstractDataStoreFactory { - - private static final Logger LOGGER = Logger.getLogger(FileDataStoreFactory.class.getName()); - - /** Directory to store data. */ - private final File dataDirectory; - - /** - * @param dataDirectory data directory - */ - public FileDataStoreFactory(File dataDirectory) throws IOException { - dataDirectory = dataDirectory.getCanonicalFile(); - this.dataDirectory = dataDirectory; - // error if it is a symbolic link - if (IOUtils.isSymbolicLink(dataDirectory)) { - throw new IOException("unable to use a symbolic link: " + dataDirectory); - } - // create parent directory (if necessary) - if (!dataDirectory.exists() && !dataDirectory.mkdirs()) { - throw new IOException("unable to create directory: " + dataDirectory); - } - setPermissionsToOwnerOnly(dataDirectory); - } - - /** Returns the data directory. */ - public final File getDataDirectory() { - return dataDirectory; - } - - @Override - protected DataStore createDataStore(String id) throws IOException { - return new FileDataStore(this, dataDirectory, id); - } - - /** - * File data store that inherits from the abstract memory data store because the key-value pairs - * are stored in a memory cache, and saved in the file (see {@link #save()} when changing values. - * - * @param serializable type of the mapped value - */ - static class FileDataStore extends AbstractMemoryDataStore { - - /** File to store data. */ - private final File dataFile; - - FileDataStore(FileDataStoreFactory dataStore, File dataDirectory, String id) - throws IOException { - super(dataStore, id); - this.dataFile = new File(dataDirectory, id); - // error if it is a symbolic link - if (IOUtils.isSymbolicLink(dataFile)) { - throw new IOException("unable to use a symbolic link: " + dataFile); - } - // create new file (if necessary) - if (dataFile.createNewFile()) { - keyValueMap = Maps.newHashMap(); - // save the credentials to create a new file - save(); - } else { - // load credentials from existing file - keyValueMap = IOUtils.deserialize(new FileInputStream(dataFile)); - } - } - - @Override - void save() throws IOException { - IOUtils.serialize(keyValueMap, new FileOutputStream(dataFile)); - } - - @Override - public FileDataStoreFactory getDataStoreFactory() { - return (FileDataStoreFactory) super.getDataStoreFactory(); - } - } - - /** - * Attempts to set the given file's permissions such that it can only be read, written, and - * executed by the file's owner. - * - * @param file the file's permissions to modify - * @throws IOException - */ - static void setPermissionsToOwnerOnly(File file) throws IOException { - // Disable access by other users if O/S allows it and set file permissions to readable and - // writable by user. Use reflection since JDK 1.5 will not have these methods - try { - Method setReadable = File.class.getMethod("setReadable", boolean.class, boolean.class); - Method setWritable = File.class.getMethod("setWritable", boolean.class, boolean.class); - Method setExecutable = File.class.getMethod("setExecutable", boolean.class, boolean.class); - if (!(Boolean) setReadable.invoke(file, false, false) - || !(Boolean) setWritable.invoke(file, false, false) - || !(Boolean) setExecutable.invoke(file, false, false)) { - LOGGER.warning("unable to change permissions for everybody: " + file); - } - if (!(Boolean) setReadable.invoke(file, true, true) - || !(Boolean) setWritable.invoke(file, true, true) - || !(Boolean) setExecutable.invoke(file, true, true)) { - LOGGER.warning("unable to change permissions for owner: " + file); - } - } catch (InvocationTargetException exception) { - Throwable cause = exception.getCause(); - Throwables.propagateIfPossible(cause, IOException.class); - // shouldn't reach this point, but just in case... - throw new RuntimeException(cause); - } catch (NoSuchMethodException exception) { - LOGGER.warning("Unable to set permissions for " + file - + ", likely because you are running a version of Java prior to 1.6"); - } catch (SecurityException exception) { - // ignored - } catch (IllegalAccessException exception) { - // ignored - } catch (IllegalArgumentException exception) { - // ignored - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/client/util/store/MemoryDataStoreFactory.java b/src/autosaveworld/zlibs/com/google/api/client/util/store/MemoryDataStoreFactory.java deleted file mode 100644 index e92ce981..00000000 --- a/src/autosaveworld/zlibs/com/google/api/client/util/store/MemoryDataStoreFactory.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ - -package autosaveworld.zlibs.com.google.api.client.util.store; - - - -import java.io.IOException; -import java.io.Serializable; - -/** - * Thread-safe in-memory implementation of a data store factory. - * - *

- * For convenience, a default global instance is provided in {@link #getDefaultInstance()}. - *

- * - * @since 1.16 - * @author Yaniv Inbar - */ -public class MemoryDataStoreFactory extends AbstractDataStoreFactory { - - @Override - protected DataStore createDataStore(String id) throws IOException { - return new MemoryDataStore(this, id); - } - - /** Returns a global thread-safe instance. */ - public static MemoryDataStoreFactory getDefaultInstance() { - return InstanceHolder.INSTANCE; - } - - /** Holder for the result of {@link #getDefaultInstance()}. */ - static class InstanceHolder { - static final MemoryDataStoreFactory INSTANCE = new MemoryDataStoreFactory(); - } - - static class MemoryDataStore extends AbstractMemoryDataStore { - - MemoryDataStore(MemoryDataStoreFactory dataStore, String id) { - super(dataStore, id); - } - - @Override - public MemoryDataStoreFactory getDataStoreFactory() { - return (MemoryDataStoreFactory) super.getDataStoreFactory(); - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/services/drive/Drive.java b/src/autosaveworld/zlibs/com/google/api/services/drive/Drive.java deleted file mode 100644 index ef7a6dea..00000000 --- a/src/autosaveworld/zlibs/com/google/api/services/drive/Drive.java +++ /dev/null @@ -1,699 +0,0 @@ -/* - * Copyright 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -/* - * This code was generated by https://github.com/google/apis-client-generator/ - * (build: 2016-10-17 16:43:55 UTC) - * on 2016-11-17 at 13:55:42 UTC - * Modify at your own risk. - */ - -package autosaveworld.zlibs.com.google.api.services.drive; - -/** - * Service definition for Drive (v2). - * - *

- * Manages files in Drive including uploading, downloading, searching, detecting changes, and updating sharing permissions. - *

- * - *

- * For more information about this service, see the - * API Documentation - *

- * - *

- * This service uses {@link DriveRequestInitializer} to initialize global parameters via its - * {@link Builder}. - *

- * - * @since 1.3 - * @author Google, Inc. - */ -@SuppressWarnings("javadoc") -public class Drive extends autosaveworld.zlibs.com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient { - - /** - * The default encoded root URL of the service. This is determined when the library is generated - * and normally should not be changed. - * - * @since 1.7 - */ - public static final String DEFAULT_ROOT_URL = "https://www.googleapis.com/"; - - /** - * The default encoded service path of the service. This is determined when the library is - * generated and normally should not be changed. - * - * @since 1.7 - */ - public static final String DEFAULT_SERVICE_PATH = "drive/v2/"; - - /** - * The default encoded base URL of the service. This is determined when the library is generated - * and normally should not be changed. - */ - public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH; - - /** - * Constructor. - * - *

- * Use {@link Builder} if you need to specify any of the optional parameters. - *

- * - * @param transport HTTP transport, which should normally be: - *
    - *
  • Google App Engine: - * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}
  • - *
  • Android: {@code newCompatibleTransport} from - * {@code com.google.api.client.extensions.android.http.AndroidHttp}
  • - *
  • Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} - *
  • - *
- * @param jsonFactory JSON factory, which may be: - *
    - *
  • Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}
  • - *
  • Google GSON: {@code com.google.api.client.json.gson.GsonFactory}
  • - *
  • Android Honeycomb or higher: - * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}
  • - *
- * @param httpRequestInitializer HTTP request initializer or {@code null} for none - * @since 1.7 - */ - public Drive(autosaveworld.zlibs.com.google.api.client.http.HttpTransport transport, autosaveworld.zlibs.com.google.api.client.json.JsonFactory jsonFactory, - autosaveworld.zlibs.com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { - this(new Builder(transport, jsonFactory, httpRequestInitializer)); - } - - /** - * @param builder builder - */ - Drive(Builder builder) { - super(builder); - } - - @Override - protected void initialize(autosaveworld.zlibs.com.google.api.client.googleapis.services.AbstractGoogleClientRequest httpClientRequest) throws java.io.IOException { - super.initialize(httpClientRequest); - } - - /** - * An accessor for creating requests from the Files collection. - * - *

The typical use is:

- *
-   *   {@code Drive drive = new Drive(...);}
-   *   {@code Drive.Files.List request = drive.files().list(parameters ...)}
-   * 
- * - * @return the resource collection - */ - public Files files() { - return new Files(); - } - - /** - * The "files" collection of methods. - */ - public class Files { - - /** - * Permanently deletes a file by ID. Skips the trash. The currently authenticated user must own the - * file. - * - * Create a request for the method "files.delete". - * - * This request holds the parameters needed by the drive server. After setting any optional - * parameters, call the {@link Delete#execute()} method to invoke the remote operation. - * - * @param fileId The ID of the file to delete. - * @return the request - */ - public Delete delete(java.lang.String fileId) throws java.io.IOException { - Delete result = new Delete(fileId); - initialize(result); - return result; - } - - public class Delete extends DriveRequest { - - private static final String REST_PATH = "files/{fileId}"; - - /** - * Permanently deletes a file by ID. Skips the trash. The currently authenticated user must own - * the file. - * - * Create a request for the method "files.delete". - * - * This request holds the parameters needed by the the drive server. After setting any optional - * parameters, call the {@link Delete#execute()} method to invoke the remote operation.

{@link - * Delete#initialize(autosaveworld.zlibs.com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must - * be called to initialize this instance immediately after invoking the constructor.

- * - * @param fileId The ID of the file to delete. - * @since 1.13 - */ - protected Delete(java.lang.String fileId) { - super(Drive.this, "DELETE", REST_PATH, null, Void.class); - this.fileId = autosaveworld.zlibs.com.google.api.client.util.Preconditions.checkNotNull(fileId, "Required parameter fileId must be specified."); - } - - @Override - public Delete setAlt(java.lang.String alt) { - return (Delete) super.setAlt(alt); - } - - @Override - public Delete setFields(java.lang.String fields) { - return (Delete) super.setFields(fields); - } - - @Override - public Delete setKey(java.lang.String key) { - return (Delete) super.setKey(key); - } - - @Override - public Delete setOauthToken(java.lang.String oauthToken) { - return (Delete) super.setOauthToken(oauthToken); - } - - @Override - public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { - return (Delete) super.setPrettyPrint(prettyPrint); - } - - @Override - public Delete setQuotaUser(java.lang.String quotaUser) { - return (Delete) super.setQuotaUser(quotaUser); - } - - @Override - public Delete setUserIp(java.lang.String userIp) { - return (Delete) super.setUserIp(userIp); - } - - /** The ID of the file to delete. */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String fileId; - - /** The ID of the file to delete. - */ - public java.lang.String getFileId() { - return fileId; - } - - /** The ID of the file to delete. */ - public Delete setFileId(java.lang.String fileId) { - this.fileId = fileId; - return this; - } - - @Override - public Delete set(String parameterName, Object value) { - return (Delete) super.set(parameterName, value); - } - } - - /** - * Insert a new file. - * - * Create a request for the method "files.insert". - * - * This request holds the parameters needed by the drive server. After setting any optional - * parameters, call the {@link Insert#execute()} method to invoke the remote operation. - * - * @param content the {@link autosaveworld.zlibs.com.google.api.services.drive.model.File} - * @return the request - */ - public Insert insert(autosaveworld.zlibs.com.google.api.services.drive.model.File content) throws java.io.IOException { - Insert result = new Insert(content); - initialize(result); - return result; - } - - /** - * Insert a new file. - * - * Create a request for the method "files.insert". - * - * This request holds the parameters needed by the the drive server. After setting any optional - * parameters, call the {@link Insert#execute()} method to invoke the remote operation. - * - *

- * This method should be used for uploading media content. - *

- * - * - * @param content the {@link autosaveworld.zlibs.com.google.api.services.drive.model.File} media metadata or {@code null} if none - * @param mediaContent The media HTTP content or {@code null} if none. - * @return the request - * @throws java.io.IOException if the initialization of the request fails - */ - public Insert insert(autosaveworld.zlibs.com.google.api.services.drive.model.File content, autosaveworld.zlibs.com.google.api.client.http.AbstractInputStreamContent mediaContent) throws java.io.IOException { - Insert result = new Insert(content, mediaContent); - initialize(result); - return result; - } - - public class Insert extends DriveRequest { - - private static final String REST_PATH = "files"; - - /** - * Insert a new file. - * - * Create a request for the method "files.insert". - * - * This request holds the parameters needed by the the drive server. After setting any optional - * parameters, call the {@link Insert#execute()} method to invoke the remote operation.

{@link - * Insert#initialize(autosaveworld.zlibs.com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must - * be called to initialize this instance immediately after invoking the constructor.

- * - * @param content the {@link autosaveworld.zlibs.com.google.api.services.drive.model.File} - * @since 1.13 - */ - protected Insert(autosaveworld.zlibs.com.google.api.services.drive.model.File content) { - super(Drive.this, "POST", REST_PATH, content, autosaveworld.zlibs.com.google.api.services.drive.model.File.class); - } - - /** - * Insert a new file. - * - * Create a request for the method "files.insert". - * - * This request holds the parameters needed by the the drive server. After setting any optional - * parameters, call the {@link Insert#execute()} method to invoke the remote operation.

{@link - * Insert#initialize(autosaveworld.zlibs.com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must - * be called to initialize this instance immediately after invoking the constructor.

- * - *

- * This constructor should be used for uploading media content. - *

- * - * - * @param content the {@link autosaveworld.zlibs.com.google.api.services.drive.model.File} media metadata or {@code null} if none - * @param mediaContent The media HTTP content or {@code null} if none. - * @since 1.13 - */ - protected Insert(autosaveworld.zlibs.com.google.api.services.drive.model.File content, autosaveworld.zlibs.com.google.api.client.http.AbstractInputStreamContent mediaContent) { - super(Drive.this, "POST", "/upload/" + getServicePath() + REST_PATH, content, autosaveworld.zlibs.com.google.api.services.drive.model.File.class); - initializeMediaUpload(mediaContent); - } - - @Override - public Insert setAlt(java.lang.String alt) { - return (Insert) super.setAlt(alt); - } - - @Override - public Insert setFields(java.lang.String fields) { - return (Insert) super.setFields(fields); - } - - @Override - public Insert setKey(java.lang.String key) { - return (Insert) super.setKey(key); - } - - @Override - public Insert setOauthToken(java.lang.String oauthToken) { - return (Insert) super.setOauthToken(oauthToken); - } - - @Override - public Insert setPrettyPrint(java.lang.Boolean prettyPrint) { - return (Insert) super.setPrettyPrint(prettyPrint); - } - - @Override - public Insert setQuotaUser(java.lang.String quotaUser) { - return (Insert) super.setQuotaUser(quotaUser); - } - - @Override - public Insert setUserIp(java.lang.String userIp) { - return (Insert) super.setUserIp(userIp); - } - - /** The visibility of the new file. This parameter is only relevant when convert=false. */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String visibility; - - /** The visibility of the new file. This parameter is only relevant when convert=false. [default: - DEFAULT] - */ - public java.lang.String getVisibility() { - return visibility; - } - - /** The visibility of the new file. This parameter is only relevant when convert=false. */ - public Insert setVisibility(java.lang.String visibility) { - this.visibility = visibility; - return this; - } - - @Override - public Insert set(String parameterName, Object value) { - return (Insert) super.set(parameterName, value); - } - } - /** - * Lists the user's files. - * - * Create a request for the method "files.list". - * - * This request holds the parameters needed by the drive server. After setting any optional - * parameters, call the {@link List#execute()} method to invoke the remote operation. - * - * @return the request - */ - public List list() throws java.io.IOException { - List result = new List(); - initialize(result); - return result; - } - - public class List extends DriveRequest { - - private static final String REST_PATH = "files"; - - /** - * Lists the user's files. - * - * Create a request for the method "files.list". - * - * This request holds the parameters needed by the the drive server. After setting any optional - * parameters, call the {@link List#execute()} method to invoke the remote operation.

{@link - * List#initialize(autosaveworld.zlibs.com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must be - * called to initialize this instance immediately after invoking the constructor.

- * - * @since 1.13 - */ - protected List() { - super(Drive.this, "GET", REST_PATH, null, autosaveworld.zlibs.com.google.api.services.drive.model.FileList.class); - } - - @Override - public autosaveworld.zlibs.com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { - return super.executeUsingHead(); - } - - @Override - public autosaveworld.zlibs.com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { - return super.buildHttpRequestUsingHead(); - } - - @Override - public List setAlt(java.lang.String alt) { - return (List) super.setAlt(alt); - } - - @Override - public List setFields(java.lang.String fields) { - return (List) super.setFields(fields); - } - - @Override - public List setKey(java.lang.String key) { - return (List) super.setKey(key); - } - - @Override - public List setOauthToken(java.lang.String oauthToken) { - return (List) super.setOauthToken(oauthToken); - } - - @Override - public List setPrettyPrint(java.lang.Boolean prettyPrint) { - return (List) super.setPrettyPrint(prettyPrint); - } - - @Override - public List setQuotaUser(java.lang.String quotaUser) { - return (List) super.setQuotaUser(quotaUser); - } - - @Override - public List setUserIp(java.lang.String userIp) { - return (List) super.setUserIp(userIp); - } - - /** The body of items (files/documents) to which the query applies. */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String corpus; - - /** The body of items (files/documents) to which the query applies. - */ - public java.lang.String getCorpus() { - return corpus; - } - - /** The body of items (files/documents) to which the query applies. */ - public List setCorpus(java.lang.String corpus) { - this.corpus = corpus; - return this; - } - - /** Maximum number of files to return. */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Integer maxResults; - - /** Maximum number of files to return. [default: 100] [minimum: 0] - */ - public java.lang.Integer getMaxResults() { - return maxResults; - } - - /** Maximum number of files to return. */ - public List setMaxResults(java.lang.Integer maxResults) { - this.maxResults = maxResults; - return this; - } - - /** - * A comma-separated list of sort keys. Valid keys are 'createdDate', 'folder', - * 'lastViewedByMeDate', 'modifiedByMeDate', 'modifiedDate', 'quotaBytesUsed', 'recency', - * 'sharedWithMeDate', 'starred', and 'title'. Each key sorts ascending by default, but may be - * reversed with the 'desc' modifier. Example usage: ?orderBy=folder,modifiedDate desc,title. - * Please note that there is a current limitation for users with approximately one million - * files in which the requested sort order is ignored. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String orderBy; - - /** A comma-separated list of sort keys. Valid keys are 'createdDate', 'folder', 'lastViewedByMeDate', - 'modifiedByMeDate', 'modifiedDate', 'quotaBytesUsed', 'recency', 'sharedWithMeDate', 'starred', and - 'title'. Each key sorts ascending by default, but may be reversed with the 'desc' modifier. Example - usage: ?orderBy=folder,modifiedDate desc,title. Please note that there is a current limitation for - users with approximately one million files in which the requested sort order is ignored. - */ - public java.lang.String getOrderBy() { - return orderBy; - } - - /** - * A comma-separated list of sort keys. Valid keys are 'createdDate', 'folder', - * 'lastViewedByMeDate', 'modifiedByMeDate', 'modifiedDate', 'quotaBytesUsed', 'recency', - * 'sharedWithMeDate', 'starred', and 'title'. Each key sorts ascending by default, but may be - * reversed with the 'desc' modifier. Example usage: ?orderBy=folder,modifiedDate desc,title. - * Please note that there is a current limitation for users with approximately one million - * files in which the requested sort order is ignored. - */ - public List setOrderBy(java.lang.String orderBy) { - this.orderBy = orderBy; - return this; - } - - /** Page token for files. */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String pageToken; - - /** Page token for files. - */ - public java.lang.String getPageToken() { - return pageToken; - } - - /** Page token for files. */ - public List setPageToken(java.lang.String pageToken) { - this.pageToken = pageToken; - return this; - } - - /** This parameter is deprecated and has no function. */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String projection; - - /** This parameter is deprecated and has no function. - */ - public java.lang.String getProjection() { - return projection; - } - - /** This parameter is deprecated and has no function. */ - public List setProjection(java.lang.String projection) { - this.projection = projection; - return this; - } - - /** Query string for searching files. */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String q; - - /** Query string for searching files. - */ - public java.lang.String getQ() { - return q; - } - - /** Query string for searching files. */ - public List setQ(java.lang.String q) { - this.q = q; - return this; - } - - /** - * A comma-separated list of spaces to query. Supported values are 'drive', 'appDataFolder' - * and 'photos'. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String spaces; - - /** A comma-separated list of spaces to query. Supported values are 'drive', 'appDataFolder' and - 'photos'. - */ - public java.lang.String getSpaces() { - return spaces; - } - - /** - * A comma-separated list of spaces to query. Supported values are 'drive', 'appDataFolder' - * and 'photos'. - */ - public List setSpaces(java.lang.String spaces) { - this.spaces = spaces; - return this; - } - - @Override - public List set(String parameterName, Object value) { - return (List) super.set(parameterName, value); - } - } - - } - - /** - * Builder for {@link Drive}. - * - *

- * Implementation is not thread-safe. - *

- * - * @since 1.3.0 - */ - public static final class Builder extends autosaveworld.zlibs.com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder { - - /** - * Returns an instance of a new builder. - * - * @param transport HTTP transport, which should normally be: - *
    - *
  • Google App Engine: - * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}
  • - *
  • Android: {@code newCompatibleTransport} from - * {@code com.google.api.client.extensions.android.http.AndroidHttp}
  • - *
  • Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} - *
  • - *
- * @param jsonFactory JSON factory, which may be: - *
    - *
  • Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}
  • - *
  • Google GSON: {@code com.google.api.client.json.gson.GsonFactory}
  • - *
  • Android Honeycomb or higher: - * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}
  • - *
- * @param httpRequestInitializer HTTP request initializer or {@code null} for none - * @since 1.7 - */ - public Builder(autosaveworld.zlibs.com.google.api.client.http.HttpTransport transport, autosaveworld.zlibs.com.google.api.client.json.JsonFactory jsonFactory, - autosaveworld.zlibs.com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { - super( - transport, - jsonFactory, - DEFAULT_ROOT_URL, - DEFAULT_SERVICE_PATH, - httpRequestInitializer, - false); - } - - /** Builds a new instance of {@link Drive}. */ - @Override - public Drive build() { - return new Drive(this); - } - - @Override - public Builder setRootUrl(String rootUrl) { - return (Builder) super.setRootUrl(rootUrl); - } - - @Override - public Builder setServicePath(String servicePath) { - return (Builder) super.setServicePath(servicePath); - } - - @Override - public Builder setHttpRequestInitializer(autosaveworld.zlibs.com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { - return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); - } - - @Override - public Builder setApplicationName(String applicationName) { - return (Builder) super.setApplicationName(applicationName); - } - - @Override - public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { - return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); - } - - @Override - public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { - return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); - } - - @Override - public Builder setSuppressAllChecks(boolean suppressAllChecks) { - return (Builder) super.setSuppressAllChecks(suppressAllChecks); - } - - /** - * Set the {@link DriveRequestInitializer}. - * - * @since 1.12 - */ - public Builder setDriveRequestInitializer( - DriveRequestInitializer driveRequestInitializer) { - return (Builder) super.setGoogleClientRequestInitializer(driveRequestInitializer); - } - - @Override - public Builder setGoogleClientRequestInitializer( - autosaveworld.zlibs.com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) { - return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); - } - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/services/drive/DriveRequest.java b/src/autosaveworld/zlibs/com/google/api/services/drive/DriveRequest.java deleted file mode 100644 index 8be2558e..00000000 --- a/src/autosaveworld/zlibs/com/google/api/services/drive/DriveRequest.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -/* - * This code was generated by https://github.com/google/apis-client-generator/ - * (build: 2016-10-17 16:43:55 UTC) - * on 2016-11-17 at 13:55:42 UTC - * Modify at your own risk. - */ - -package autosaveworld.zlibs.com.google.api.services.drive; - -/** - * Drive request. - * - * @since 1.3 - */ -@SuppressWarnings("javadoc") -public abstract class DriveRequest extends autosaveworld.zlibs.com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest { - - /** - * @param client Google client - * @param method HTTP Method - * @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/" - * the base path from the base URL will be stripped out. The URI template can also be a - * full URL. URI template expansion is done using - * {@link autosaveworld.zlibs.com.google.api.client.http.UriTemplate#expand(String, String, Object, boolean)} - * @param content A POJO that can be serialized into JSON or {@code null} for none - * @param responseClass response class to parse into - */ - public DriveRequest( - Drive client, String method, String uriTemplate, Object content, Class responseClass) { - super( - client, - method, - uriTemplate, - content, - responseClass); - } - - /** Data format for the response. */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String alt; - - /** - * Data format for the response. [default: json] - */ - public java.lang.String getAlt() { - return alt; - } - - /** Data format for the response. */ - public DriveRequest setAlt(java.lang.String alt) { - this.alt = alt; - return this; - } - - /** Selector specifying which fields to include in a partial response. */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String fields; - - /** - * Selector specifying which fields to include in a partial response. - */ - public java.lang.String getFields() { - return fields; - } - - /** Selector specifying which fields to include in a partial response. */ - public DriveRequest setFields(java.lang.String fields) { - this.fields = fields; - return this; - } - - /** - * API key. Your API key identifies your project and provides you with API access, quota, and - * reports. Required unless you provide an OAuth 2.0 token. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String key; - - /** - * API key. Your API key identifies your project and provides you with API access, quota, and - * reports. Required unless you provide an OAuth 2.0 token. - */ - public java.lang.String getKey() { - return key; - } - - /** - * API key. Your API key identifies your project and provides you with API access, quota, and - * reports. Required unless you provide an OAuth 2.0 token. - */ - public DriveRequest setKey(java.lang.String key) { - this.key = key; - return this; - } - - /** OAuth 2.0 token for the current user. */ - @autosaveworld.zlibs.com.google.api.client.util.Key("oauth_token") - private java.lang.String oauthToken; - - /** - * OAuth 2.0 token for the current user. - */ - public java.lang.String getOauthToken() { - return oauthToken; - } - - /** OAuth 2.0 token for the current user. */ - public DriveRequest setOauthToken(java.lang.String oauthToken) { - this.oauthToken = oauthToken; - return this; - } - - /** Returns response with indentations and line breaks. */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Boolean prettyPrint; - - /** - * Returns response with indentations and line breaks. [default: true] - */ - public java.lang.Boolean getPrettyPrint() { - return prettyPrint; - } - - /** Returns response with indentations and line breaks. */ - public DriveRequest setPrettyPrint(java.lang.Boolean prettyPrint) { - this.prettyPrint = prettyPrint; - return this; - } - - /** - * Available to use for quota purposes for server-side applications. Can be any arbitrary string - * assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String quotaUser; - - /** - * Available to use for quota purposes for server-side applications. Can be any arbitrary string - * assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - */ - public java.lang.String getQuotaUser() { - return quotaUser; - } - - /** - * Available to use for quota purposes for server-side applications. Can be any arbitrary string - * assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - */ - public DriveRequest setQuotaUser(java.lang.String quotaUser) { - this.quotaUser = quotaUser; - return this; - } - - /** - * IP address of the site where the request originates. Use this if you want to enforce per-user - * limits. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String userIp; - - /** - * IP address of the site where the request originates. Use this if you want to enforce per-user - * limits. - */ - public java.lang.String getUserIp() { - return userIp; - } - - /** - * IP address of the site where the request originates. Use this if you want to enforce per-user - * limits. - */ - public DriveRequest setUserIp(java.lang.String userIp) { - this.userIp = userIp; - return this; - } - - @Override - public final Drive getAbstractGoogleClient() { - return (Drive) super.getAbstractGoogleClient(); - } - - @Override - public DriveRequest setDisableGZipContent(boolean disableGZipContent) { - return (DriveRequest) super.setDisableGZipContent(disableGZipContent); - } - - @Override - public DriveRequest setRequestHeaders(autosaveworld.zlibs.com.google.api.client.http.HttpHeaders headers) { - return (DriveRequest) super.setRequestHeaders(headers); - } - - @Override - public DriveRequest set(String parameterName, Object value) { - return (DriveRequest) super.set(parameterName, value); - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/services/drive/DriveRequestInitializer.java b/src/autosaveworld/zlibs/com/google/api/services/drive/DriveRequestInitializer.java deleted file mode 100644 index 5958d1ec..00000000 --- a/src/autosaveworld/zlibs/com/google/api/services/drive/DriveRequestInitializer.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -/* - * This code was generated by https://github.com/google/apis-client-generator/ - * (build: 2016-10-17 16:43:55 UTC) - * on 2016-11-17 at 13:55:42 UTC - * Modify at your own risk. - */ - -package autosaveworld.zlibs.com.google.api.services.drive; - -/** - * Drive request initializer for setting properties like key and userIp. - * - *

- * The simplest usage is to use it to set the key parameter: - *

- * - *
-  public static final GoogleClientRequestInitializer KEY_INITIALIZER =
-      new DriveRequestInitializer(KEY);
- * 
- * - *

- * There is also a constructor to set both the key and userIp parameters: - *

- * - *
-  public static final GoogleClientRequestInitializer INITIALIZER =
-      new DriveRequestInitializer(KEY, USER_IP);
- * 
- * - *

- * If you want to implement custom logic, extend it like this: - *

- * - *
-  public static class MyRequestInitializer extends DriveRequestInitializer {
-
-    {@literal @}Override
-    public void initializeDriveRequest(DriveRequest{@literal <}?{@literal >} request)
-        throws IOException {
-      // custom logic
-    }
-  }
- * 
- * - *

- * Finally, to set the key and userIp parameters and insert custom logic, extend it like this: - *

- * - *
-  public static class MyRequestInitializer2 extends DriveRequestInitializer {
-
-    public MyKeyRequestInitializer() {
-      super(KEY, USER_IP);
-    }
-
-    {@literal @}Override
-    public void initializeDriveRequest(DriveRequest{@literal <}?{@literal >} request)
-        throws IOException {
-      // custom logic
-    }
-  }
- * 
- * - *

- * Subclasses should be thread-safe. - *

- * - * @since 1.12 - */ -public class DriveRequestInitializer extends autosaveworld.zlibs.com.google.api.client.googleapis.services.json.CommonGoogleJsonClientRequestInitializer { - - public DriveRequestInitializer() { - super(); - } - - /** - * @param key API key or {@code null} to leave it unchanged - */ - public DriveRequestInitializer(String key) { - super(key); - } - - /** - * @param key API key or {@code null} to leave it unchanged - * @param userIp user IP or {@code null} to leave it unchanged - */ - public DriveRequestInitializer(String key, String userIp) { - super(key, userIp); - } - - @Override - public final void initializeJsonRequest(autosaveworld.zlibs.com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest request) throws java.io.IOException { - super.initializeJsonRequest(request); - initializeDriveRequest((DriveRequest) request); - } - - /** - * Initializes Drive request. - * - *

- * Default implementation does nothing. Called from - * {@link #initializeJsonRequest(autosaveworld.zlibs.com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest)}. - *

- * - * @throws java.io.IOException I/O exception - */ - protected void initializeDriveRequest(DriveRequest request) throws java.io.IOException { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/services/drive/DriveScopes.java b/src/autosaveworld/zlibs/com/google/api/services/drive/DriveScopes.java deleted file mode 100644 index 7519c756..00000000 --- a/src/autosaveworld/zlibs/com/google/api/services/drive/DriveScopes.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -/* - * This code was generated by https://github.com/google/apis-client-generator/ - * (build: 2016-10-17 16:43:55 UTC) - * on 2016-11-17 at 13:55:42 UTC - * Modify at your own risk. - */ - -package autosaveworld.zlibs.com.google.api.services.drive; - -/** - * Available OAuth 2.0 scopes for use with the Drive API. - * - * @since 1.4 - */ -public class DriveScopes { - - /** View and manage the files in your Google Drive. */ - public static final String DRIVE = "https://www.googleapis.com/auth/drive"; - - /** View and manage its own configuration data in your Google Drive. */ - public static final String DRIVE_APPDATA = "https://www.googleapis.com/auth/drive.appdata"; - - /** View your Google Drive apps. */ - public static final String DRIVE_APPS_READONLY = "https://www.googleapis.com/auth/drive.apps.readonly"; - - /** View and manage Google Drive files and folders that you have opened or created with this app. */ - public static final String DRIVE_FILE = "https://www.googleapis.com/auth/drive.file"; - - /** View and manage metadata of files in your Google Drive. */ - public static final String DRIVE_METADATA = "https://www.googleapis.com/auth/drive.metadata"; - - /** View metadata for files in your Google Drive. */ - public static final String DRIVE_METADATA_READONLY = "https://www.googleapis.com/auth/drive.metadata.readonly"; - - /** View the photos, videos and albums in your Google Photos. */ - public static final String DRIVE_PHOTOS_READONLY = "https://www.googleapis.com/auth/drive.photos.readonly"; - - /** View the files in your Google Drive. */ - public static final String DRIVE_READONLY = "https://www.googleapis.com/auth/drive.readonly"; - - /** Modify your Google Apps Script scripts' behavior. */ - public static final String DRIVE_SCRIPTS = "https://www.googleapis.com/auth/drive.scripts"; - - /** - * Returns an unmodifiable set that contains all scopes declared by this class. - * - * @since 1.16 - */ - public static java.util.Set all() { - java.util.Set set = new java.util.HashSet(); - set.add(DRIVE); - set.add(DRIVE_APPDATA); - set.add(DRIVE_APPS_READONLY); - set.add(DRIVE_FILE); - set.add(DRIVE_METADATA); - set.add(DRIVE_METADATA_READONLY); - set.add(DRIVE_PHOTOS_READONLY); - set.add(DRIVE_READONLY); - set.add(DRIVE_SCRIPTS); - return java.util.Collections.unmodifiableSet(set); - } - - private DriveScopes() { - } -} diff --git a/src/autosaveworld/zlibs/com/google/api/services/drive/model/File.java b/src/autosaveworld/zlibs/com/google/api/services/drive/model/File.java deleted file mode 100644 index 010cb086..00000000 --- a/src/autosaveworld/zlibs/com/google/api/services/drive/model/File.java +++ /dev/null @@ -1,2375 +0,0 @@ -/* - * Copyright 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -/* - * This code was generated by https://github.com/google/apis-client-generator/ - * (build: 2016-10-17 16:43:55 UTC) - * on 2016-11-17 at 13:55:42 UTC - * Modify at your own risk. - */ - -package autosaveworld.zlibs.com.google.api.services.drive.model; - -/** - * The metadata for a file. - * - *

This is the Java data model class that specifies how to parse/serialize into the JSON that is - * transmitted over HTTP when working with the Drive API. For a detailed explanation see: - * https://developers.google.com/api-client-library/java/google-http-java-client/json - *

- * - * @author Google, Inc. - */ -@SuppressWarnings("javadoc") -public final class File extends autosaveworld.zlibs.com.google.api.client.json.GenericJson { - - /** - * A link for opening the file in a relevant Google editor or viewer. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String alternateLink; - - /** - * Whether this file is in the Application Data folder. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Boolean appDataContents; - - /** - * Whether the current user can comment on the file. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Boolean canComment; - - /** - * Whether the current user has read access to the Revisions resource of the file. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Boolean canReadRevisions; - - /** - * Whether the file can be copied by the current user. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Boolean copyable; - - /** - * Create time for this file (formatted RFC 3339 timestamp). - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private autosaveworld.zlibs.com.google.api.client.util.DateTime createdDate; - - /** - * A link to open this file with the user's default app for this file. Only populated when the - * drive.apps.readonly scope is used. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String defaultOpenWithLink; - - /** - * A short description of the file. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String description; - - /** - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String downloadUrl; - - /** - * Whether the file can be edited by the current user. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Boolean editable; - - /** - * A link for embedding the file. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String embedLink; - - /** - * ETag of the file. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String etag; - - /** - * Whether this file has been explicitly trashed, as opposed to recursively trashed. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Boolean explicitlyTrashed; - - /** - * Links for exporting Google Docs to specific formats. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.util.Map exportLinks; - - /** - * The final component of fullFileExtension with trailing text that does not appear to be part of - * the extension removed. This field is only populated for files with content stored in Drive; it - * is not populated for Google Docs or shortcut files. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String fileExtension; - - /** - * The size of the file in bytes. This field is only populated for files with content stored in - * Drive; it is not populated for Google Docs or shortcut files. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key @autosaveworld.zlibs.com.google.api.client.json.JsonString - private java.lang.Long fileSize; - - /** - * Folder color as an RGB hex string if the file is a folder. The list of supported colors is - * available in the folderColorPalette field of the About resource. If an unsupported color is - * specified, it will be changed to the closest color in the palette. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String folderColorRgb; - - /** - * The full file extension; extracted from the title. May contain multiple concatenated - * extensions, such as "tar.gz". Removing an extension from the title does not clear this field; - * however, changing the extension on the title does update this field. This field is only - * populated for files with content stored in Drive; it is not populated for Google Docs or - * shortcut files. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String fullFileExtension; - - /** - * The ID of the file's head revision. This field is only populated for files with content stored - * in Drive; it is not populated for Google Docs or shortcut files. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String headRevisionId; - - /** - * A link to the file's icon. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String iconLink; - - /** - * The ID of the file. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String id; - - /** - * Metadata about image media. This will only be present for image types, and its contents will - * depend on what can be parsed from the image content. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private ImageMediaMetadata imageMediaMetadata; - - /** - * Indexable text attributes for the file (can only be written) - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private IndexableText indexableText; - - /** - * Whether the file was created or opened by the requesting app. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Boolean isAppAuthorized; - - /** - * The type of file. This is always drive#file. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String kind; - - /** - * A group of labels for the file. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private Labels labels; - - /** - * Name of the last user to modify this file. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String lastModifyingUserName; - - /** - * Last time this file was viewed by the user (formatted RFC 3339 timestamp). - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private autosaveworld.zlibs.com.google.api.client.util.DateTime lastViewedByMeDate; - - /** - * Deprecated. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private autosaveworld.zlibs.com.google.api.client.util.DateTime markedViewedByMeDate; - - /** - * An MD5 checksum for the content of this file. This field is only populated for files with - * content stored in Drive; it is not populated for Google Docs or shortcut files. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String md5Checksum; - - /** - * The MIME type of the file. This is only mutable on update when uploading new content. This - * field can be left blank, and the mimetype will be determined from the uploaded content's MIME - * type. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String mimeType; - - /** - * Last time this file was modified by the user (formatted RFC 3339 timestamp). Note that setting - * modifiedDate will also update the modifiedByMe date for the user which set the date. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private autosaveworld.zlibs.com.google.api.client.util.DateTime modifiedByMeDate; - - /** - * Last time this file was modified by anyone (formatted RFC 3339 timestamp). This is only mutable - * on update when the setModifiedDate parameter is set. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private autosaveworld.zlibs.com.google.api.client.util.DateTime modifiedDate; - - /** - * A map of the id of each of the user's apps to a link to open this file with that app. Only - * populated when the drive.apps.readonly scope is used. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.util.Map openWithLinks; - - /** - * The original filename of the uploaded content if available, or else the original value of the - * title field. This is only available for files with binary content in Drive. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String originalFilename; - - /** - * Whether the file is owned by the current user. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Boolean ownedByMe; - - /** - * Name(s) of the owner(s) of this file. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.util.List ownerNames; - - /** - * Collection of parent folders which contain this file. Setting this field will put the file in - * all of the provided folders. On insert, if no folders are provided, the file will be placed in - * the default root folder. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.util.List parents; - - /** - * The number of quota bytes used by this file. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key @autosaveworld.zlibs.com.google.api.client.json.JsonString - private java.lang.Long quotaBytesUsed; - - /** - * A link back to this file. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String selfLink; - - /** - * Whether the file's sharing settings can be modified by the current user. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Boolean shareable; - - /** - * Whether the file has been shared. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Boolean shared; - - /** - * Time at which this file was shared with the user (formatted RFC 3339 timestamp). - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private autosaveworld.zlibs.com.google.api.client.util.DateTime sharedWithMeDate; - - /** - * The list of spaces which contain the file. Supported values are 'drive', 'appDataFolder' and - * 'photos'. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.util.List spaces; - - /** - * Thumbnail for the file. Only accepted on upload and for files that are not already thumbnailed - * by Google. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private Thumbnail thumbnail; - - /** - * A short-lived link to the file's thumbnail. Typically lasts on the order of hours. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String thumbnailLink; - - /** - * The title of this file. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String title; - - /** - * A monotonically increasing version number for the file. This reflects every change made to the - * file on the server, even those not visible to the requesting user. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key @autosaveworld.zlibs.com.google.api.client.json.JsonString - private java.lang.Long version; - - /** - * Metadata about video media. This will only be present for video types. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private VideoMediaMetadata videoMediaMetadata; - - /** - * A link for downloading the content of the file in a browser using cookie based authentication. - * In cases where the content is shared publicly, the content can be downloaded without any - * credentials. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String webContentLink; - - /** - * A link only available on public folders for viewing their static web assets (HTML, CSS, JS, - * etc) via Google Drive's Website Hosting. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String webViewLink; - - /** - * Whether writers can share the document with other users. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Boolean writersCanShare; - - /** - * A link for opening the file in a relevant Google editor or viewer. - * @return value or {@code null} for none - */ - public java.lang.String getAlternateLink() { - return alternateLink; - } - - /** - * A link for opening the file in a relevant Google editor or viewer. - * @param alternateLink alternateLink or {@code null} for none - */ - public File setAlternateLink(java.lang.String alternateLink) { - this.alternateLink = alternateLink; - return this; - } - - /** - * Whether this file is in the Application Data folder. - * @return value or {@code null} for none - */ - public java.lang.Boolean getAppDataContents() { - return appDataContents; - } - - /** - * Whether this file is in the Application Data folder. - * @param appDataContents appDataContents or {@code null} for none - */ - public File setAppDataContents(java.lang.Boolean appDataContents) { - this.appDataContents = appDataContents; - return this; - } - - /** - * Whether the current user can comment on the file. - * @return value or {@code null} for none - */ - public java.lang.Boolean getCanComment() { - return canComment; - } - - /** - * Whether the current user can comment on the file. - * @param canComment canComment or {@code null} for none - */ - public File setCanComment(java.lang.Boolean canComment) { - this.canComment = canComment; - return this; - } - - /** - * Whether the current user has read access to the Revisions resource of the file. - * @return value or {@code null} for none - */ - public java.lang.Boolean getCanReadRevisions() { - return canReadRevisions; - } - - /** - * Whether the current user has read access to the Revisions resource of the file. - * @param canReadRevisions canReadRevisions or {@code null} for none - */ - public File setCanReadRevisions(java.lang.Boolean canReadRevisions) { - this.canReadRevisions = canReadRevisions; - return this; - } - - /** - * Whether the file can be copied by the current user. - * @return value or {@code null} for none - */ - public java.lang.Boolean getCopyable() { - return copyable; - } - - /** - * Whether the file can be copied by the current user. - * @param copyable copyable or {@code null} for none - */ - public File setCopyable(java.lang.Boolean copyable) { - this.copyable = copyable; - return this; - } - - /** - * Create time for this file (formatted RFC 3339 timestamp). - * @return value or {@code null} for none - */ - public autosaveworld.zlibs.com.google.api.client.util.DateTime getCreatedDate() { - return createdDate; - } - - /** - * Create time for this file (formatted RFC 3339 timestamp). - * @param createdDate createdDate or {@code null} for none - */ - public File setCreatedDate(autosaveworld.zlibs.com.google.api.client.util.DateTime createdDate) { - this.createdDate = createdDate; - return this; - } - - /** - * A link to open this file with the user's default app for this file. Only populated when the - * drive.apps.readonly scope is used. - * @return value or {@code null} for none - */ - public java.lang.String getDefaultOpenWithLink() { - return defaultOpenWithLink; - } - - /** - * A link to open this file with the user's default app for this file. Only populated when the - * drive.apps.readonly scope is used. - * @param defaultOpenWithLink defaultOpenWithLink or {@code null} for none - */ - public File setDefaultOpenWithLink(java.lang.String defaultOpenWithLink) { - this.defaultOpenWithLink = defaultOpenWithLink; - return this; - } - - /** - * A short description of the file. - * @return value or {@code null} for none - */ - public java.lang.String getDescription() { - return description; - } - - /** - * A short description of the file. - * @param description description or {@code null} for none - */ - public File setDescription(java.lang.String description) { - this.description = description; - return this; - } - - /** - * @return value or {@code null} for none - */ - public java.lang.String getDownloadUrl() { - return downloadUrl; - } - - /** - * @param downloadUrl downloadUrl or {@code null} for none - */ - public File setDownloadUrl(java.lang.String downloadUrl) { - this.downloadUrl = downloadUrl; - return this; - } - - /** - * Whether the file can be edited by the current user. - * @return value or {@code null} for none - */ - public java.lang.Boolean getEditable() { - return editable; - } - - /** - * Whether the file can be edited by the current user. - * @param editable editable or {@code null} for none - */ - public File setEditable(java.lang.Boolean editable) { - this.editable = editable; - return this; - } - - /** - * A link for embedding the file. - * @return value or {@code null} for none - */ - public java.lang.String getEmbedLink() { - return embedLink; - } - - /** - * A link for embedding the file. - * @param embedLink embedLink or {@code null} for none - */ - public File setEmbedLink(java.lang.String embedLink) { - this.embedLink = embedLink; - return this; - } - - /** - * ETag of the file. - * @return value or {@code null} for none - */ - public java.lang.String getEtag() { - return etag; - } - - /** - * ETag of the file. - * @param etag etag or {@code null} for none - */ - public File setEtag(java.lang.String etag) { - this.etag = etag; - return this; - } - - /** - * Whether this file has been explicitly trashed, as opposed to recursively trashed. - * @return value or {@code null} for none - */ - public java.lang.Boolean getExplicitlyTrashed() { - return explicitlyTrashed; - } - - /** - * Whether this file has been explicitly trashed, as opposed to recursively trashed. - * @param explicitlyTrashed explicitlyTrashed or {@code null} for none - */ - public File setExplicitlyTrashed(java.lang.Boolean explicitlyTrashed) { - this.explicitlyTrashed = explicitlyTrashed; - return this; - } - - /** - * Links for exporting Google Docs to specific formats. - * @return value or {@code null} for none - */ - public java.util.Map getExportLinks() { - return exportLinks; - } - - /** - * Links for exporting Google Docs to specific formats. - * @param exportLinks exportLinks or {@code null} for none - */ - public File setExportLinks(java.util.Map exportLinks) { - this.exportLinks = exportLinks; - return this; - } - - /** - * The final component of fullFileExtension with trailing text that does not appear to be part of - * the extension removed. This field is only populated for files with content stored in Drive; it - * is not populated for Google Docs or shortcut files. - * @return value or {@code null} for none - */ - public java.lang.String getFileExtension() { - return fileExtension; - } - - /** - * The final component of fullFileExtension with trailing text that does not appear to be part of - * the extension removed. This field is only populated for files with content stored in Drive; it - * is not populated for Google Docs or shortcut files. - * @param fileExtension fileExtension or {@code null} for none - */ - public File setFileExtension(java.lang.String fileExtension) { - this.fileExtension = fileExtension; - return this; - } - - /** - * The size of the file in bytes. This field is only populated for files with content stored in - * Drive; it is not populated for Google Docs or shortcut files. - * @return value or {@code null} for none - */ - public java.lang.Long getFileSize() { - return fileSize; - } - - /** - * The size of the file in bytes. This field is only populated for files with content stored in - * Drive; it is not populated for Google Docs or shortcut files. - * @param fileSize fileSize or {@code null} for none - */ - public File setFileSize(java.lang.Long fileSize) { - this.fileSize = fileSize; - return this; - } - - /** - * Folder color as an RGB hex string if the file is a folder. The list of supported colors is - * available in the folderColorPalette field of the About resource. If an unsupported color is - * specified, it will be changed to the closest color in the palette. - * @return value or {@code null} for none - */ - public java.lang.String getFolderColorRgb() { - return folderColorRgb; - } - - /** - * Folder color as an RGB hex string if the file is a folder. The list of supported colors is - * available in the folderColorPalette field of the About resource. If an unsupported color is - * specified, it will be changed to the closest color in the palette. - * @param folderColorRgb folderColorRgb or {@code null} for none - */ - public File setFolderColorRgb(java.lang.String folderColorRgb) { - this.folderColorRgb = folderColorRgb; - return this; - } - - /** - * The full file extension; extracted from the title. May contain multiple concatenated - * extensions, such as "tar.gz". Removing an extension from the title does not clear this field; - * however, changing the extension on the title does update this field. This field is only - * populated for files with content stored in Drive; it is not populated for Google Docs or - * shortcut files. - * @return value or {@code null} for none - */ - public java.lang.String getFullFileExtension() { - return fullFileExtension; - } - - /** - * The full file extension; extracted from the title. May contain multiple concatenated - * extensions, such as "tar.gz". Removing an extension from the title does not clear this field; - * however, changing the extension on the title does update this field. This field is only - * populated for files with content stored in Drive; it is not populated for Google Docs or - * shortcut files. - * @param fullFileExtension fullFileExtension or {@code null} for none - */ - public File setFullFileExtension(java.lang.String fullFileExtension) { - this.fullFileExtension = fullFileExtension; - return this; - } - - /** - * The ID of the file's head revision. This field is only populated for files with content stored - * in Drive; it is not populated for Google Docs or shortcut files. - * @return value or {@code null} for none - */ - public java.lang.String getHeadRevisionId() { - return headRevisionId; - } - - /** - * The ID of the file's head revision. This field is only populated for files with content stored - * in Drive; it is not populated for Google Docs or shortcut files. - * @param headRevisionId headRevisionId or {@code null} for none - */ - public File setHeadRevisionId(java.lang.String headRevisionId) { - this.headRevisionId = headRevisionId; - return this; - } - - /** - * A link to the file's icon. - * @return value or {@code null} for none - */ - public java.lang.String getIconLink() { - return iconLink; - } - - /** - * A link to the file's icon. - * @param iconLink iconLink or {@code null} for none - */ - public File setIconLink(java.lang.String iconLink) { - this.iconLink = iconLink; - return this; - } - - /** - * The ID of the file. - * @return value or {@code null} for none - */ - public java.lang.String getId() { - return id; - } - - /** - * The ID of the file. - * @param id id or {@code null} for none - */ - public File setId(java.lang.String id) { - this.id = id; - return this; - } - - /** - * Metadata about image media. This will only be present for image types, and its contents will - * depend on what can be parsed from the image content. - * @return value or {@code null} for none - */ - public ImageMediaMetadata getImageMediaMetadata() { - return imageMediaMetadata; - } - - /** - * Metadata about image media. This will only be present for image types, and its contents will - * depend on what can be parsed from the image content. - * @param imageMediaMetadata imageMediaMetadata or {@code null} for none - */ - public File setImageMediaMetadata(ImageMediaMetadata imageMediaMetadata) { - this.imageMediaMetadata = imageMediaMetadata; - return this; - } - - /** - * Indexable text attributes for the file (can only be written) - * @return value or {@code null} for none - */ - public IndexableText getIndexableText() { - return indexableText; - } - - /** - * Indexable text attributes for the file (can only be written) - * @param indexableText indexableText or {@code null} for none - */ - public File setIndexableText(IndexableText indexableText) { - this.indexableText = indexableText; - return this; - } - - /** - * Whether the file was created or opened by the requesting app. - * @return value or {@code null} for none - */ - public java.lang.Boolean getIsAppAuthorized() { - return isAppAuthorized; - } - - /** - * Whether the file was created or opened by the requesting app. - * @param isAppAuthorized isAppAuthorized or {@code null} for none - */ - public File setIsAppAuthorized(java.lang.Boolean isAppAuthorized) { - this.isAppAuthorized = isAppAuthorized; - return this; - } - - /** - * The type of file. This is always drive#file. - * @return value or {@code null} for none - */ - public java.lang.String getKind() { - return kind; - } - - /** - * The type of file. This is always drive#file. - * @param kind kind or {@code null} for none - */ - public File setKind(java.lang.String kind) { - this.kind = kind; - return this; - } - - /** - * A group of labels for the file. - * @return value or {@code null} for none - */ - public Labels getLabels() { - return labels; - } - - /** - * A group of labels for the file. - * @param labels labels or {@code null} for none - */ - public File setLabels(Labels labels) { - this.labels = labels; - return this; - } - - /** - * Name of the last user to modify this file. - * @return value or {@code null} for none - */ - public java.lang.String getLastModifyingUserName() { - return lastModifyingUserName; - } - - /** - * Name of the last user to modify this file. - * @param lastModifyingUserName lastModifyingUserName or {@code null} for none - */ - public File setLastModifyingUserName(java.lang.String lastModifyingUserName) { - this.lastModifyingUserName = lastModifyingUserName; - return this; - } - - /** - * Last time this file was viewed by the user (formatted RFC 3339 timestamp). - * @return value or {@code null} for none - */ - public autosaveworld.zlibs.com.google.api.client.util.DateTime getLastViewedByMeDate() { - return lastViewedByMeDate; - } - - /** - * Last time this file was viewed by the user (formatted RFC 3339 timestamp). - * @param lastViewedByMeDate lastViewedByMeDate or {@code null} for none - */ - public File setLastViewedByMeDate(autosaveworld.zlibs.com.google.api.client.util.DateTime lastViewedByMeDate) { - this.lastViewedByMeDate = lastViewedByMeDate; - return this; - } - - /** - * Deprecated. - * @return value or {@code null} for none - */ - public autosaveworld.zlibs.com.google.api.client.util.DateTime getMarkedViewedByMeDate() { - return markedViewedByMeDate; - } - - /** - * Deprecated. - * @param markedViewedByMeDate markedViewedByMeDate or {@code null} for none - */ - public File setMarkedViewedByMeDate(autosaveworld.zlibs.com.google.api.client.util.DateTime markedViewedByMeDate) { - this.markedViewedByMeDate = markedViewedByMeDate; - return this; - } - - /** - * An MD5 checksum for the content of this file. This field is only populated for files with - * content stored in Drive; it is not populated for Google Docs or shortcut files. - * @return value or {@code null} for none - */ - public java.lang.String getMd5Checksum() { - return md5Checksum; - } - - /** - * An MD5 checksum for the content of this file. This field is only populated for files with - * content stored in Drive; it is not populated for Google Docs or shortcut files. - * @param md5Checksum md5Checksum or {@code null} for none - */ - public File setMd5Checksum(java.lang.String md5Checksum) { - this.md5Checksum = md5Checksum; - return this; - } - - /** - * The MIME type of the file. This is only mutable on update when uploading new content. This - * field can be left blank, and the mimetype will be determined from the uploaded content's MIME - * type. - * @return value or {@code null} for none - */ - public java.lang.String getMimeType() { - return mimeType; - } - - /** - * The MIME type of the file. This is only mutable on update when uploading new content. This - * field can be left blank, and the mimetype will be determined from the uploaded content's MIME - * type. - * @param mimeType mimeType or {@code null} for none - */ - public File setMimeType(java.lang.String mimeType) { - this.mimeType = mimeType; - return this; - } - - /** - * Last time this file was modified by the user (formatted RFC 3339 timestamp). Note that setting - * modifiedDate will also update the modifiedByMe date for the user which set the date. - * @return value or {@code null} for none - */ - public autosaveworld.zlibs.com.google.api.client.util.DateTime getModifiedByMeDate() { - return modifiedByMeDate; - } - - /** - * Last time this file was modified by the user (formatted RFC 3339 timestamp). Note that setting - * modifiedDate will also update the modifiedByMe date for the user which set the date. - * @param modifiedByMeDate modifiedByMeDate or {@code null} for none - */ - public File setModifiedByMeDate(autosaveworld.zlibs.com.google.api.client.util.DateTime modifiedByMeDate) { - this.modifiedByMeDate = modifiedByMeDate; - return this; - } - - /** - * Last time this file was modified by anyone (formatted RFC 3339 timestamp). This is only mutable - * on update when the setModifiedDate parameter is set. - * @return value or {@code null} for none - */ - public autosaveworld.zlibs.com.google.api.client.util.DateTime getModifiedDate() { - return modifiedDate; - } - - /** - * Last time this file was modified by anyone (formatted RFC 3339 timestamp). This is only mutable - * on update when the setModifiedDate parameter is set. - * @param modifiedDate modifiedDate or {@code null} for none - */ - public File setModifiedDate(autosaveworld.zlibs.com.google.api.client.util.DateTime modifiedDate) { - this.modifiedDate = modifiedDate; - return this; - } - - /** - * A map of the id of each of the user's apps to a link to open this file with that app. Only - * populated when the drive.apps.readonly scope is used. - * @return value or {@code null} for none - */ - public java.util.Map getOpenWithLinks() { - return openWithLinks; - } - - /** - * A map of the id of each of the user's apps to a link to open this file with that app. Only - * populated when the drive.apps.readonly scope is used. - * @param openWithLinks openWithLinks or {@code null} for none - */ - public File setOpenWithLinks(java.util.Map openWithLinks) { - this.openWithLinks = openWithLinks; - return this; - } - - /** - * The original filename of the uploaded content if available, or else the original value of the - * title field. This is only available for files with binary content in Drive. - * @return value or {@code null} for none - */ - public java.lang.String getOriginalFilename() { - return originalFilename; - } - - /** - * The original filename of the uploaded content if available, or else the original value of the - * title field. This is only available for files with binary content in Drive. - * @param originalFilename originalFilename or {@code null} for none - */ - public File setOriginalFilename(java.lang.String originalFilename) { - this.originalFilename = originalFilename; - return this; - } - - /** - * Whether the file is owned by the current user. - * @return value or {@code null} for none - */ - public java.lang.Boolean getOwnedByMe() { - return ownedByMe; - } - - /** - * Whether the file is owned by the current user. - * @param ownedByMe ownedByMe or {@code null} for none - */ - public File setOwnedByMe(java.lang.Boolean ownedByMe) { - this.ownedByMe = ownedByMe; - return this; - } - - /** - * Name(s) of the owner(s) of this file. - * @return value or {@code null} for none - */ - public java.util.List getOwnerNames() { - return ownerNames; - } - - /** - * Name(s) of the owner(s) of this file. - * @param ownerNames ownerNames or {@code null} for none - */ - public File setOwnerNames(java.util.List ownerNames) { - this.ownerNames = ownerNames; - return this; - } - - /** - * Collection of parent folders which contain this file. Setting this field will put the file in - * all of the provided folders. On insert, if no folders are provided, the file will be placed in - * the default root folder. - * @return value or {@code null} for none - */ - public java.util.List getParents() { - return parents; - } - - /** - * Collection of parent folders which contain this file. Setting this field will put the file in - * all of the provided folders. On insert, if no folders are provided, the file will be placed in - * the default root folder. - * @param parents parents or {@code null} for none - */ - public File setParents(java.util.List parents) { - this.parents = parents; - return this; - } - - /** - * The number of quota bytes used by this file. - * @return value or {@code null} for none - */ - public java.lang.Long getQuotaBytesUsed() { - return quotaBytesUsed; - } - - /** - * The number of quota bytes used by this file. - * @param quotaBytesUsed quotaBytesUsed or {@code null} for none - */ - public File setQuotaBytesUsed(java.lang.Long quotaBytesUsed) { - this.quotaBytesUsed = quotaBytesUsed; - return this; - } - - /** - * A link back to this file. - * @return value or {@code null} for none - */ - public java.lang.String getSelfLink() { - return selfLink; - } - - /** - * A link back to this file. - * @param selfLink selfLink or {@code null} for none - */ - public File setSelfLink(java.lang.String selfLink) { - this.selfLink = selfLink; - return this; - } - - /** - * Whether the file's sharing settings can be modified by the current user. - * @return value or {@code null} for none - */ - public java.lang.Boolean getShareable() { - return shareable; - } - - /** - * Whether the file's sharing settings can be modified by the current user. - * @param shareable shareable or {@code null} for none - */ - public File setShareable(java.lang.Boolean shareable) { - this.shareable = shareable; - return this; - } - - /** - * Whether the file has been shared. - * @return value or {@code null} for none - */ - public java.lang.Boolean getShared() { - return shared; - } - - /** - * Whether the file has been shared. - * @param shared shared or {@code null} for none - */ - public File setShared(java.lang.Boolean shared) { - this.shared = shared; - return this; - } - - /** - * Time at which this file was shared with the user (formatted RFC 3339 timestamp). - * @return value or {@code null} for none - */ - public autosaveworld.zlibs.com.google.api.client.util.DateTime getSharedWithMeDate() { - return sharedWithMeDate; - } - - /** - * Time at which this file was shared with the user (formatted RFC 3339 timestamp). - * @param sharedWithMeDate sharedWithMeDate or {@code null} for none - */ - public File setSharedWithMeDate(autosaveworld.zlibs.com.google.api.client.util.DateTime sharedWithMeDate) { - this.sharedWithMeDate = sharedWithMeDate; - return this; - } - - /** - * The list of spaces which contain the file. Supported values are 'drive', 'appDataFolder' and - * 'photos'. - * @return value or {@code null} for none - */ - public java.util.List getSpaces() { - return spaces; - } - - /** - * The list of spaces which contain the file. Supported values are 'drive', 'appDataFolder' and - * 'photos'. - * @param spaces spaces or {@code null} for none - */ - public File setSpaces(java.util.List spaces) { - this.spaces = spaces; - return this; - } - - /** - * Thumbnail for the file. Only accepted on upload and for files that are not already thumbnailed - * by Google. - * @return value or {@code null} for none - */ - public Thumbnail getThumbnail() { - return thumbnail; - } - - /** - * Thumbnail for the file. Only accepted on upload and for files that are not already thumbnailed - * by Google. - * @param thumbnail thumbnail or {@code null} for none - */ - public File setThumbnail(Thumbnail thumbnail) { - this.thumbnail = thumbnail; - return this; - } - - /** - * A short-lived link to the file's thumbnail. Typically lasts on the order of hours. - * @return value or {@code null} for none - */ - public java.lang.String getThumbnailLink() { - return thumbnailLink; - } - - /** - * A short-lived link to the file's thumbnail. Typically lasts on the order of hours. - * @param thumbnailLink thumbnailLink or {@code null} for none - */ - public File setThumbnailLink(java.lang.String thumbnailLink) { - this.thumbnailLink = thumbnailLink; - return this; - } - - /** - * The title of this file. - * @return value or {@code null} for none - */ - public java.lang.String getTitle() { - return title; - } - - /** - * The title of this file. - * @param title title or {@code null} for none - */ - public File setTitle(java.lang.String title) { - this.title = title; - return this; - } - - /** - * A monotonically increasing version number for the file. This reflects every change made to the - * file on the server, even those not visible to the requesting user. - * @return value or {@code null} for none - */ - public java.lang.Long getVersion() { - return version; - } - - /** - * A monotonically increasing version number for the file. This reflects every change made to the - * file on the server, even those not visible to the requesting user. - * @param version version or {@code null} for none - */ - public File setVersion(java.lang.Long version) { - this.version = version; - return this; - } - - /** - * Metadata about video media. This will only be present for video types. - * @return value or {@code null} for none - */ - public VideoMediaMetadata getVideoMediaMetadata() { - return videoMediaMetadata; - } - - /** - * Metadata about video media. This will only be present for video types. - * @param videoMediaMetadata videoMediaMetadata or {@code null} for none - */ - public File setVideoMediaMetadata(VideoMediaMetadata videoMediaMetadata) { - this.videoMediaMetadata = videoMediaMetadata; - return this; - } - - /** - * A link for downloading the content of the file in a browser using cookie based authentication. - * In cases where the content is shared publicly, the content can be downloaded without any - * credentials. - * @return value or {@code null} for none - */ - public java.lang.String getWebContentLink() { - return webContentLink; - } - - /** - * A link for downloading the content of the file in a browser using cookie based authentication. - * In cases where the content is shared publicly, the content can be downloaded without any - * credentials. - * @param webContentLink webContentLink or {@code null} for none - */ - public File setWebContentLink(java.lang.String webContentLink) { - this.webContentLink = webContentLink; - return this; - } - - /** - * A link only available on public folders for viewing their static web assets (HTML, CSS, JS, - * etc) via Google Drive's Website Hosting. - * @return value or {@code null} for none - */ - public java.lang.String getWebViewLink() { - return webViewLink; - } - - /** - * A link only available on public folders for viewing their static web assets (HTML, CSS, JS, - * etc) via Google Drive's Website Hosting. - * @param webViewLink webViewLink or {@code null} for none - */ - public File setWebViewLink(java.lang.String webViewLink) { - this.webViewLink = webViewLink; - return this; - } - - /** - * Whether writers can share the document with other users. - * @return value or {@code null} for none - */ - public java.lang.Boolean getWritersCanShare() { - return writersCanShare; - } - - /** - * Whether writers can share the document with other users. - * @param writersCanShare writersCanShare or {@code null} for none - */ - public File setWritersCanShare(java.lang.Boolean writersCanShare) { - this.writersCanShare = writersCanShare; - return this; - } - - @Override - public File set(String fieldName, Object value) { - return (File) super.set(fieldName, value); - } - - @Override - public File clone() { - return (File) super.clone(); - } - - /** - * Metadata about image media. This will only be present for image types, and its contents will - * depend on what can be parsed from the image content. - */ - public static final class ImageMediaMetadata extends autosaveworld.zlibs.com.google.api.client.json.GenericJson { - - /** - * The aperture used to create the photo (f-number). - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Float aperture; - - /** - * The make of the camera used to create the photo. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String cameraMake; - - /** - * The model of the camera used to create the photo. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String cameraModel; - - /** - * The color space of the photo. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String colorSpace; - - /** - * The date and time the photo was taken (EXIF format timestamp). - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String date; - - /** - * The exposure bias of the photo (APEX value). - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Float exposureBias; - - /** - * The exposure mode used to create the photo. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String exposureMode; - - /** - * The length of the exposure, in seconds. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Float exposureTime; - - /** - * Whether a flash was used to create the photo. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Boolean flashUsed; - - /** - * The focal length used to create the photo, in millimeters. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Float focalLength; - - /** - * The height of the image in pixels. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Integer height; - - /** - * The ISO speed used to create the photo. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Integer isoSpeed; - - /** - * The lens used to create the photo. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String lens; - - /** - * Geographic location information stored in the image. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private Location location; - - /** - * The smallest f-number of the lens at the focal length used to create the photo (APEX value). - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Float maxApertureValue; - - /** - * The metering mode used to create the photo. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String meteringMode; - - /** - * The rotation in clockwise degrees from the image's original orientation. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Integer rotation; - - /** - * The type of sensor used to create the photo. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String sensor; - - /** - * The distance to the subject of the photo, in meters. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Integer subjectDistance; - - /** - * The white balance mode used to create the photo. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String whiteBalance; - - /** - * The width of the image in pixels. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Integer width; - - /** - * The aperture used to create the photo (f-number). - * @return value or {@code null} for none - */ - public java.lang.Float getAperture() { - return aperture; - } - - /** - * The aperture used to create the photo (f-number). - * @param aperture aperture or {@code null} for none - */ - public ImageMediaMetadata setAperture(java.lang.Float aperture) { - this.aperture = aperture; - return this; - } - - /** - * The make of the camera used to create the photo. - * @return value or {@code null} for none - */ - public java.lang.String getCameraMake() { - return cameraMake; - } - - /** - * The make of the camera used to create the photo. - * @param cameraMake cameraMake or {@code null} for none - */ - public ImageMediaMetadata setCameraMake(java.lang.String cameraMake) { - this.cameraMake = cameraMake; - return this; - } - - /** - * The model of the camera used to create the photo. - * @return value or {@code null} for none - */ - public java.lang.String getCameraModel() { - return cameraModel; - } - - /** - * The model of the camera used to create the photo. - * @param cameraModel cameraModel or {@code null} for none - */ - public ImageMediaMetadata setCameraModel(java.lang.String cameraModel) { - this.cameraModel = cameraModel; - return this; - } - - /** - * The color space of the photo. - * @return value or {@code null} for none - */ - public java.lang.String getColorSpace() { - return colorSpace; - } - - /** - * The color space of the photo. - * @param colorSpace colorSpace or {@code null} for none - */ - public ImageMediaMetadata setColorSpace(java.lang.String colorSpace) { - this.colorSpace = colorSpace; - return this; - } - - /** - * The date and time the photo was taken (EXIF format timestamp). - * @return value or {@code null} for none - */ - public java.lang.String getDate() { - return date; - } - - /** - * The date and time the photo was taken (EXIF format timestamp). - * @param date date or {@code null} for none - */ - public ImageMediaMetadata setDate(java.lang.String date) { - this.date = date; - return this; - } - - /** - * The exposure bias of the photo (APEX value). - * @return value or {@code null} for none - */ - public java.lang.Float getExposureBias() { - return exposureBias; - } - - /** - * The exposure bias of the photo (APEX value). - * @param exposureBias exposureBias or {@code null} for none - */ - public ImageMediaMetadata setExposureBias(java.lang.Float exposureBias) { - this.exposureBias = exposureBias; - return this; - } - - /** - * The exposure mode used to create the photo. - * @return value or {@code null} for none - */ - public java.lang.String getExposureMode() { - return exposureMode; - } - - /** - * The exposure mode used to create the photo. - * @param exposureMode exposureMode or {@code null} for none - */ - public ImageMediaMetadata setExposureMode(java.lang.String exposureMode) { - this.exposureMode = exposureMode; - return this; - } - - /** - * The length of the exposure, in seconds. - * @return value or {@code null} for none - */ - public java.lang.Float getExposureTime() { - return exposureTime; - } - - /** - * The length of the exposure, in seconds. - * @param exposureTime exposureTime or {@code null} for none - */ - public ImageMediaMetadata setExposureTime(java.lang.Float exposureTime) { - this.exposureTime = exposureTime; - return this; - } - - /** - * Whether a flash was used to create the photo. - * @return value or {@code null} for none - */ - public java.lang.Boolean getFlashUsed() { - return flashUsed; - } - - /** - * Whether a flash was used to create the photo. - * @param flashUsed flashUsed or {@code null} for none - */ - public ImageMediaMetadata setFlashUsed(java.lang.Boolean flashUsed) { - this.flashUsed = flashUsed; - return this; - } - - /** - * The focal length used to create the photo, in millimeters. - * @return value or {@code null} for none - */ - public java.lang.Float getFocalLength() { - return focalLength; - } - - /** - * The focal length used to create the photo, in millimeters. - * @param focalLength focalLength or {@code null} for none - */ - public ImageMediaMetadata setFocalLength(java.lang.Float focalLength) { - this.focalLength = focalLength; - return this; - } - - /** - * The height of the image in pixels. - * @return value or {@code null} for none - */ - public java.lang.Integer getHeight() { - return height; - } - - /** - * The height of the image in pixels. - * @param height height or {@code null} for none - */ - public ImageMediaMetadata setHeight(java.lang.Integer height) { - this.height = height; - return this; - } - - /** - * The ISO speed used to create the photo. - * @return value or {@code null} for none - */ - public java.lang.Integer getIsoSpeed() { - return isoSpeed; - } - - /** - * The ISO speed used to create the photo. - * @param isoSpeed isoSpeed or {@code null} for none - */ - public ImageMediaMetadata setIsoSpeed(java.lang.Integer isoSpeed) { - this.isoSpeed = isoSpeed; - return this; - } - - /** - * The lens used to create the photo. - * @return value or {@code null} for none - */ - public java.lang.String getLens() { - return lens; - } - - /** - * The lens used to create the photo. - * @param lens lens or {@code null} for none - */ - public ImageMediaMetadata setLens(java.lang.String lens) { - this.lens = lens; - return this; - } - - /** - * Geographic location information stored in the image. - * @return value or {@code null} for none - */ - public Location getLocation() { - return location; - } - - /** - * Geographic location information stored in the image. - * @param location location or {@code null} for none - */ - public ImageMediaMetadata setLocation(Location location) { - this.location = location; - return this; - } - - /** - * The smallest f-number of the lens at the focal length used to create the photo (APEX value). - * @return value or {@code null} for none - */ - public java.lang.Float getMaxApertureValue() { - return maxApertureValue; - } - - /** - * The smallest f-number of the lens at the focal length used to create the photo (APEX value). - * @param maxApertureValue maxApertureValue or {@code null} for none - */ - public ImageMediaMetadata setMaxApertureValue(java.lang.Float maxApertureValue) { - this.maxApertureValue = maxApertureValue; - return this; - } - - /** - * The metering mode used to create the photo. - * @return value or {@code null} for none - */ - public java.lang.String getMeteringMode() { - return meteringMode; - } - - /** - * The metering mode used to create the photo. - * @param meteringMode meteringMode or {@code null} for none - */ - public ImageMediaMetadata setMeteringMode(java.lang.String meteringMode) { - this.meteringMode = meteringMode; - return this; - } - - /** - * The rotation in clockwise degrees from the image's original orientation. - * @return value or {@code null} for none - */ - public java.lang.Integer getRotation() { - return rotation; - } - - /** - * The rotation in clockwise degrees from the image's original orientation. - * @param rotation rotation or {@code null} for none - */ - public ImageMediaMetadata setRotation(java.lang.Integer rotation) { - this.rotation = rotation; - return this; - } - - /** - * The type of sensor used to create the photo. - * @return value or {@code null} for none - */ - public java.lang.String getSensor() { - return sensor; - } - - /** - * The type of sensor used to create the photo. - * @param sensor sensor or {@code null} for none - */ - public ImageMediaMetadata setSensor(java.lang.String sensor) { - this.sensor = sensor; - return this; - } - - /** - * The distance to the subject of the photo, in meters. - * @return value or {@code null} for none - */ - public java.lang.Integer getSubjectDistance() { - return subjectDistance; - } - - /** - * The distance to the subject of the photo, in meters. - * @param subjectDistance subjectDistance or {@code null} for none - */ - public ImageMediaMetadata setSubjectDistance(java.lang.Integer subjectDistance) { - this.subjectDistance = subjectDistance; - return this; - } - - /** - * The white balance mode used to create the photo. - * @return value or {@code null} for none - */ - public java.lang.String getWhiteBalance() { - return whiteBalance; - } - - /** - * The white balance mode used to create the photo. - * @param whiteBalance whiteBalance or {@code null} for none - */ - public ImageMediaMetadata setWhiteBalance(java.lang.String whiteBalance) { - this.whiteBalance = whiteBalance; - return this; - } - - /** - * The width of the image in pixels. - * @return value or {@code null} for none - */ - public java.lang.Integer getWidth() { - return width; - } - - /** - * The width of the image in pixels. - * @param width width or {@code null} for none - */ - public ImageMediaMetadata setWidth(java.lang.Integer width) { - this.width = width; - return this; - } - - @Override - public ImageMediaMetadata set(String fieldName, Object value) { - return (ImageMediaMetadata) super.set(fieldName, value); - } - - @Override - public ImageMediaMetadata clone() { - return (ImageMediaMetadata) super.clone(); - } - - /** - * Geographic location information stored in the image. - */ - public static final class Location extends autosaveworld.zlibs.com.google.api.client.json.GenericJson { - - /** - * The altitude stored in the image. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Double altitude; - - /** - * The latitude stored in the image. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Double latitude; - - /** - * The longitude stored in the image. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Double longitude; - - /** - * The altitude stored in the image. - * @return value or {@code null} for none - */ - public java.lang.Double getAltitude() { - return altitude; - } - - /** - * The altitude stored in the image. - * @param altitude altitude or {@code null} for none - */ - public Location setAltitude(java.lang.Double altitude) { - this.altitude = altitude; - return this; - } - - /** - * The latitude stored in the image. - * @return value or {@code null} for none - */ - public java.lang.Double getLatitude() { - return latitude; - } - - /** - * The latitude stored in the image. - * @param latitude latitude or {@code null} for none - */ - public Location setLatitude(java.lang.Double latitude) { - this.latitude = latitude; - return this; - } - - /** - * The longitude stored in the image. - * @return value or {@code null} for none - */ - public java.lang.Double getLongitude() { - return longitude; - } - - /** - * The longitude stored in the image. - * @param longitude longitude or {@code null} for none - */ - public Location setLongitude(java.lang.Double longitude) { - this.longitude = longitude; - return this; - } - - @Override - public Location set(String fieldName, Object value) { - return (Location) super.set(fieldName, value); - } - - @Override - public Location clone() { - return (Location) super.clone(); - } - - } - } - - /** - * Indexable text attributes for the file (can only be written) - */ - public static final class IndexableText extends autosaveworld.zlibs.com.google.api.client.json.GenericJson { - - /** - * The text to be indexed for this file. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String text; - - /** - * The text to be indexed for this file. - * @return value or {@code null} for none - */ - public java.lang.String getText() { - return text; - } - - /** - * The text to be indexed for this file. - * @param text text or {@code null} for none - */ - public IndexableText setText(java.lang.String text) { - this.text = text; - return this; - } - - @Override - public IndexableText set(String fieldName, Object value) { - return (IndexableText) super.set(fieldName, value); - } - - @Override - public IndexableText clone() { - return (IndexableText) super.clone(); - } - - } - - /** - * A group of labels for the file. - */ - public static final class Labels extends autosaveworld.zlibs.com.google.api.client.json.GenericJson { - - /** - * Deprecated. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Boolean hidden; - - /** - * Whether the file has been modified by this user. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Boolean modified; - - /** - * Whether viewers and commenters are prevented from downloading, printing, and copying this file. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Boolean restricted; - - /** - * Whether this file is starred by the user. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Boolean starred; - - /** - * Whether this file has been trashed. This label applies to all users accessing the file; - * however, only owners are allowed to see and untrash files. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Boolean trashed; - - /** - * Whether this file has been viewed by this user. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Boolean viewed; - - /** - * Deprecated. - * @return value or {@code null} for none - */ - public java.lang.Boolean getHidden() { - return hidden; - } - - /** - * Deprecated. - * @param hidden hidden or {@code null} for none - */ - public Labels setHidden(java.lang.Boolean hidden) { - this.hidden = hidden; - return this; - } - - /** - * Whether the file has been modified by this user. - * @return value or {@code null} for none - */ - public java.lang.Boolean getModified() { - return modified; - } - - /** - * Whether the file has been modified by this user. - * @param modified modified or {@code null} for none - */ - public Labels setModified(java.lang.Boolean modified) { - this.modified = modified; - return this; - } - - /** - * Whether viewers and commenters are prevented from downloading, printing, and copying this file. - * @return value or {@code null} for none - */ - public java.lang.Boolean getRestricted() { - return restricted; - } - - /** - * Whether viewers and commenters are prevented from downloading, printing, and copying this file. - * @param restricted restricted or {@code null} for none - */ - public Labels setRestricted(java.lang.Boolean restricted) { - this.restricted = restricted; - return this; - } - - /** - * Whether this file is starred by the user. - * @return value or {@code null} for none - */ - public java.lang.Boolean getStarred() { - return starred; - } - - /** - * Whether this file is starred by the user. - * @param starred starred or {@code null} for none - */ - public Labels setStarred(java.lang.Boolean starred) { - this.starred = starred; - return this; - } - - /** - * Whether this file has been trashed. This label applies to all users accessing the file; - * however, only owners are allowed to see and untrash files. - * @return value or {@code null} for none - */ - public java.lang.Boolean getTrashed() { - return trashed; - } - - /** - * Whether this file has been trashed. This label applies to all users accessing the file; - * however, only owners are allowed to see and untrash files. - * @param trashed trashed or {@code null} for none - */ - public Labels setTrashed(java.lang.Boolean trashed) { - this.trashed = trashed; - return this; - } - - /** - * Whether this file has been viewed by this user. - * @return value or {@code null} for none - */ - public java.lang.Boolean getViewed() { - return viewed; - } - - /** - * Whether this file has been viewed by this user. - * @param viewed viewed or {@code null} for none - */ - public Labels setViewed(java.lang.Boolean viewed) { - this.viewed = viewed; - return this; - } - - @Override - public Labels set(String fieldName, Object value) { - return (Labels) super.set(fieldName, value); - } - - @Override - public Labels clone() { - return (Labels) super.clone(); - } - - } - - /** - * Thumbnail for the file. Only accepted on upload and for files that are not already thumbnailed by - * Google. - */ - public static final class Thumbnail extends autosaveworld.zlibs.com.google.api.client.json.GenericJson { - - /** - * The URL-safe Base64 encoded bytes of the thumbnail image. It should conform to RFC 4648 section - * 5. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String image; - - /** - * The MIME type of the thumbnail. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String mimeType; - - /** - * The URL-safe Base64 encoded bytes of the thumbnail image. It should conform to RFC 4648 section - * 5. - * @see #decodeImage() - * @return value or {@code null} for none - */ - public java.lang.String getImage() { - return image; - } - - /** - * The URL-safe Base64 encoded bytes of the thumbnail image. It should conform to RFC 4648 section - * 5. - * @see #getImage() - * @return Base64 decoded value or {@code null} for none - * - * @since 1.14 - */ - public byte[] decodeImage() { - return autosaveworld.zlibs.com.google.api.client.util.Base64.decodeBase64(image); - } - - /** - * The URL-safe Base64 encoded bytes of the thumbnail image. It should conform to RFC 4648 section - * 5. - * @see #encodeImage() - * @param image image or {@code null} for none - */ - public Thumbnail setImage(java.lang.String image) { - this.image = image; - return this; - } - - /** - * The URL-safe Base64 encoded bytes of the thumbnail image. It should conform to RFC 4648 section - * 5. - * @see #setImage() - * - *

- * The value is encoded Base64 or {@code null} for none. - *

- * - * @since 1.14 - */ - public Thumbnail encodeImage(byte[] image) { - this.image = autosaveworld.zlibs.com.google.api.client.util.Base64.encodeBase64URLSafeString(image); - return this; - } - - /** - * The MIME type of the thumbnail. - * @return value or {@code null} for none - */ - public java.lang.String getMimeType() { - return mimeType; - } - - /** - * The MIME type of the thumbnail. - * @param mimeType mimeType or {@code null} for none - */ - public Thumbnail setMimeType(java.lang.String mimeType) { - this.mimeType = mimeType; - return this; - } - - @Override - public Thumbnail set(String fieldName, Object value) { - return (Thumbnail) super.set(fieldName, value); - } - - @Override - public Thumbnail clone() { - return (Thumbnail) super.clone(); - } - - } - - /** - * Metadata about video media. This will only be present for video types. - */ - public static final class VideoMediaMetadata extends autosaveworld.zlibs.com.google.api.client.json.GenericJson { - - /** - * The duration of the video in milliseconds. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key @autosaveworld.zlibs.com.google.api.client.json.JsonString - private java.lang.Long durationMillis; - - /** - * The height of the video in pixels. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Integer height; - - /** - * The width of the video in pixels. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Integer width; - - /** - * The duration of the video in milliseconds. - * @return value or {@code null} for none - */ - public java.lang.Long getDurationMillis() { - return durationMillis; - } - - /** - * The duration of the video in milliseconds. - * @param durationMillis durationMillis or {@code null} for none - */ - public VideoMediaMetadata setDurationMillis(java.lang.Long durationMillis) { - this.durationMillis = durationMillis; - return this; - } - - /** - * The height of the video in pixels. - * @return value or {@code null} for none - */ - public java.lang.Integer getHeight() { - return height; - } - - /** - * The height of the video in pixels. - * @param height height or {@code null} for none - */ - public VideoMediaMetadata setHeight(java.lang.Integer height) { - this.height = height; - return this; - } - - /** - * The width of the video in pixels. - * @return value or {@code null} for none - */ - public java.lang.Integer getWidth() { - return width; - } - - /** - * The width of the video in pixels. - * @param width width or {@code null} for none - */ - public VideoMediaMetadata setWidth(java.lang.Integer width) { - this.width = width; - return this; - } - - @Override - public VideoMediaMetadata set(String fieldName, Object value) { - return (VideoMediaMetadata) super.set(fieldName, value); - } - - @Override - public VideoMediaMetadata clone() { - return (VideoMediaMetadata) super.clone(); - } - - } - -} diff --git a/src/autosaveworld/zlibs/com/google/api/services/drive/model/FileList.java b/src/autosaveworld/zlibs/com/google/api/services/drive/model/FileList.java deleted file mode 100644 index fcae8b64..00000000 --- a/src/autosaveworld/zlibs/com/google/api/services/drive/model/FileList.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Copyright 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -/* - * This code was generated by https://github.com/google/apis-client-generator/ - * (build: 2016-10-17 16:43:55 UTC) - * on 2016-11-17 at 13:55:42 UTC - * Modify at your own risk. - */ - -package autosaveworld.zlibs.com.google.api.services.drive.model; - -/** - * A list of files. - * - *

This is the Java data model class that specifies how to parse/serialize into the JSON that is - * transmitted over HTTP when working with the Drive API. For a detailed explanation see: - * https://developers.google.com/api-client-library/java/google-http-java-client/json - *

- * - * @author Google, Inc. - */ -@SuppressWarnings("javadoc") -public final class FileList extends autosaveworld.zlibs.com.google.api.client.json.GenericJson { - - /** - * The ETag of the list. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String etag; - - /** - * The actual list of files. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.util.List items; - - static { - // hack to force ProGuard to consider File used, since otherwise it would be stripped out - // see https://github.com/google/google-api-java-client/issues/543 - autosaveworld.zlibs.com.google.api.client.util.Data.nullOf(File.class); - } - - /** - * This is always drive#fileList. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String kind; - - /** - * A link to the next page of files. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String nextLink; - - /** - * The page token for the next page of files. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String nextPageToken; - - /** - * A link back to this list. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String selfLink; - - /** - * The ETag of the list. - * @return value or {@code null} for none - */ - public java.lang.String getEtag() { - return etag; - } - - /** - * The ETag of the list. - * @param etag etag or {@code null} for none - */ - public FileList setEtag(java.lang.String etag) { - this.etag = etag; - return this; - } - - /** - * The actual list of files. - * @return value or {@code null} for none - */ - public java.util.List getItems() { - return items; - } - - /** - * The actual list of files. - * @param items items or {@code null} for none - */ - public FileList setItems(java.util.List items) { - this.items = items; - return this; - } - - /** - * This is always drive#fileList. - * @return value or {@code null} for none - */ - public java.lang.String getKind() { - return kind; - } - - /** - * This is always drive#fileList. - * @param kind kind or {@code null} for none - */ - public FileList setKind(java.lang.String kind) { - this.kind = kind; - return this; - } - - /** - * A link to the next page of files. - * @return value or {@code null} for none - */ - public java.lang.String getNextLink() { - return nextLink; - } - - /** - * A link to the next page of files. - * @param nextLink nextLink or {@code null} for none - */ - public FileList setNextLink(java.lang.String nextLink) { - this.nextLink = nextLink; - return this; - } - - /** - * The page token for the next page of files. - * @return value or {@code null} for none - */ - public java.lang.String getNextPageToken() { - return nextPageToken; - } - - /** - * The page token for the next page of files. - * @param nextPageToken nextPageToken or {@code null} for none - */ - public FileList setNextPageToken(java.lang.String nextPageToken) { - this.nextPageToken = nextPageToken; - return this; - } - - /** - * A link back to this list. - * @return value or {@code null} for none - */ - public java.lang.String getSelfLink() { - return selfLink; - } - - /** - * A link back to this list. - * @param selfLink selfLink or {@code null} for none - */ - public FileList setSelfLink(java.lang.String selfLink) { - this.selfLink = selfLink; - return this; - } - - @Override - public FileList set(String fieldName, Object value) { - return (FileList) super.set(fieldName, value); - } - - @Override - public FileList clone() { - return (FileList) super.clone(); - } - -} diff --git a/src/autosaveworld/zlibs/com/google/api/services/drive/model/ParentReference.java b/src/autosaveworld/zlibs/com/google/api/services/drive/model/ParentReference.java deleted file mode 100644 index f4a4e984..00000000 --- a/src/autosaveworld/zlibs/com/google/api/services/drive/model/ParentReference.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. - */ -/* - * This code was generated by https://github.com/google/apis-client-generator/ - * (build: 2016-10-17 16:43:55 UTC) - * on 2016-11-17 at 13:55:42 UTC - * Modify at your own risk. - */ - -package autosaveworld.zlibs.com.google.api.services.drive.model; - -/** - * A reference to a file's parent. - * - *

This is the Java data model class that specifies how to parse/serialize into the JSON that is - * transmitted over HTTP when working with the Drive API. For a detailed explanation see: - * https://developers.google.com/api-client-library/java/google-http-java-client/json - *

- * - * @author Google, Inc. - */ -@SuppressWarnings("javadoc") -public final class ParentReference extends autosaveworld.zlibs.com.google.api.client.json.GenericJson { - - /** - * The ID of the parent. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String id; - - /** - * Whether or not the parent is the root folder. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.Boolean isRoot; - - /** - * This is always drive#parentReference. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String kind; - - /** - * A link to the parent. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String parentLink; - - /** - * A link back to this reference. - * The value may be {@code null}. - */ - @autosaveworld.zlibs.com.google.api.client.util.Key - private java.lang.String selfLink; - - /** - * The ID of the parent. - * @return value or {@code null} for none - */ - public java.lang.String getId() { - return id; - } - - /** - * The ID of the parent. - * @param id id or {@code null} for none - */ - public ParentReference setId(java.lang.String id) { - this.id = id; - return this; - } - - /** - * Whether or not the parent is the root folder. - * @return value or {@code null} for none - */ - public java.lang.Boolean getIsRoot() { - return isRoot; - } - - /** - * Whether or not the parent is the root folder. - * @param isRoot isRoot or {@code null} for none - */ - public ParentReference setIsRoot(java.lang.Boolean isRoot) { - this.isRoot = isRoot; - return this; - } - - /** - * This is always drive#parentReference. - * @return value or {@code null} for none - */ - public java.lang.String getKind() { - return kind; - } - - /** - * This is always drive#parentReference. - * @param kind kind or {@code null} for none - */ - public ParentReference setKind(java.lang.String kind) { - this.kind = kind; - return this; - } - - /** - * A link to the parent. - * @return value or {@code null} for none - */ - public java.lang.String getParentLink() { - return parentLink; - } - - /** - * A link to the parent. - * @param parentLink parentLink or {@code null} for none - */ - public ParentReference setParentLink(java.lang.String parentLink) { - this.parentLink = parentLink; - return this; - } - - /** - * A link back to this reference. - * @return value or {@code null} for none - */ - public java.lang.String getSelfLink() { - return selfLink; - } - - /** - * A link back to this reference. - * @param selfLink selfLink or {@code null} for none - */ - public ParentReference setSelfLink(java.lang.String selfLink) { - this.selfLink = selfLink; - return this; - } - - @Override - public ParentReference set(String fieldName, Object value) { - return (ParentReference) super.set(fieldName, value); - } - - @Override - public ParentReference clone() { - return (ParentReference) super.clone(); - } - -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/Buffer.java b/src/autosaveworld/zlibs/com/jcraft/jsch/Buffer.java deleted file mode 100644 index 57fee3e6..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/Buffer.java +++ /dev/null @@ -1,283 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public class Buffer { - final byte[] tmp = new byte[4]; - byte[] buffer; - int index; - int s; - - public Buffer(int size) { - buffer = new byte[size]; - index = 0; - s = 0; - } - - public Buffer(byte[] buffer) { - this.buffer = buffer; - index = 0; - s = 0; - } - - public Buffer() { - this(1024 * 10 * 2); - } - - public void putByte(byte foo) { - buffer[index++] = foo; - } - - public void putByte(byte[] foo) { - putByte(foo, 0, foo.length); - } - - public void putByte(byte[] foo, int begin, int length) { - System.arraycopy(foo, begin, buffer, index, length); - index += length; - } - - public void putString(byte[] foo) { - putString(foo, 0, foo.length); - } - - public void putString(byte[] foo, int begin, int length) { - putInt(length); - putByte(foo, begin, length); - } - - public void putInt(int val) { - tmp[0] = (byte) (val >>> 24); - tmp[1] = (byte) (val >>> 16); - tmp[2] = (byte) (val >>> 8); - tmp[3] = (byte) (val); - System.arraycopy(tmp, 0, buffer, index, 4); - index += 4; - } - - public void putLong(long val) { - tmp[0] = (byte) (val >>> 56); - tmp[1] = (byte) (val >>> 48); - tmp[2] = (byte) (val >>> 40); - tmp[3] = (byte) (val >>> 32); - System.arraycopy(tmp, 0, buffer, index, 4); - tmp[0] = (byte) (val >>> 24); - tmp[1] = (byte) (val >>> 16); - tmp[2] = (byte) (val >>> 8); - tmp[3] = (byte) (val); - System.arraycopy(tmp, 0, buffer, index + 4, 4); - index += 8; - } - - void skip(int n) { - index += n; - } - - void putPad(int n) { - while (n > 0) { - buffer[index++] = (byte) 0; - n--; - } - } - - public void putMPInt(byte[] foo) { - int i = foo.length; - if ((foo[0] & 0x80) != 0) { - i++; - putInt(i); - putByte((byte) 0); - } else { - putInt(i); - } - putByte(foo); - } - - public int getLength() { - return index - s; - } - - public int getOffSet() { - return s; - } - - public void setOffSet(int s) { - this.s = s; - } - - public long getLong() { - long foo = getInt() & 0xffffffffL; - foo = ((foo << 32)) | (getInt() & 0xffffffffL); - return foo; - } - - public int getInt() { - int foo = getShort(); - foo = ((foo << 16) & 0xffff0000) | (getShort() & 0xffff); - return foo; - } - - public long getUInt() { - long foo = 0L; - long bar = 0L; - foo = getByte(); - foo = ((foo << 8) & 0xff00) | (getByte() & 0xff); - bar = getByte(); - bar = ((bar << 8) & 0xff00) | (getByte() & 0xff); - foo = ((foo << 16) & 0xffff0000) | (bar & 0xffff); - return foo; - } - - int getShort() { - int foo = getByte(); - foo = ((foo << 8) & 0xff00) | (getByte() & 0xff); - return foo; - } - - public int getByte() { - return (buffer[s++] & 0xff); - } - - public void getByte(byte[] foo) { - getByte(foo, 0, foo.length); - } - - void getByte(byte[] foo, int start, int len) { - System.arraycopy(buffer, s, foo, start, len); - s += len; - } - - public int getByte(int len) { - int foo = s; - s += len; - return foo; - } - - public byte[] getMPInt() { - int i = getInt(); - if ((i < 0) || (i > (8 * 1024))) { - i = 8 * 1024; - } - byte[] foo = new byte[i]; - getByte(foo, 0, i); - return foo; - } - - public byte[] getMPIntBits() { - int bits = getInt(); - int bytes = (bits + 7) / 8; - byte[] foo = new byte[bytes]; - getByte(foo, 0, bytes); - if ((foo[0] & 0x80) != 0) { - byte[] bar = new byte[foo.length + 1]; - bar[0] = 0; // ?? - System.arraycopy(foo, 0, bar, 1, foo.length); - foo = bar; - } - return foo; - } - - public byte[] getString() { - int i = getInt(); - if ((i < 0) || (i > (256 * 1024))) { - i = 256 * 1024; - } - byte[] foo = new byte[i]; - getByte(foo, 0, i); - return foo; - } - - byte[] getString(int[] start, int[] len) { - int i = getInt(); - start[0] = getByte(i); - len[0] = i; - return buffer; - } - - public void reset() { - index = 0; - s = 0; - } - - public void shift() { - if (s == 0) { - return; - } - System.arraycopy(buffer, s, buffer, 0, index - s); - index = index - s; - s = 0; - } - - void rewind() { - s = 0; - } - - byte getCommand() { - return buffer[5]; - } - - void checkFreeSize(int n) { - int size = index + n + Session.buffer_margin; - if (buffer.length < size) { - int i = buffer.length * 2; - if (i < size) { - i = size; - } - byte[] tmp = new byte[i]; - System.arraycopy(buffer, 0, tmp, 0, index); - buffer = tmp; - } - } - - byte[][] getBytes(int n, String msg) throws JSchException { - byte[][] tmp = new byte[n][]; - for (int i = 0; i < n; i++) { - int j = getInt(); - if (getLength() < j) { - throw new JSchException(msg); - } - tmp[i] = new byte[j]; - getByte(tmp[i]); - } - return tmp; - } - - static Buffer fromBytes(byte[][] args) { - int length = args.length * 4; - for (int i = 0; i < args.length; i++) { - length += args[i].length; - } - Buffer buf = new Buffer(length); - for (int i = 0; i < args.length; i++) { - buf.putString(args[i]); - } - return buf; - } - -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/Channel.java b/src/autosaveworld/zlibs/com/jcraft/jsch/Channel.java deleted file mode 100644 index ded99b34..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/Channel.java +++ /dev/null @@ -1,563 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -import java.io.IOException; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; - -public abstract class Channel implements Runnable { - - static final int SSH_MSG_CHANNEL_OPEN_CONFIRMATION = 91; - static final int SSH_MSG_CHANNEL_OPEN_FAILURE = 92; - static final int SSH_MSG_CHANNEL_WINDOW_ADJUST = 93; - - static final int SSH_OPEN_ADMINISTRATIVELY_PROHIBITED = 1; - static final int SSH_OPEN_CONNECT_FAILED = 2; - static final int SSH_OPEN_UNKNOWN_CHANNEL_TYPE = 3; - static final int SSH_OPEN_RESOURCE_SHORTAGE = 4; - - static int index = 0; - private static java.util.Vector pool = new java.util.Vector(); - - public static enum ChannelType { - SFTP; - } - - static Channel getChannel(ChannelType ctype) { - if (ctype == ChannelType.SFTP) { - return new ChannelSftp(); - } - return null; - } - - static Channel getChannel(int id, Session session) { - synchronized (pool) { - for (int i = 0; i < pool.size(); i++) { - Channel c = (pool.elementAt(i)); - if ((c.id == id) && (c.session == session)) { - return c; - } - } - } - return null; - } - - static void del(Channel c) { - synchronized (pool) { - pool.removeElement(c); - } - } - - int id; - volatile int recipient = -1; - protected byte[] type = Util.str2byte("foo"); - volatile int lwsize_max = 0x100000; - volatile int lwsize = lwsize_max; // local initial window size - volatile int lmpsize = 0x4000; // local maximum packet size - - volatile long rwsize = 0; // remote initial window size - volatile int rmpsize = 0; // remote maximum packet size - - IO io = null; - Thread thread = null; - - volatile boolean eof_local = false; - volatile boolean eof_remote = false; - - volatile boolean close = false; - volatile boolean connected = false; - volatile boolean open_confirmation = false; - - volatile int exitstatus = -1; - - volatile int reply = 0; - volatile int connectTimeout = 0; - - private Session session; - - int notifyme = 0; - - Channel() { - synchronized (pool) { - id = index++; - pool.addElement(this); - } - } - - synchronized void setRecipient(int foo) { - recipient = foo; - if (notifyme > 0) { - notifyAll(); - } - } - - int getRecipient() { - return recipient; - } - - void init() throws JSchException { - } - - public void connect() throws JSchException { - connect(0); - } - - public void connect(int connectTimeout) throws JSchException { - this.connectTimeout = connectTimeout; - try { - sendChannelOpen(); - start(); - } catch (Exception e) { - connected = false; - disconnect(); - if (e instanceof JSchException) { - throw (JSchException) e; - } - throw new JSchException(e.toString(), e); - } - } - - public void setXForwarding(boolean foo) { - } - - public void start() throws JSchException { - } - - public boolean isEOF() { - return eof_remote; - } - - void getData(Buffer buf) { - setRecipient(buf.getInt()); - setRemoteWindowSize(buf.getUInt()); - setRemotePacketSize(buf.getInt()); - } - - static class MyPipedInputStream extends PipedInputStream { - private int BUFFER_SIZE = 1024; - private int max_buffer_size = BUFFER_SIZE; - - MyPipedInputStream() throws IOException { - super(); - } - - MyPipedInputStream(int size) throws IOException { - super(); - buffer = new byte[size]; - BUFFER_SIZE = size; - max_buffer_size = size; - } - - MyPipedInputStream(int size, int max_buffer_size) throws IOException { - this(size); - this.max_buffer_size = max_buffer_size; - } - - MyPipedInputStream(PipedOutputStream out) throws IOException { - super(out); - } - - MyPipedInputStream(PipedOutputStream out, int size) throws IOException { - super(out); - buffer = new byte[size]; - BUFFER_SIZE = size; - } - - public synchronized void updateReadSide() throws IOException { - if (available() != 0) { // not empty - return; - } - in = 0; - out = 0; - buffer[in++] = 0; - read(); - } - - private int freeSpace() { - int size = 0; - if (out < in) { - size = buffer.length - in; - } else if (in < out) { - if (in == -1) { - size = buffer.length; - } else { - size = out - in; - } - } - return size; - } - - synchronized void checkSpace(int len) throws IOException { - int size = freeSpace(); - if (size < len) { - int datasize = buffer.length - size; - int foo = buffer.length; - while ((foo - datasize) < len) { - foo *= 2; - } - - if (foo > max_buffer_size) { - foo = max_buffer_size; - } - if ((foo - datasize) < len) { - return; - } - - byte[] tmp = new byte[foo]; - if (out < in) { - System.arraycopy(buffer, 0, tmp, 0, buffer.length); - } else if (in < out) { - if (in == -1) { - } else { - System.arraycopy(buffer, 0, tmp, 0, in); - System.arraycopy(buffer, out, tmp, tmp.length - (buffer.length - out), (buffer.length - out)); - out = tmp.length - (buffer.length - out); - } - } else if (in == out) { - System.arraycopy(buffer, 0, tmp, 0, buffer.length); - in = buffer.length; - } - buffer = tmp; - } else if ((buffer.length == size) && (size > BUFFER_SIZE)) { - int i = size / 2; - if (i < BUFFER_SIZE) { - i = BUFFER_SIZE; - } - byte[] tmp = new byte[i]; - buffer = tmp; - } - } - } - - void setLocalWindowSizeMax(int foo) { - lwsize_max = foo; - } - - void setLocalWindowSize(int foo) { - lwsize = foo; - } - - void setLocalPacketSize(int foo) { - lmpsize = foo; - } - - synchronized void setRemoteWindowSize(long foo) { - rwsize = foo; - } - - synchronized void addRemoteWindowSize(long foo) { - rwsize += foo; - if (notifyme > 0) { - notifyAll(); - } - } - - void setRemotePacketSize(int foo) { - rmpsize = foo; - } - - @Override - public void run() { - } - - void write(byte[] foo) throws IOException { - write(foo, 0, foo.length); - } - - void write(byte[] foo, int s, int l) throws IOException { - try { - io.put(foo, s, l); - } catch (NullPointerException e) { - } - } - - void eof_remote() { - eof_remote = true; - try { - io.out_close(); - } catch (NullPointerException e) { - } - } - - void eof() { - if (eof_local) { - return; - } - eof_local = true; - - int i = getRecipient(); - if (i == -1) { - return; - } - - try { - Buffer buf = new Buffer(100); - Packet packet = new Packet(buf); - packet.reset(); - buf.putByte((byte) Session.SSH_MSG_CHANNEL_EOF); - buf.putInt(i); - synchronized (this) { - if (!close) { - getSession().write(packet); - } - } - } catch (Exception e) { - // System.err.println("Channel.eof"); - // e.printStackTrace(); - } - /* - * if(!isConnected()){ disconnect(); } - */ - } - - /* - * http://www1.ietf.org/internet-drafts/draft-ietf-secsh-connect-24.txt - * - * 5.3 Closing a Channel When a party will no longer send more data to a channel, it SHOULD send SSH_MSG_CHANNEL_EOF. - * - * byte SSH_MSG_CHANNEL_EOF uint32 recipient_channel - * - * No explicit response is sent to this message. However, the application may send EOF to whatever is at the other end of the channel. Note that the channel remains open after this message, and more data may still be sent in the other direction. This message does not consume window space and can be sent even if no window space is available. - * - * When either party wishes to terminate the channel, it sends SSH_MSG_CHANNEL_CLOSE. Upon receiving this message, a party MUST send back a SSH_MSG_CHANNEL_CLOSE unless it has already sent this message for the channel. The channel is considered closed for a party when it has both sent and received SSH_MSG_CHANNEL_CLOSE, and the party may then reuse the channel number. A party MAY send SSH_MSG_CHANNEL_CLOSE without having sent or received SSH_MSG_CHANNEL_EOF. - * - * byte SSH_MSG_CHANNEL_CLOSE uint32 recipient_channel - * - * This message does not consume window space and can be sent even if no window space is available. - * - * It is recommended that any data sent before this message is delivered to the actual destination, if possible. - */ - - void close() { - if (close) { - return; - } - close = true; - eof_local = eof_remote = true; - - int i = getRecipient(); - if (i == -1) { - return; - } - - try { - Buffer buf = new Buffer(100); - Packet packet = new Packet(buf); - packet.reset(); - buf.putByte((byte) Session.SSH_MSG_CHANNEL_CLOSE); - buf.putInt(i); - synchronized (this) { - getSession().write(packet); - } - } catch (Exception e) { - // e.printStackTrace(); - } - } - - public boolean isClosed() { - return close; - } - - static void disconnect(Session session) { - Channel[] channels = null; - int count = 0; - synchronized (pool) { - channels = new Channel[pool.size()]; - for (int i = 0; i < pool.size(); i++) { - try { - Channel c = (pool.elementAt(i)); - if (c.session == session) { - channels[count++] = c; - } - } catch (Exception e) { - } - } - } - for (int i = 0; i < count; i++) { - channels[i].disconnect(); - } - } - - public void disconnect() { - // System.err.println(this+":disconnect "+io+" "+connected); - // Thread.dumpStack(); - - try { - - synchronized (this) { - if (!connected) { - return; - } - connected = false; - } - - close(); - - eof_remote = eof_local = true; - - thread = null; - - try { - if (io != null) { - io.close(); - } - } catch (Exception e) { - // e.printStackTrace(); - } - // io=null; - } finally { - Channel.del(this); - } - } - - public boolean isConnected() { - Session _session = session; - if (_session != null) { - return _session.isConnected() && connected; - } - return false; - } - - void setExitStatus(int status) { - exitstatus = status; - } - - public int getExitStatus() { - return exitstatus; - } - - void setSession(Session session) { - this.session = session; - } - - public Session getSession() throws JSchException { - Session _session = session; - if (_session == null) { - throw new JSchException("session is not available"); - } - return _session; - } - - public int getId() { - return id; - } - - protected void sendOpenConfirmation() throws Exception { - Buffer buf = new Buffer(100); - Packet packet = new Packet(buf); - packet.reset(); - buf.putByte((byte) SSH_MSG_CHANNEL_OPEN_CONFIRMATION); - buf.putInt(getRecipient()); - buf.putInt(id); - buf.putInt(lwsize); - buf.putInt(lmpsize); - getSession().write(packet); - } - - protected void sendOpenFailure(int reasoncode) { - try { - Buffer buf = new Buffer(100); - Packet packet = new Packet(buf); - packet.reset(); - buf.putByte((byte) SSH_MSG_CHANNEL_OPEN_FAILURE); - buf.putInt(getRecipient()); - buf.putInt(reasoncode); - buf.putString(Util.str2byte("open failed")); - buf.putString(Util.empty); - getSession().write(packet); - } catch (Exception e) { - } - } - - protected Packet genChannelOpenPacket() { - Buffer buf = new Buffer(100); - Packet packet = new Packet(buf); - // byte SSH_MSG_CHANNEL_OPEN(90) - // string channel type // - // uint32 sender channel // 0 - // uint32 initial window size // 0x100000(65536) - // uint32 maxmum packet size // 0x4000(16384) - packet.reset(); - buf.putByte((byte) 90); - buf.putString(type); - buf.putInt(id); - buf.putInt(lwsize); - buf.putInt(lmpsize); - return packet; - } - - protected void sendChannelOpen() throws Exception { - Session _session = getSession(); - if (!_session.isConnected()) { - throw new JSchException("session is down"); - } - - Packet packet = genChannelOpenPacket(); - _session.write(packet); - - int retry = 2000; - long start = System.currentTimeMillis(); - long timeout = connectTimeout; - if (timeout != 0L) { - retry = 1; - } - synchronized (this) { - while ((getRecipient() == -1) && _session.isConnected() && (retry > 0)) { - if (timeout > 0L) { - if ((System.currentTimeMillis() - start) > timeout) { - retry = 0; - continue; - } - } - try { - long t = timeout == 0L ? 10L : timeout; - notifyme = 1; - wait(t); - } catch (java.lang.InterruptedException e) { - } finally { - notifyme = 0; - } - retry--; - } - } - if (!_session.isConnected()) { - throw new JSchException("session is down"); - } - if (getRecipient() == -1) { // timeout - throw new JSchException("channel is not opened."); - } - if (open_confirmation == false) { // SSH_MSG_CHANNEL_OPEN_FAILURE - throw new JSchException("channel is not opened."); - } - connected = true; - } - -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/ChannelSession.java b/src/autosaveworld/zlibs/com/jcraft/jsch/ChannelSession.java deleted file mode 100644 index 55ab7375..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/ChannelSession.java +++ /dev/null @@ -1,82 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -class ChannelSession extends Channel { - - private static byte[] _session = Util.str2byte("session"); - - ChannelSession() { - super(); - type = _session; - io = new IO(); - } - - @Override - public void run() { - Buffer buf = new Buffer(rmpsize); - Packet packet = new Packet(buf); - int i = -1; - try { - while (isConnected() && (thread != null) && (io != null) && (io.in != null)) { - i = io.in.read(buf.buffer, 14, buf.buffer.length - 14 - Session.buffer_margin); - if (i == 0) { - continue; - } - if (i == -1) { - eof(); - break; - } - if (close) { - break; - } - // System.out.println("write: "+i); - packet.reset(); - buf.putByte((byte) Session.SSH_MSG_CHANNEL_DATA); - buf.putInt(recipient); - buf.putInt(i); - buf.skip(i); - getSession().write(packet, this, i); - } - } catch (Exception e) { - // System.err.println("# ChannelExec.run"); - // e.printStackTrace(); - } - Thread _thread = thread; - if (_thread != null) { - synchronized (_thread) { - _thread.notifyAll(); - } - } - thread = null; - // System.err.println(this+":run <"); - } - -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/ChannelSftp.java b/src/autosaveworld/zlibs/com/jcraft/jsch/ChannelSftp.java deleted file mode 100644 index b6c3145a..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/ChannelSftp.java +++ /dev/null @@ -1,1351 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -import java.io.IOException; -import java.io.InputStream; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; -import java.util.Vector; - -public class ChannelSftp extends ChannelSession { - - static private final int LOCAL_MAXIMUM_PACKET_SIZE = 32 * 1024; - static private final int LOCAL_WINDOW_SIZE_MAX = (64 * LOCAL_MAXIMUM_PACKET_SIZE); - - private static final byte SSH_FXP_INIT = 1; - private static final byte SSH_FXP_OPEN = 3; - private static final byte SSH_FXP_CLOSE = 4; - private static final byte SSH_FXP_WRITE = 6; - private static final byte SSH_FXP_OPENDIR = 11; - private static final byte SSH_FXP_READDIR = 12; - private static final byte SSH_FXP_REMOVE = 13; - private static final byte SSH_FXP_MKDIR = 14; - private static final byte SSH_FXP_RMDIR = 15; - private static final byte SSH_FXP_REALPATH = 16; - private static final byte SSH_FXP_STAT = 17; - private static final byte SSH_FXP_STATUS = 101; - private static final byte SSH_FXP_HANDLE = 102; - private static final byte SSH_FXP_NAME = 104; - private static final byte SSH_FXP_ATTRS = 105; - private static final byte SSH_FXP_EXTENDED = (byte) 200; - - // pflags - private static final int SSH_FXF_WRITE = 0x00000002; - private static final int SSH_FXF_CREAT = 0x00000008; - private static final int SSH_FXF_TRUNC = 0x00000010; - - public static final int SSH_FX_OK = 0; - public static final int SSH_FX_EOF = 1; - public static final int SSH_FX_NO_SUCH_FILE = 2; - public static final int SSH_FX_PERMISSION_DENIED = 3; - public static final int SSH_FX_FAILURE = 4; - public static final int SSH_FX_BAD_MESSAGE = 5; - public static final int SSH_FX_NO_CONNECTION = 6; - public static final int SSH_FX_CONNECTION_LOST = 7; - public static final int SSH_FX_OP_UNSUPPORTED = 8; - /* - * SSH_FX_OK Indicates successful completion of the operation. SSH_FX_EOF indicates end-of-file condition; for SSH_FX_READ it means that no more data is available in the file, and for SSH_FX_READDIR it indicates that no more files are contained in the directory. SSH_FX_NO_SUCH_FILE is returned when a reference is made to a file which should exist but doesn't. SSH_FX_PERMISSION_DENIED is returned when the authenticated user does not have sufficient permissions to perform the operation. - * SSH_FX_FAILURE is a generic catch-all error message; it should be returned if an error occurs for which there is no more specific error code defined. SSH_FX_BAD_MESSAGE may be returned if a badly formatted packet or protocol incompatibility is detected. SSH_FX_NO_CONNECTION is a pseudo-error which indicates that the client has no connection to the server (it can only be generated locally by the client, and MUST NOT be returned by servers). SSH_FX_CONNECTION_LOST is a pseudo-error which - * indicates that the connection to the server has been lost (it can only be generated locally by the client, and MUST NOT be returned by servers). SSH_FX_OP_UNSUPPORTED indicates that an attempt was made to perform an operation which is not supported for the server (it may be generated locally by the client if e.g. the version number exchange indicates that a required feature is not supported by the server, or it may be returned by the server if the server does not implement an operation). - */ - private static final int MAX_MSG_LENGTH = 256 * 1024; - - public static final int OVERWRITE = 0; - public static final int RESUME = 1; - public static final int APPEND = 2; - - private int seq = 1; - private int[] ackid = new int[1]; - - private Buffer buf; - private Packet packet; - - // The followings will be used in file uploading. - private Buffer obuf; - private Packet opacket; - - private int client_version = 3; - private int server_version = 3; - private String version = String.valueOf(client_version); - - private java.util.Hashtable extensions = null; - private InputStream io_in = null; - - private String cwd; - private String home; - - private static final String UTF8 = "UTF-8"; - private String fEncoding = UTF8; - private boolean fEncoding_is_utf8 = true; - - private int bulkRequests = 16; - - /** - * Specify how many requests may be sent at any one time. Increasing this value may slightly improve file transfer speed but will increase memory usage. The default is 16 requests. - * - * @param bulk_requests - * how many requests may be outstanding at any one time. - */ - public void setBulkRequests(int bulk_requests) throws JSchException { - if (bulk_requests > 0) { - bulkRequests = bulk_requests; - } else { - throw new JSchException("setBulkRequests: " + bulk_requests + " must be greater than 0."); - } - } - - /** - * This method will return the value how many requests may be sent at any one time. - * - * @return how many requests may be sent at any one time. - */ - public int getBulkRequests() { - return bulkRequests; - } - - public ChannelSftp() { - super(); - setLocalWindowSizeMax(LOCAL_WINDOW_SIZE_MAX); - setLocalWindowSize(LOCAL_WINDOW_SIZE_MAX); - setLocalPacketSize(LOCAL_MAXIMUM_PACKET_SIZE); - } - - @Override - void init() { - } - - @Override - public void start() throws JSchException { - try { - - PipedOutputStream pos = new PipedOutputStream(); - io.setOutputStream(pos); - PipedInputStream pis = new MyPipedInputStream(pos, rmpsize); - io.setInputStream(pis); - - io_in = io.in; - - if (io_in == null) { - throw new JSchException("channel is down"); - } - - Request request = new RequestSftp(); - request.request(getSession(), this); - - /* - * System.err.println("lmpsize: "+lmpsize); System.err.println("lwsize: "+lwsize); System.err.println("rmpsize: "+rmpsize); System.err.println("rwsize: "+rwsize); - */ - - buf = new Buffer(lmpsize); - packet = new Packet(buf); - - obuf = new Buffer(rmpsize); - opacket = new Packet(obuf); - - int length; - // send SSH_FXP_INIT - sendINIT(); - - // receive SSH_FXP_VERSION - Header header = new Header(); - header = header(buf, header); - length = header.length; - if (length > MAX_MSG_LENGTH) { - throw new SftpException(SSH_FX_FAILURE, "Received message is too long: " + length); - } - server_version = header.rid; - extensions = new java.util.Hashtable(); - if (length > 0) { - // extension data - fill(buf, length); - byte[] extension_name = null; - byte[] extension_data = null; - while (length > 0) { - extension_name = buf.getString(); - length -= (4 + extension_name.length); - extension_data = buf.getString(); - length -= (4 + extension_data.length); - extensions.put(Util.byte2str(extension_name), Util.byte2str(extension_data)); - } - } - } catch (Exception e) { - // System.err.println(e); - if (e instanceof JSchException) { - throw (JSchException) e; - } - if (e instanceof Throwable) { - throw new JSchException(e.toString(), e); - } - throw new JSchException(e.toString()); - } - } - - public void cd(String path) throws SftpException { - try { - ((MyPipedInputStream) io_in).updateReadSide(); - - path = remoteAbsolutePath(path); - path = isUnique(path); - - byte[] str = _realpath(path); - SftpATTRS attr = _stat(str); - - if ((attr.getFlags() & SftpATTRS.SSH_FILEXFER_ATTR_PERMISSIONS) == 0) { - throw new SftpException(SSH_FX_FAILURE, "Can't change directory: " + path); - } - if (!attr.isDir()) { - throw new SftpException(SSH_FX_FAILURE, "Can't change directory: " + path); - } - - setCwd(Util.byte2str(str, fEncoding)); - } catch (Exception e) { - if (e instanceof SftpException) { - throw (SftpException) e; - } - if (e instanceof Throwable) { - throw new SftpException(SSH_FX_FAILURE, "", e); - } - throw new SftpException(SSH_FX_FAILURE, ""); - } - } - - public void put(InputStream src, String dst) throws SftpException { - put(src, dst, null, OVERWRITE); - } - - public void put(InputStream src, String dst, int mode) throws SftpException { - put(src, dst, null, mode); - } - - /** - * Sends data from the input stream src to dst file. The mode should be OVERWRITE, RESUME or APPEND. - * - * @param src - * input stream - * @param dst - * destination file - * @param monitor - * progress monitor - * @param mode - * how data should be added to dst - */ - public void put(InputStream src, String dst, SftpProgressMonitor monitor, int mode) throws SftpException { - try { - ((MyPipedInputStream) io_in).updateReadSide(); - - dst = remoteAbsolutePath(dst); - - Vector v = glob_remote(dst); - int vsize = v.size(); - if (vsize != 1) { - if (vsize == 0) { - if (isPattern(dst)) { - throw new SftpException(SSH_FX_FAILURE, dst); - } else { - dst = Util.unquote(dst); - } - } - throw new SftpException(SSH_FX_FAILURE, v.toString()); - } else { - dst = (v.elementAt(0)); - } - - if (monitor != null) { - monitor.init(SftpProgressMonitor.PUT, "-", dst, SftpProgressMonitor.UNKNOWN_SIZE); - } - - _put(src, dst, monitor, mode); - } catch (Exception e) { - if (e instanceof SftpException) { - if ((((SftpException) e).id == SSH_FX_FAILURE) && isRemoteDir(dst)) { - throw new SftpException(SSH_FX_FAILURE, dst + " is a directory"); - } - throw (SftpException) e; - } - if (e instanceof Throwable) { - throw new SftpException(SSH_FX_FAILURE, e.toString(), e); - } - throw new SftpException(SSH_FX_FAILURE, e.toString()); - } - } - - public void _put(InputStream src, String dst, SftpProgressMonitor monitor, int mode) throws SftpException { - try { - ((MyPipedInputStream) io_in).updateReadSide(); - - byte[] dstb = Util.str2byte(dst, fEncoding); - long skip = 0; - if ((mode == RESUME) || (mode == APPEND)) { - try { - SftpATTRS attr = _stat(dstb); - skip = attr.getSize(); - } catch (Exception eee) { - // System.err.println(eee); - } - } - if ((mode == RESUME) && (skip > 0)) { - long skipped = src.skip(skip); - if (skipped < skip) { - throw new SftpException(SSH_FX_FAILURE, "failed to resume for " + dst); - } - } - - if (mode == OVERWRITE) { - sendOPENW(dstb); - } else { - sendOPENA(dstb); - } - - Header header = new Header(); - header = header(buf, header); - int length = header.length; - int type = header.type; - - fill(buf, length); - - if ((type != SSH_FXP_STATUS) && (type != SSH_FXP_HANDLE)) { - throw new SftpException(SSH_FX_FAILURE, "invalid type=" + type); - } - if (type == SSH_FXP_STATUS) { - int i = buf.getInt(); - throwStatusError(buf, i); - } - byte[] handle = buf.getString(); // handle - byte[] data = null; - - boolean dontcopy = true; - - if (!dontcopy) { // This case will not work anymore. - data = new byte[obuf.buffer.length - (5 + 13 + 21 + handle.length + Session.buffer_margin)]; - } - - long offset = 0; - if ((mode == RESUME) || (mode == APPEND)) { - offset += skip; - } - - int startid = seq; - int ackcount = 0; - int _s = 0; - int _datalen = 0; - - if (!dontcopy) { // This case will not work anymore. - _datalen = data.length; - } else { - data = obuf.buffer; - _s = 5 + 13 + 21 + handle.length; - _datalen = obuf.buffer.length - _s - Session.buffer_margin; - } - - int bulk_requests = bulkRequests; - - while (true) { - int nread = 0; - int count = 0; - int s = _s; - int datalen = _datalen; - - do { - nread = src.read(data, s, datalen); - if (nread > 0) { - s += nread; - datalen -= nread; - count += nread; - } - } while ((datalen > 0) && (nread > 0)); - if (count <= 0) { - break; - } - - int foo = count; - while (foo > 0) { - if (((seq - 1) == startid) || (((seq - startid) - ackcount) >= bulk_requests)) { - while (((seq - startid) - ackcount) >= bulk_requests) { - if (checkStatus(ackid, header)) { - int _ackid = ackid[0]; - if ((startid > _ackid) || (_ackid > (seq - 1))) { - if (_ackid == seq) { - System.err.println("ack error: startid=" + startid + " seq=" + seq + " _ackid=" + _ackid); - } else { - throw new SftpException(SSH_FX_FAILURE, "ack error: startid=" + startid + " seq=" + seq + " _ackid=" + _ackid); - } - } - ackcount++; - } else { - break; - } - } - } - foo -= sendWRITE(handle, offset, data, 0, foo); - } - offset += count; - if ((monitor != null) && !monitor.count(count)) { - break; - } - } - int _ackcount = seq - startid; - while (_ackcount > ackcount) { - if (!checkStatus(null, header)) { - break; - } - ackcount++; - } - if (monitor != null) { - monitor.end(); - } - _sendCLOSE(handle, header); - } catch (Exception e) { - if (e instanceof SftpException) { - throw (SftpException) e; - } - if (e instanceof Throwable) { - throw new SftpException(SSH_FX_FAILURE, e.toString(), e); - } - throw new SftpException(SSH_FX_FAILURE, e.toString()); - } - } - - public java.util.Vector ls(String path) throws SftpException { - final java.util.Vector v = new Vector(); - LsEntrySelector selector = new LsEntrySelector() { - @Override - public int select(LsEntry entry) { - v.addElement(entry); - return CONTINUE; - } - }; - ls(path, selector); - return v; - } - - /** - * List files specified by the remote path. Each files and directories will be passed to LsEntrySelector#select(LsEntry) method, and if that method returns LsEntrySelector#BREAK, the operation will be canceled immediately. - * - * @see ChannelSftp.LsEntrySelector - * @since 0.1.47 - */ - public void ls(String path, LsEntrySelector selector) throws SftpException { - try { - ((MyPipedInputStream) io_in).updateReadSide(); - - path = remoteAbsolutePath(path); - byte[] pattern = null; - - int foo = path.lastIndexOf('/'); - String dir = path.substring(0, ((foo == 0) ? 1 : foo)); - String _pattern = path.substring(foo + 1); - dir = Util.unquote(dir); - - // If pattern has included '*' or '?', we need to convert - // to UTF-8 string before globbing. - byte[][] _pattern_utf8 = new byte[1][]; - boolean pattern_has_wildcard = isPattern(_pattern, _pattern_utf8); - - if (pattern_has_wildcard) { - pattern = _pattern_utf8[0]; - } else { - String upath = Util.unquote(path); - SftpATTRS attr = _stat(upath); - if (attr.isDir()) { - pattern = null; - dir = upath; - } else { - /* - * // If we can generage longname by ourself, // we don't have to use openDIR. String filename=Util.unquote(_pattern); String longname=... v.addElement(new LsEntry(filename, longname, attr)); return v; - */ - if (fEncoding_is_utf8) { - pattern = _pattern_utf8[0]; - pattern = Util.unquote(pattern); - } else { - _pattern = Util.unquote(_pattern); - pattern = Util.str2byte(_pattern, fEncoding); - } - - } - } - - sendOPENDIR(Util.str2byte(dir, fEncoding)); - - Header header = new Header(); - header = header(buf, header); - int length = header.length; - int type = header.type; - - fill(buf, length); - - if ((type != SSH_FXP_STATUS) && (type != SSH_FXP_HANDLE)) { - throw new SftpException(SSH_FX_FAILURE, ""); - } - if (type == SSH_FXP_STATUS) { - int i = buf.getInt(); - throwStatusError(buf, i); - } - - int cancel = LsEntrySelector.CONTINUE; - byte[] handle = buf.getString(); // handle - - while (cancel == LsEntrySelector.CONTINUE) { - - sendREADDIR(handle); - - header = header(buf, header); - length = header.length; - type = header.type; - if ((type != SSH_FXP_STATUS) && (type != SSH_FXP_NAME)) { - throw new SftpException(SSH_FX_FAILURE, ""); - } - if (type == SSH_FXP_STATUS) { - fill(buf, length); - int i = buf.getInt(); - if (i == SSH_FX_EOF) { - break; - } - throwStatusError(buf, i); - } - - buf.rewind(); - fill(buf.buffer, 0, 4); - length -= 4; - int count = buf.getInt(); - - buf.reset(); - while (count > 0) { - if (length > 0) { - buf.shift(); - int j = (buf.buffer.length > (buf.index + length)) ? length : (buf.buffer.length - buf.index); - int i = fill(buf.buffer, buf.index, j); - buf.index += i; - length -= i; - } - byte[] filename = buf.getString(); - byte[] longname = null; - if (server_version <= 3) { - longname = buf.getString(); - } - SftpATTRS attrs = SftpATTRS.getATTR(buf); - - if (cancel == LsEntrySelector.BREAK) { - count--; - continue; - } - - boolean find = false; - String f = null; - if (pattern == null) { - find = true; - } else if (!pattern_has_wildcard) { - find = Util.array_equals(pattern, filename); - } else { - byte[] _filename = filename; - if (!fEncoding_is_utf8) { - f = Util.byte2str(_filename, fEncoding); - _filename = Util.str2byte(f, UTF8); - } - find = Util.glob(pattern, _filename); - } - - if (find) { - if (f == null) { - f = Util.byte2str(filename, fEncoding); - } - String l = null; - if (longname == null) { - l = attrs.toString() + " " + f; - } else { - l = Util.byte2str(longname, fEncoding); - } - - cancel = selector.select(new LsEntry(f, l, attrs)); - } - - count--; - } - } - _sendCLOSE(handle, header); - - /* - * if(v.size()==1 && pattern_has_wildcard){ LsEntry le=(LsEntry)v.elementAt(0); if(le.getAttrs().isDir()){ String f=le.getFilename(); if(isPattern(f)){ f=Util.quote(f); } if(!dir.endsWith("/")){ dir+="/"; } v=null; return ls(dir+f); } } - */ - - } catch (Exception e) { - if (e instanceof SftpException) { - throw (SftpException) e; - } - if (e instanceof Throwable) { - throw new SftpException(SSH_FX_FAILURE, "", e); - } - throw new SftpException(SSH_FX_FAILURE, ""); - } - } - - public void rm(String path) throws SftpException { - try { - ((MyPipedInputStream) io_in).updateReadSide(); - - path = remoteAbsolutePath(path); - - Vector v = glob_remote(path); - int vsize = v.size(); - - Header header = new Header(); - - for (int j = 0; j < vsize; j++) { - path = (v.elementAt(j)); - sendREMOVE(Util.str2byte(path, fEncoding)); - - header = header(buf, header); - int length = header.length; - int type = header.type; - - fill(buf, length); - - if (type != SSH_FXP_STATUS) { - throw new SftpException(SSH_FX_FAILURE, ""); - } - int i = buf.getInt(); - if (i != SSH_FX_OK) { - throwStatusError(buf, i); - } - } - } catch (Exception e) { - if (e instanceof SftpException) { - throw (SftpException) e; - } - if (e instanceof Throwable) { - throw new SftpException(SSH_FX_FAILURE, "", e); - } - throw new SftpException(SSH_FX_FAILURE, ""); - } - } - - public boolean isRemoteDir(String path) { - try { - sendSTAT(Util.str2byte(path, fEncoding)); - - Header header = new Header(); - header = header(buf, header); - int length = header.length; - int type = header.type; - - fill(buf, length); - - if (type != SSH_FXP_ATTRS) { - return false; - } - SftpATTRS attr = SftpATTRS.getATTR(buf); - return attr.isDir(); - } catch (Exception e) { - } - return false; - } - - public void rmdir(String path) throws SftpException { - try { - ((MyPipedInputStream) io_in).updateReadSide(); - - path = remoteAbsolutePath(path); - - Vector v = glob_remote(path); - int vsize = v.size(); - - Header header = new Header(); - - for (int j = 0; j < vsize; j++) { - path = (v.elementAt(j)); - sendRMDIR(Util.str2byte(path, fEncoding)); - - header = header(buf, header); - int length = header.length; - int type = header.type; - - fill(buf, length); - - if (type != SSH_FXP_STATUS) { - throw new SftpException(SSH_FX_FAILURE, ""); - } - - int i = buf.getInt(); - if (i != SSH_FX_OK) { - throwStatusError(buf, i); - } - } - } catch (Exception e) { - if (e instanceof SftpException) { - throw (SftpException) e; - } - if (e instanceof Throwable) { - throw new SftpException(SSH_FX_FAILURE, "", e); - } - throw new SftpException(SSH_FX_FAILURE, ""); - } - } - - public void mkdir(String path) throws SftpException { - try { - ((MyPipedInputStream) io_in).updateReadSide(); - - path = remoteAbsolutePath(path); - - sendMKDIR(Util.str2byte(path, fEncoding), null); - - Header header = new Header(); - header = header(buf, header); - int length = header.length; - int type = header.type; - - fill(buf, length); - - if (type != SSH_FXP_STATUS) { - throw new SftpException(SSH_FX_FAILURE, ""); - } - - int i = buf.getInt(); - if (i == SSH_FX_OK) { - return; - } - throwStatusError(buf, i); - } catch (Exception e) { - if (e instanceof SftpException) { - throw (SftpException) e; - } - if (e instanceof Throwable) { - throw new SftpException(SSH_FX_FAILURE, "", e); - } - throw new SftpException(SSH_FX_FAILURE, ""); - } - } - - public SftpATTRS stat(String path) throws SftpException { - try { - ((MyPipedInputStream) io_in).updateReadSide(); - - path = remoteAbsolutePath(path); - path = isUnique(path); - - return _stat(path); - } catch (Exception e) { - if (e instanceof SftpException) { - throw (SftpException) e; - } - if (e instanceof Throwable) { - throw new SftpException(SSH_FX_FAILURE, "", e); - } - throw new SftpException(SSH_FX_FAILURE, ""); - } - // return null; - } - - private SftpATTRS _stat(byte[] path) throws SftpException { - try { - - sendSTAT(path); - - Header header = new Header(); - header = header(buf, header); - int length = header.length; - int type = header.type; - - fill(buf, length); - - if (type != SSH_FXP_ATTRS) { - if (type == SSH_FXP_STATUS) { - int i = buf.getInt(); - throwStatusError(buf, i); - } - throw new SftpException(SSH_FX_FAILURE, ""); - } - SftpATTRS attr = SftpATTRS.getATTR(buf); - return attr; - } catch (Exception e) { - if (e instanceof SftpException) { - throw (SftpException) e; - } - if (e instanceof Throwable) { - throw new SftpException(SSH_FX_FAILURE, "", e); - } - throw new SftpException(SSH_FX_FAILURE, ""); - } - // return null; - } - - private SftpATTRS _stat(String path) throws SftpException { - return _stat(Util.str2byte(path, fEncoding)); - } - - private byte[] _realpath(String path) throws SftpException, IOException, Exception { - sendREALPATH(Util.str2byte(path, fEncoding)); - - Header header = new Header(); - header = header(buf, header); - int length = header.length; - int type = header.type; - - fill(buf, length); - - if ((type != SSH_FXP_STATUS) && (type != SSH_FXP_NAME)) { - throw new SftpException(SSH_FX_FAILURE, ""); - } - int i; - if (type == SSH_FXP_STATUS) { - i = buf.getInt(); - throwStatusError(buf, i); - } - i = buf.getInt(); // count - - byte[] str = null; - while (i-- > 0) { - str = buf.getString(); // absolute path; - if (server_version <= 3) { - buf.getString(); - } - SftpATTRS.getATTR(buf); - } - return str; - } - - public String pwd() throws SftpException { - return getCwd(); - } - - public String version() { - return version; - } - - public String getHome() throws SftpException { - if (home == null) { - try { - ((MyPipedInputStream) io_in).updateReadSide(); - - byte[] _home = _realpath(""); - home = Util.byte2str(_home, fEncoding); - } catch (Exception e) { - if (e instanceof SftpException) { - throw (SftpException) e; - } - if (e instanceof Throwable) { - throw new SftpException(SSH_FX_FAILURE, "", e); - } - throw new SftpException(SSH_FX_FAILURE, ""); - } - } - return home; - } - - private String getCwd() throws SftpException { - if (cwd == null) { - cwd = getHome(); - } - return cwd; - } - - private void setCwd(String cwd) { - this.cwd = cwd; - } - - private boolean checkStatus(int[] ackid, Header header) throws IOException, SftpException { - header = header(buf, header); - int length = header.length; - int type = header.type; - if (ackid != null) { - ackid[0] = header.rid; - } - - fill(buf, length); - - if (type != SSH_FXP_STATUS) { - throw new SftpException(SSH_FX_FAILURE, ""); - } - int i = buf.getInt(); - if (i != SSH_FX_OK) { - throwStatusError(buf, i); - } - return true; - } - - private boolean _sendCLOSE(byte[] handle, Header header) throws Exception { - sendCLOSE(handle); - return checkStatus(null, header); - } - - private void sendINIT() throws Exception { - packet.reset(); - putHEAD(SSH_FXP_INIT, 5); - buf.putInt(3); // version 3 - getSession().write(packet, this, 5 + 4); - } - - private void sendREALPATH(byte[] path) throws Exception { - sendPacketPath(SSH_FXP_REALPATH, path); - } - - private void sendSTAT(byte[] path) throws Exception { - sendPacketPath(SSH_FXP_STAT, path); - } - - private void sendREMOVE(byte[] path) throws Exception { - sendPacketPath(SSH_FXP_REMOVE, path); - } - - private void sendMKDIR(byte[] path, SftpATTRS attr) throws Exception { - packet.reset(); - putHEAD(SSH_FXP_MKDIR, 9 + path.length + (attr != null ? attr.length() : 4)); - buf.putInt(seq++); - buf.putString(path); // path - if (attr != null) { - attr.dump(buf); - } else { - buf.putInt(0); - } - getSession().write(packet, this, 9 + path.length + (attr != null ? attr.length() : 4) + 4); - } - - private void sendRMDIR(byte[] path) throws Exception { - sendPacketPath(SSH_FXP_RMDIR, path); - } - - private void sendOPENDIR(byte[] path) throws Exception { - sendPacketPath(SSH_FXP_OPENDIR, path); - } - - private void sendREADDIR(byte[] path) throws Exception { - sendPacketPath(SSH_FXP_READDIR, path); - } - - private void sendCLOSE(byte[] path) throws Exception { - sendPacketPath(SSH_FXP_CLOSE, path); - } - - private void sendOPENW(byte[] path) throws Exception { - sendOPEN(path, SSH_FXF_WRITE | SSH_FXF_CREAT | SSH_FXF_TRUNC); - } - - private void sendOPENA(byte[] path) throws Exception { - sendOPEN(path, SSH_FXF_WRITE | /* SSH_FXF_APPEND| */SSH_FXF_CREAT); - } - - private void sendOPEN(byte[] path, int mode) throws Exception { - packet.reset(); - putHEAD(SSH_FXP_OPEN, 17 + path.length); - buf.putInt(seq++); - buf.putString(path); - buf.putInt(mode); - buf.putInt(0); // attrs - getSession().write(packet, this, 17 + path.length + 4); - } - - private void sendPacketPath(byte fxp, byte[] path) throws Exception { - sendPacketPath(fxp, path, (String) null); - } - - private void sendPacketPath(byte fxp, byte[] path, String extension) throws Exception { - packet.reset(); - int len = 9 + path.length; - if (extension == null) { - putHEAD(fxp, len); - buf.putInt(seq++); - } else { - len += (4 + extension.length()); - putHEAD(SSH_FXP_EXTENDED, len); - buf.putInt(seq++); - buf.putString(Util.str2byte(extension)); - } - buf.putString(path); // path - getSession().write(packet, this, len + 4); - } - - private int sendWRITE(byte[] handle, long offset, byte[] data, int start, int length) throws Exception { - int _length = length; - opacket.reset(); - if (obuf.buffer.length < (obuf.index + 13 + 21 + handle.length + length + Session.buffer_margin)) { - _length = obuf.buffer.length - (obuf.index + 13 + 21 + handle.length + Session.buffer_margin); - // System.err.println("_length="+_length+" length="+length); - } - - putHEAD(obuf, SSH_FXP_WRITE, 21 + handle.length + _length); // 14 - obuf.putInt(seq++); // 4 - obuf.putString(handle); // 4+handle.length - obuf.putLong(offset); // 8 - if (obuf.buffer != data) { - obuf.putString(data, start, _length); // 4+_length - } else { - obuf.putInt(_length); - obuf.skip(_length); - } - getSession().write(opacket, this, 21 + handle.length + _length + 4); - return _length; - } - - private void putHEAD(Buffer buf, byte type, int length) throws Exception { - buf.putByte((byte) Session.SSH_MSG_CHANNEL_DATA); - buf.putInt(recipient); - buf.putInt(length + 4); - buf.putInt(length); - buf.putByte(type); - } - - private void putHEAD(byte type, int length) throws Exception { - putHEAD(buf, type, length); - } - - private Vector glob_remote(String _path) throws Exception { - Vector v = new Vector(); - int i = 0; - - int foo = _path.lastIndexOf('/'); - if (foo < 0) { // it is not absolute path. - v.addElement(Util.unquote(_path)); - return v; - } - - String dir = _path.substring(0, ((foo == 0) ? 1 : foo)); - String _pattern = _path.substring(foo + 1); - - dir = Util.unquote(dir); - - byte[] pattern = null; - byte[][] _pattern_utf8 = new byte[1][]; - boolean pattern_has_wildcard = isPattern(_pattern, _pattern_utf8); - - if (!pattern_has_wildcard) { - if (!dir.equals("/")) { - dir += "/"; - } - v.addElement(dir + Util.unquote(_pattern)); - return v; - } - - pattern = _pattern_utf8[0]; - - sendOPENDIR(Util.str2byte(dir, fEncoding)); - - Header header = new Header(); - header = header(buf, header); - int length = header.length; - int type = header.type; - - fill(buf, length); - - if ((type != SSH_FXP_STATUS) && (type != SSH_FXP_HANDLE)) { - throw new SftpException(SSH_FX_FAILURE, ""); - } - if (type == SSH_FXP_STATUS) { - i = buf.getInt(); - throwStatusError(buf, i); - } - - byte[] handle = buf.getString(); // filename - String pdir = null; // parent directory - - while (true) { - sendREADDIR(handle); - header = header(buf, header); - length = header.length; - type = header.type; - - if ((type != SSH_FXP_STATUS) && (type != SSH_FXP_NAME)) { - throw new SftpException(SSH_FX_FAILURE, ""); - } - if (type == SSH_FXP_STATUS) { - fill(buf, length); - break; - } - - buf.rewind(); - fill(buf.buffer, 0, 4); - length -= 4; - int count = buf.getInt(); - - buf.reset(); - while (count > 0) { - if (length > 0) { - buf.shift(); - int j = (buf.buffer.length > (buf.index + length)) ? length : (buf.buffer.length - buf.index); - i = io_in.read(buf.buffer, buf.index, j); - if (i <= 0) { - break; - } - buf.index += i; - length -= i; - } - - byte[] filename = buf.getString(); - // System.err.println("filename: "+new String(filename)); - if (server_version <= 3) { - buf.getString(); - } - SftpATTRS.getATTR(buf); - - byte[] _filename = filename; - String f = null; - boolean found = false; - - if (!fEncoding_is_utf8) { - f = Util.byte2str(filename, fEncoding); - _filename = Util.str2byte(f, UTF8); - } - found = Util.glob(pattern, _filename); - - if (found) { - if (f == null) { - f = Util.byte2str(filename, fEncoding); - } - if (pdir == null) { - pdir = dir; - if (!pdir.endsWith("/")) { - pdir += "/"; - } - } - v.addElement(pdir + f); - } - count--; - } - } - if (_sendCLOSE(handle, header)) { - return v; - } - return null; - } - - private boolean isPattern(byte[] path) { - int length = path.length; - int i = 0; - while (i < length) { - if ((path[i] == '*') || (path[i] == '?')) { - return true; - } - if ((path[i] == '\\') && ((i + 1) < length)) { - i++; - } - i++; - } - return false; - } - - private void throwStatusError(Buffer buf, int i) throws SftpException { - if ((server_version >= 3) && (buf.getLength() >= 4)) { // WindRiver's sftp will send invalid SSH_FXP_STATUS packet. - byte[] str = buf.getString(); - throw new SftpException(i, Util.byte2str(str, UTF8)); - } else { - throw new SftpException(i, "Failure"); - } - } - - @Override - public void disconnect() { - super.disconnect(); - } - - private boolean isPattern(String path, byte[][] utf8) { - byte[] _path = Util.str2byte(path, UTF8); - if (utf8 != null) { - utf8[0] = _path; - } - return isPattern(_path); - } - - private boolean isPattern(String path) { - return isPattern(path, null); - } - - private void fill(Buffer buf, int len) throws IOException { - buf.reset(); - fill(buf.buffer, 0, len); - buf.skip(len); - } - - private int fill(byte[] buf, int s, int len) throws IOException { - int i = 0; - int foo = s; - while (len > 0) { - i = io_in.read(buf, s, len); - if (i <= 0) { - throw new IOException("inputstream is closed"); - // return (s-foo)==0 ? i : s-foo; - } - s += i; - len -= i; - } - return s - foo; - } - - static class Header { - int length; - int type; - int rid; - } - - private Header header(Buffer buf, Header header) throws IOException { - buf.rewind(); - fill(buf.buffer, 0, 9); - header.length = buf.getInt() - 5; - header.type = buf.getByte() & 0xff; - header.rid = buf.getInt(); - return header; - } - - private String remoteAbsolutePath(String path) throws SftpException { - if (path.charAt(0) == '/') { - return path; - } - String cwd = getCwd(); - // if(cwd.equals(getHome())) return path; - if (cwd.endsWith("/")) { - return cwd + path; - } - return cwd + "/" + path; - } - - /** - * This method will check if the given string can be expanded to the unique string. If it can be expanded to mutiple files, SftpException will be thrown. - * - * @return the returned string is unquoted. - */ - private String isUnique(String path) throws SftpException, Exception { - Vector v = glob_remote(path); - if (v.size() != 1) { - throw new SftpException(SSH_FX_FAILURE, path + " is not unique: " + v.toString()); - } - return (v.elementAt(0)); - } - - public int getServerVersion() throws SftpException { - if (!isConnected()) { - throw new SftpException(SSH_FX_FAILURE, "The channel is not connected."); - } - return server_version; - } - - public void setFilenameEncoding(String encoding) throws SftpException { - int sversion = getServerVersion(); - if ((3 <= sversion) && (sversion <= 5) && !encoding.equals(UTF8)) { - throw new SftpException(SSH_FX_FAILURE, "The encoding can not be changed for this sftp server."); - } - if (encoding.equals(UTF8)) { - encoding = UTF8; - } - fEncoding = encoding; - fEncoding_is_utf8 = fEncoding.equals(UTF8); - } - - public String getExtension(String key) { - if (extensions == null) { - return null; - } - return extensions.get(key); - } - - public String realpath(String path) throws SftpException { - try { - byte[] _path = _realpath(remoteAbsolutePath(path)); - return Util.byte2str(_path, fEncoding); - } catch (Exception e) { - if (e instanceof SftpException) { - throw (SftpException) e; - } - if (e instanceof Throwable) { - throw new SftpException(SSH_FX_FAILURE, "", e); - } - throw new SftpException(SSH_FX_FAILURE, ""); - } - } - - public static class LsEntry implements Comparable { - private String filename; - private String longname; - private SftpATTRS attrs; - - LsEntry(String filename, String longname, SftpATTRS attrs) { - setFilename(filename); - setLongname(longname); - setAttrs(attrs); - } - - public String getFilename() { - return filename; - }; - - void setFilename(String filename) { - this.filename = filename; - }; - - public String getLongname() { - return longname; - }; - - void setLongname(String longname) { - this.longname = longname; - }; - - public SftpATTRS getAttrs() { - return attrs; - }; - - void setAttrs(SftpATTRS attrs) { - this.attrs = attrs; - }; - - @Override - public String toString() { - return longname; - } - - @Override - public int compareTo(Object o) throws ClassCastException { - if (o instanceof LsEntry) { - return filename.compareTo(((LsEntry) o).getFilename()); - } - throw new ClassCastException("a decendent of LsEntry must be given."); - } - } - - /** - * This interface will be passed as an argument for ls method. - * - * @see ChannelSftp.LsEntry - * @see #ls(String, ChannelSftp.LsEntrySelector) - * @since 0.1.47 - */ - public interface LsEntrySelector { - public final int CONTINUE = 0; - public final int BREAK = 1; - - /** - *

- * The select method will be invoked in ls method for each file entry. If this method returns BREAK, ls will be canceled. - * - * @param entry - * one of entry from ls - * @return if BREAK is returned, the 'ls' operation will be canceled. - */ - public int select(LsEntry entry); - } - -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/Cipher.java b/src/autosaveworld/zlibs/com/jcraft/jsch/Cipher.java deleted file mode 100644 index bf6dfa4a..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/Cipher.java +++ /dev/null @@ -1,45 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public interface Cipher { - static int ENCRYPT_MODE = 0; - static int DECRYPT_MODE = 1; - - int getIVSize(); - - int getBlockSize(); - - void init(int mode, byte[] key, byte[] iv) throws Exception; - - void update(byte[] foo, int s1, int len, byte[] bar, int s2) throws Exception; - - boolean isCBC(); -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/CipherNone.java b/src/autosaveworld/zlibs/com/jcraft/jsch/CipherNone.java deleted file mode 100644 index 9872b340..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/CipherNone.java +++ /dev/null @@ -1,60 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public class CipherNone implements Cipher { - - private static final int ivsize = 8; - private static final int bsize = 16; - - @Override - public int getIVSize() { - return ivsize; - } - - @Override - public int getBlockSize() { - return bsize; - } - - @Override - public void init(int mode, byte[] key, byte[] iv) throws Exception { - } - - @Override - public void update(byte[] foo, int s1, int len, byte[] bar, int s2) throws Exception { - } - - @Override - public boolean isCBC() { - return false; - } - -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/DH.java b/src/autosaveworld/zlibs/com/jcraft/jsch/DH.java deleted file mode 100644 index bb38ce9b..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/DH.java +++ /dev/null @@ -1,46 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public interface DH { - - void init() throws Exception; - - void setP(byte[] p); - - void setG(byte[] g); - - byte[] getE() throws Exception; - - void setF(byte[] f); - - byte[] getK() throws Exception; - -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/DHG1.java b/src/autosaveworld/zlibs/com/jcraft/jsch/DHG1.java deleted file mode 100644 index e052d66e..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/DHG1.java +++ /dev/null @@ -1,298 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public class DHG1 extends KeyExchange { - - static final byte[] g = { 2 }; - static final byte[] p = { (byte) 0x00, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xC9, (byte) 0x0F, (byte) 0xDA, (byte) 0xA2, (byte) 0x21, (byte) 0x68, (byte) 0xC2, (byte) 0x34, (byte) 0xC4, (byte) 0xC6, (byte) 0x62, (byte) 0x8B, (byte) 0x80, (byte) 0xDC, (byte) 0x1C, (byte) 0xD1, (byte) 0x29, (byte) 0x02, (byte) 0x4E, (byte) 0x08, (byte) 0x8A, (byte) 0x67, (byte) 0xCC, (byte) 0x74, (byte) 0x02, (byte) 0x0B, (byte) 0xBE, - (byte) 0xA6, (byte) 0x3B, (byte) 0x13, (byte) 0x9B, (byte) 0x22, (byte) 0x51, (byte) 0x4A, (byte) 0x08, (byte) 0x79, (byte) 0x8E, (byte) 0x34, (byte) 0x04, (byte) 0xDD, (byte) 0xEF, (byte) 0x95, (byte) 0x19, (byte) 0xB3, (byte) 0xCD, (byte) 0x3A, (byte) 0x43, (byte) 0x1B, (byte) 0x30, (byte) 0x2B, (byte) 0x0A, (byte) 0x6D, (byte) 0xF2, (byte) 0x5F, (byte) 0x14, (byte) 0x37, (byte) 0x4F, (byte) 0xE1, (byte) 0x35, (byte) 0x6D, (byte) 0x6D, (byte) 0x51, (byte) 0xC2, (byte) 0x45, - (byte) 0xE4, (byte) 0x85, (byte) 0xB5, (byte) 0x76, (byte) 0x62, (byte) 0x5E, (byte) 0x7E, (byte) 0xC6, (byte) 0xF4, (byte) 0x4C, (byte) 0x42, (byte) 0xE9, (byte) 0xA6, (byte) 0x37, (byte) 0xED, (byte) 0x6B, (byte) 0x0B, (byte) 0xFF, (byte) 0x5C, (byte) 0xB6, (byte) 0xF4, (byte) 0x06, (byte) 0xB7, (byte) 0xED, (byte) 0xEE, (byte) 0x38, (byte) 0x6B, (byte) 0xFB, (byte) 0x5A, (byte) 0x89, (byte) 0x9F, (byte) 0xA5, (byte) 0xAE, (byte) 0x9F, (byte) 0x24, (byte) 0x11, (byte) 0x7C, - (byte) 0x4B, (byte) 0x1F, (byte) 0xE6, (byte) 0x49, (byte) 0x28, (byte) 0x66, (byte) 0x51, (byte) 0xEC, (byte) 0xE6, (byte) 0x53, (byte) 0x81, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF }; - - private static final int SSH_MSG_KEXDH_INIT = 30; - private static final int SSH_MSG_KEXDH_REPLY = 31; - - static final int RSA = 0; - static final int DSS = 1; - private int type = 0; - - private int state; - - DH dh; - // HASH sha; - - // byte[] K; - // byte[] H; - - byte[] V_S; - byte[] V_C; - byte[] I_S; - byte[] I_C; - - // byte[] K_S; - - byte[] e; - - private Buffer buf; - private Packet packet; - - @Override - public void init(Session session, byte[] V_S, byte[] V_C, byte[] I_S, byte[] I_C) throws Exception { - this.session = session; - this.V_S = V_S; - this.V_C = V_C; - this.I_S = I_S; - this.I_C = I_C; - - // sha=new SHA1(); - // sha.init(); - try { - Class c = Class.forName(session.getConfig("sha-1")); - sha = (HASH) (c.newInstance()); - sha.init(); - } catch (Exception e) { - System.err.println(e); - } - - buf = new Buffer(); - packet = new Packet(buf); - - try { - Class c = Class.forName(session.getConfig("dh")); - dh = (DH) (c.newInstance()); - dh.init(); - } catch (Exception e) { - // System.err.println(e); - throw e; - } - - dh.setP(p); - dh.setG(g); - - // The client responds with: - // byte SSH_MSG_KEXDH_INIT(30) - // mpint e <- g^x mod p - // x is a random number (1 < x < (p-1)/2) - - e = dh.getE(); - - packet.reset(); - buf.putByte((byte) SSH_MSG_KEXDH_INIT); - buf.putMPInt(e); - session.write(packet); - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "SSH_MSG_KEXDH_INIT sent"); - JSch.getLogger().log(Logger.INFO, "expecting SSH_MSG_KEXDH_REPLY"); - } - - state = SSH_MSG_KEXDH_REPLY; - } - - @Override - public boolean next(Buffer _buf) throws Exception { - int i, j; - - switch (state) { - case SSH_MSG_KEXDH_REPLY: - // The server responds with: - // byte SSH_MSG_KEXDH_REPLY(31) - // string server public host key and certificates (K_S) - // mpint f - // string signature of H - j = _buf.getInt(); - j = _buf.getByte(); - j = _buf.getByte(); - if (j != 31) { - System.err.println("type: must be 31 " + j); - return false; - } - - K_S = _buf.getString(); - // K_S is server_key_blob, which includes .... - // string ssh-dss - // impint p of dsa - // impint q of dsa - // impint g of dsa - // impint pub_key of dsa - // System.err.print("K_S: "); //dump(K_S, 0, K_S.length); - byte[] f = _buf.getMPInt(); - byte[] sig_of_H = _buf.getString(); - /* - * for(int ii=0; ii "); //dump(H, 0, H.length); - - i = 0; - j = 0; - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - String alg = Util.byte2str(K_S, i, j); - i += j; - - boolean result = false; - - if (alg.equals("ssh-rsa")) { - byte[] tmp; - byte[] ee; - byte[] n; - - type = RSA; - - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - ee = tmp; - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - n = tmp; - - // SignatureRSA sig=new SignatureRSA(); - // sig.init(); - - SignatureRSA sig = null; - try { - Class c = Class.forName(session.getConfig("signature.rsa")); - sig = (SignatureRSA) (c.newInstance()); - sig.init(); - } catch (Exception e) { - System.err.println(e); - } - - sig.setPubKey(ee, n); - sig.update(H); - result = sig.verify(sig_of_H); - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "ssh_rsa_verify: signature " + result); - } - - } else if (alg.equals("ssh-dss")) { - byte[] q = null; - byte[] tmp; - byte[] p; - byte[] g; - - type = DSS; - - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - p = tmp; - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - q = tmp; - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - g = tmp; - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - f = tmp; - // SignatureDSA sig=new SignatureDSA(); - // sig.init(); - SignatureDSA sig = null; - try { - Class c = Class.forName(session.getConfig("signature.dss")); - sig = (SignatureDSA) (c.newInstance()); - sig.init(); - } catch (Exception e) { - System.err.println(e); - } - sig.setPubKey(f, p, q, g); - sig.update(H); - result = sig.verify(sig_of_H); - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "ssh_dss_verify: signature " + result); - } - - } else { - System.err.println("unknown alg"); - } - state = STATE_END; - return result; - } - return false; - } - - @Override - public String getKeyType() { - if (type == DSS) { - return "DSA"; - } - return "RSA"; - } - - @Override - public int getState() { - return state; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/DHG14.java b/src/autosaveworld/zlibs/com/jcraft/jsch/DHG14.java deleted file mode 100644 index 6b8c26d0..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/DHG14.java +++ /dev/null @@ -1,290 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public class DHG14 extends KeyExchange { - - static final byte[] g = { 2 }; - static final byte[] p = { (byte) 0x00, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xC9, (byte) 0x0F, (byte) 0xDA, (byte) 0xA2, (byte) 0x21, (byte) 0x68, (byte) 0xC2, (byte) 0x34, (byte) 0xC4, (byte) 0xC6, (byte) 0x62, (byte) 0x8B, (byte) 0x80, (byte) 0xDC, (byte) 0x1C, (byte) 0xD1, (byte) 0x29, (byte) 0x02, (byte) 0x4E, (byte) 0x08, (byte) 0x8A, (byte) 0x67, (byte) 0xCC, (byte) 0x74, (byte) 0x02, (byte) 0x0B, (byte) 0xBE, - (byte) 0xA6, (byte) 0x3B, (byte) 0x13, (byte) 0x9B, (byte) 0x22, (byte) 0x51, (byte) 0x4A, (byte) 0x08, (byte) 0x79, (byte) 0x8E, (byte) 0x34, (byte) 0x04, (byte) 0xDD, (byte) 0xEF, (byte) 0x95, (byte) 0x19, (byte) 0xB3, (byte) 0xCD, (byte) 0x3A, (byte) 0x43, (byte) 0x1B, (byte) 0x30, (byte) 0x2B, (byte) 0x0A, (byte) 0x6D, (byte) 0xF2, (byte) 0x5F, (byte) 0x14, (byte) 0x37, (byte) 0x4F, (byte) 0xE1, (byte) 0x35, (byte) 0x6D, (byte) 0x6D, (byte) 0x51, (byte) 0xC2, (byte) 0x45, - (byte) 0xE4, (byte) 0x85, (byte) 0xB5, (byte) 0x76, (byte) 0x62, (byte) 0x5E, (byte) 0x7E, (byte) 0xC6, (byte) 0xF4, (byte) 0x4C, (byte) 0x42, (byte) 0xE9, (byte) 0xA6, (byte) 0x37, (byte) 0xED, (byte) 0x6B, (byte) 0x0B, (byte) 0xFF, (byte) 0x5C, (byte) 0xB6, (byte) 0xF4, (byte) 0x06, (byte) 0xB7, (byte) 0xED, (byte) 0xEE, (byte) 0x38, (byte) 0x6B, (byte) 0xFB, (byte) 0x5A, (byte) 0x89, (byte) 0x9F, (byte) 0xA5, (byte) 0xAE, (byte) 0x9F, (byte) 0x24, (byte) 0x11, (byte) 0x7C, - (byte) 0x4B, (byte) 0x1F, (byte) 0xE6, (byte) 0x49, (byte) 0x28, (byte) 0x66, (byte) 0x51, (byte) 0xEC, (byte) 0xE4, (byte) 0x5B, (byte) 0x3D, (byte) 0xC2, (byte) 0x00, (byte) 0x7C, (byte) 0xB8, (byte) 0xA1, (byte) 0x63, (byte) 0xBF, (byte) 0x05, (byte) 0x98, (byte) 0xDA, (byte) 0x48, (byte) 0x36, (byte) 0x1C, (byte) 0x55, (byte) 0xD3, (byte) 0x9A, (byte) 0x69, (byte) 0x16, (byte) 0x3F, (byte) 0xA8, (byte) 0xFD, (byte) 0x24, (byte) 0xCF, (byte) 0x5F, (byte) 0x83, (byte) 0x65, - (byte) 0x5D, (byte) 0x23, (byte) 0xDC, (byte) 0xA3, (byte) 0xAD, (byte) 0x96, (byte) 0x1C, (byte) 0x62, (byte) 0xF3, (byte) 0x56, (byte) 0x20, (byte) 0x85, (byte) 0x52, (byte) 0xBB, (byte) 0x9E, (byte) 0xD5, (byte) 0x29, (byte) 0x07, (byte) 0x70, (byte) 0x96, (byte) 0x96, (byte) 0x6D, (byte) 0x67, (byte) 0x0C, (byte) 0x35, (byte) 0x4E, (byte) 0x4A, (byte) 0xBC, (byte) 0x98, (byte) 0x04, (byte) 0xF1, (byte) 0x74, (byte) 0x6C, (byte) 0x08, (byte) 0xCA, (byte) 0x18, (byte) 0x21, - (byte) 0x7C, (byte) 0x32, (byte) 0x90, (byte) 0x5E, (byte) 0x46, (byte) 0x2E, (byte) 0x36, (byte) 0xCE, (byte) 0x3B, (byte) 0xE3, (byte) 0x9E, (byte) 0x77, (byte) 0x2C, (byte) 0x18, (byte) 0x0E, (byte) 0x86, (byte) 0x03, (byte) 0x9B, (byte) 0x27, (byte) 0x83, (byte) 0xA2, (byte) 0xEC, (byte) 0x07, (byte) 0xA2, (byte) 0x8F, (byte) 0xB5, (byte) 0xC5, (byte) 0x5D, (byte) 0xF0, (byte) 0x6F, (byte) 0x4C, (byte) 0x52, (byte) 0xC9, (byte) 0xDE, (byte) 0x2B, (byte) 0xCB, (byte) 0xF6, - (byte) 0x95, (byte) 0x58, (byte) 0x17, (byte) 0x18, (byte) 0x39, (byte) 0x95, (byte) 0x49, (byte) 0x7C, (byte) 0xEA, (byte) 0x95, (byte) 0x6A, (byte) 0xE5, (byte) 0x15, (byte) 0xD2, (byte) 0x26, (byte) 0x18, (byte) 0x98, (byte) 0xFA, (byte) 0x05, (byte) 0x10, (byte) 0x15, (byte) 0x72, (byte) 0x8E, (byte) 0x5A, (byte) 0x8A, (byte) 0xAC, (byte) 0xAA, (byte) 0x68, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF }; - - private static final int SSH_MSG_KEXDH_INIT = 30; - private static final int SSH_MSG_KEXDH_REPLY = 31; - - static final int RSA = 0; - static final int DSS = 1; - private int type = 0; - - private int state; - - DH dh; - - byte[] V_S; - byte[] V_C; - byte[] I_S; - byte[] I_C; - - byte[] e; - - private Buffer buf; - private Packet packet; - - @Override - public void init(Session session, byte[] V_S, byte[] V_C, byte[] I_S, byte[] I_C) throws Exception { - this.session = session; - this.V_S = V_S; - this.V_C = V_C; - this.I_S = I_S; - this.I_C = I_C; - - try { - Class c = Class.forName(session.getConfig("sha-1")); - sha = (HASH) (c.newInstance()); - sha.init(); - } catch (Exception e) { - System.err.println(e); - } - - buf = new Buffer(); - packet = new Packet(buf); - - try { - Class c = Class.forName(session.getConfig("dh")); - dh = (DH) (c.newInstance()); - dh.init(); - } catch (Exception e) { - // System.err.println(e); - throw e; - } - - dh.setP(p); - dh.setG(g); - // The client responds with: - // byte SSH_MSG_KEXDH_INIT(30) - // mpint e <- g^x mod p - // x is a random number (1 < x < (p-1)/2) - - e = dh.getE(); - packet.reset(); - buf.putByte((byte) SSH_MSG_KEXDH_INIT); - buf.putMPInt(e); - - if (V_S == null) { // This is a really ugly hack for Session.checkKexes - // ;-( - return; - } - - session.write(packet); - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "SSH_MSG_KEXDH_INIT sent"); - JSch.getLogger().log(Logger.INFO, "expecting SSH_MSG_KEXDH_REPLY"); - } - - state = SSH_MSG_KEXDH_REPLY; - } - - @Override - public boolean next(Buffer _buf) throws Exception { - int i, j; - - switch (state) { - case SSH_MSG_KEXDH_REPLY: - // The server responds with: - // byte SSH_MSG_KEXDH_REPLY(31) - // string server public host key and certificates (K_S) - // mpint f - // string signature of H - j = _buf.getInt(); - j = _buf.getByte(); - j = _buf.getByte(); - if (j != 31) { - System.err.println("type: must be 31 " + j); - return false; - } - - K_S = _buf.getString(); - // K_S is server_key_blob, which includes .... - // string ssh-dss - // impint p of dsa - // impint q of dsa - // impint g of dsa - // impint pub_key of dsa - // System.err.print("K_S: "); //dump(K_S, 0, K_S.length); - byte[] f = _buf.getMPInt(); - byte[] sig_of_H = _buf.getString(); - - dh.setF(f); - K = normalize(dh.getK()); - - // The hash H is computed as the HASH hash of the concatenation of - // the - // following: - // string V_C, the client's version string (CR and NL excluded) - // string V_S, the server's version string (CR and NL excluded) - // string I_C, the payload of the client's SSH_MSG_KEXINIT - // string I_S, the payload of the server's SSH_MSG_KEXINIT - // string K_S, the host key - // mpint e, exchange value sent by the client - // mpint f, exchange value sent by the server - // mpint K, the shared secret - // This value is called the exchange hash, and it is used to - // authenti- - // cate the key exchange. - buf.reset(); - buf.putString(V_C); - buf.putString(V_S); - buf.putString(I_C); - buf.putString(I_S); - buf.putString(K_S); - buf.putMPInt(e); - buf.putMPInt(f); - buf.putMPInt(K); - byte[] foo = new byte[buf.getLength()]; - buf.getByte(foo); - sha.update(foo, 0, foo.length); - H = sha.digest(); - // System.err.print("H -> "); //dump(H, 0, H.length); - - i = 0; - j = 0; - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - String alg = Util.byte2str(K_S, i, j); - i += j; - - boolean result = false; - - if (alg.equals("ssh-rsa")) { - byte[] tmp; - byte[] ee; - byte[] n; - - type = RSA; - - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - ee = tmp; - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - n = tmp; - - SignatureRSA sig = null; - try { - Class c = Class.forName(session.getConfig("signature.rsa")); - sig = (SignatureRSA) (c.newInstance()); - sig.init(); - } catch (Exception e) { - System.err.println(e); - } - - sig.setPubKey(ee, n); - sig.update(H); - result = sig.verify(sig_of_H); - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "ssh_rsa_verify: signature " + result); - } - - } else if (alg.equals("ssh-dss")) { - byte[] q = null; - byte[] tmp; - byte[] p; - byte[] g; - - type = DSS; - - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - p = tmp; - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - q = tmp; - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - g = tmp; - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - f = tmp; - - SignatureDSA sig = null; - try { - Class c = Class.forName(session.getConfig("signature.dss")); - sig = (SignatureDSA) (c.newInstance()); - sig.init(); - } catch (Exception e) { - System.err.println(e); - } - sig.setPubKey(f, p, q, g); - sig.update(H); - result = sig.verify(sig_of_H); - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "ssh_dss_verify: signature " + result); - } - - } else { - System.err.println("unknown alg"); - } - state = STATE_END; - return result; - } - return false; - } - - @Override - public String getKeyType() { - if (type == DSS) { - return "DSA"; - } - return "RSA"; - } - - @Override - public int getState() { - return state; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/DHGEX.java b/src/autosaveworld/zlibs/com/jcraft/jsch/DHGEX.java deleted file mode 100644 index 313897a9..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/DHGEX.java +++ /dev/null @@ -1,345 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public class DHGEX extends KeyExchange { - - private static final int SSH_MSG_KEX_DH_GEX_GROUP = 31; - private static final int SSH_MSG_KEX_DH_GEX_INIT = 32; - private static final int SSH_MSG_KEX_DH_GEX_REPLY = 33; - private static final int SSH_MSG_KEX_DH_GEX_REQUEST = 34; - - static int min = 1024; - - // static int min=512; - static int preferred = 1024; - static int max = 1024; - - // static int preferred=1024; - // static int max=2000; - - static final int RSA = 0; - static final int DSS = 1; - private int type = 0; - - private int state; - - // com.jcraft.jsch.DH dh; - DH dh; - - byte[] V_S; - byte[] V_C; - byte[] I_S; - byte[] I_C; - - private Buffer buf; - private Packet packet; - - private byte[] p; - private byte[] g; - private byte[] e; - - // private byte[] f; - - @Override - public void init(Session session, byte[] V_S, byte[] V_C, byte[] I_S, byte[] I_C) throws Exception { - this.session = session; - this.V_S = V_S; - this.V_C = V_C; - this.I_S = I_S; - this.I_C = I_C; - - try { - Class c = Class.forName(session.getConfig("sha-1")); - sha = (HASH) (c.newInstance()); - sha.init(); - } catch (Exception e) { - System.err.println(e); - } - - buf = new Buffer(); - packet = new Packet(buf); - - try { - Class c = Class.forName(session.getConfig("dh")); - dh = (autosaveworld.zlibs.com.jcraft.jsch.DH) (c.newInstance()); - dh.init(); - } catch (Exception e) { - // System.err.println(e); - throw e; - } - - packet.reset(); - buf.putByte((byte) SSH_MSG_KEX_DH_GEX_REQUEST); - buf.putInt(min); - buf.putInt(preferred); - buf.putInt(max); - session.write(packet); - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "SSH_MSG_KEX_DH_GEX_REQUEST(" + min + "<" + preferred + "<" + max + ") sent"); - JSch.getLogger().log(Logger.INFO, "expecting SSH_MSG_KEX_DH_GEX_GROUP"); - } - - state = SSH_MSG_KEX_DH_GEX_GROUP; - } - - @Override - public boolean next(Buffer _buf) throws Exception { - int i, j; - switch (state) { - case SSH_MSG_KEX_DH_GEX_GROUP: - // byte SSH_MSG_KEX_DH_GEX_GROUP(31) - // mpint p, safe prime - // mpint g, generator for subgroup in GF (p) - _buf.getInt(); - _buf.getByte(); - j = _buf.getByte(); - if (j != SSH_MSG_KEX_DH_GEX_GROUP) { - System.err.println("type: must be SSH_MSG_KEX_DH_GEX_GROUP " + j); - return false; - } - - p = _buf.getMPInt(); - g = _buf.getMPInt(); - /* - * for(int iii=0; iii "); dump(H, 0, H.length); - - i = 0; - j = 0; - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - String alg = Util.byte2str(K_S, i, j); - i += j; - - boolean result = false; - if (alg.equals("ssh-rsa")) { - byte[] tmp; - byte[] ee; - byte[] n; - - type = RSA; - - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - ee = tmp; - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - n = tmp; - - // SignatureRSA sig=new SignatureRSA(); - // sig.init(); - - SignatureRSA sig = null; - try { - Class c = Class.forName(session.getConfig("signature.rsa")); - sig = (SignatureRSA) (c.newInstance()); - sig.init(); - } catch (Exception e) { - System.err.println(e); - } - - sig.setPubKey(ee, n); - sig.update(H); - result = sig.verify(sig_of_H); - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "ssh_rsa_verify: signature " + result); - } - - } else if (alg.equals("ssh-dss")) { - byte[] q = null; - byte[] tmp; - - type = DSS; - - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - p = tmp; - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - q = tmp; - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - g = tmp; - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - f = tmp; - - // SignatureDSA sig=new SignatureDSA(); - // sig.init(); - - SignatureDSA sig = null; - try { - Class c = Class.forName(session.getConfig("signature.dss")); - sig = (SignatureDSA) (c.newInstance()); - sig.init(); - } catch (Exception e) { - System.err.println(e); - } - - sig.setPubKey(f, p, q, g); - sig.update(H); - result = sig.verify(sig_of_H); - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "ssh_dss_verify: signature " + result); - } - - } else { - System.err.println("unknown alg"); - } - state = STATE_END; - return result; - } - return false; - } - - @Override - public String getKeyType() { - if (type == DSS) { - return "DSA"; - } - return "RSA"; - } - - @Override - public int getState() { - return state; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/DHGEX256.java b/src/autosaveworld/zlibs/com/jcraft/jsch/DHGEX256.java deleted file mode 100644 index 647bb465..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/DHGEX256.java +++ /dev/null @@ -1,345 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public class DHGEX256 extends KeyExchange { - - private static final int SSH_MSG_KEX_DH_GEX_GROUP = 31; - private static final int SSH_MSG_KEX_DH_GEX_INIT = 32; - private static final int SSH_MSG_KEX_DH_GEX_REPLY = 33; - private static final int SSH_MSG_KEX_DH_GEX_REQUEST = 34; - - static int min = 1024; - - // static int min=512; - static int preferred = 1024; - static int max = 1024; - - // static int preferred=1024; - // static int max=2000; - - static final int RSA = 0; - static final int DSS = 1; - private int type = 0; - - private int state; - - // com.jcraft.jsch.DH dh; - DH dh; - - byte[] V_S; - byte[] V_C; - byte[] I_S; - byte[] I_C; - - private Buffer buf; - private Packet packet; - - private byte[] p; - private byte[] g; - private byte[] e; - - // private byte[] f; - - @Override - public void init(Session session, byte[] V_S, byte[] V_C, byte[] I_S, byte[] I_C) throws Exception { - this.session = session; - this.V_S = V_S; - this.V_C = V_C; - this.I_S = I_S; - this.I_C = I_C; - - try { - Class c = Class.forName(session.getConfig("sha-256")); - sha = (HASH) (c.newInstance()); - sha.init(); - } catch (Exception e) { - System.err.println(e); - } - - buf = new Buffer(); - packet = new Packet(buf); - - try { - Class c = Class.forName(session.getConfig("dh")); - dh = (autosaveworld.zlibs.com.jcraft.jsch.DH) (c.newInstance()); - dh.init(); - } catch (Exception e) { - // System.err.println(e); - throw e; - } - - packet.reset(); - buf.putByte((byte) SSH_MSG_KEX_DH_GEX_REQUEST); - buf.putInt(min); - buf.putInt(preferred); - buf.putInt(max); - session.write(packet); - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "SSH_MSG_KEX_DH_GEX_REQUEST(" + min + "<" + preferred + "<" + max + ") sent"); - JSch.getLogger().log(Logger.INFO, "expecting SSH_MSG_KEX_DH_GEX_GROUP"); - } - - state = SSH_MSG_KEX_DH_GEX_GROUP; - } - - @Override - public boolean next(Buffer _buf) throws Exception { - int i, j; - switch (state) { - case SSH_MSG_KEX_DH_GEX_GROUP: - // byte SSH_MSG_KEX_DH_GEX_GROUP(31) - // mpint p, safe prime - // mpint g, generator for subgroup in GF (p) - _buf.getInt(); - _buf.getByte(); - j = _buf.getByte(); - if (j != SSH_MSG_KEX_DH_GEX_GROUP) { - System.err.println("type: must be SSH_MSG_KEX_DH_GEX_GROUP " + j); - return false; - } - - p = _buf.getMPInt(); - g = _buf.getMPInt(); - /* - * for(int iii=0; iii "); dump(H, 0, H.length); - - i = 0; - j = 0; - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - String alg = Util.byte2str(K_S, i, j); - i += j; - - boolean result = false; - if (alg.equals("ssh-rsa")) { - byte[] tmp; - byte[] ee; - byte[] n; - - type = RSA; - - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - ee = tmp; - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - n = tmp; - - // SignatureRSA sig=new SignatureRSA(); - // sig.init(); - - SignatureRSA sig = null; - try { - Class c = Class.forName(session.getConfig("signature.rsa")); - sig = (SignatureRSA) (c.newInstance()); - sig.init(); - } catch (Exception e) { - System.err.println(e); - } - - sig.setPubKey(ee, n); - sig.update(H); - result = sig.verify(sig_of_H); - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "ssh_rsa_verify: signature " + result); - } - - } else if (alg.equals("ssh-dss")) { - byte[] q = null; - byte[] tmp; - - type = DSS; - - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - p = tmp; - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - q = tmp; - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - g = tmp; - j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); - tmp = new byte[j]; - System.arraycopy(K_S, i, tmp, 0, j); - i += j; - f = tmp; - - // SignatureDSA sig=new SignatureDSA(); - // sig.init(); - - SignatureDSA sig = null; - try { - Class c = Class.forName(session.getConfig("signature.dss")); - sig = (SignatureDSA) (c.newInstance()); - sig.init(); - } catch (Exception e) { - System.err.println(e); - } - - sig.setPubKey(f, p, q, g); - sig.update(H); - result = sig.verify(sig_of_H); - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "ssh_dss_verify: signature " + result); - } - - } else { - System.err.println("unknown alg"); - } - state = STATE_END; - return result; - } - return false; - } - - @Override - public String getKeyType() { - if (type == DSS) { - return "DSA"; - } - return "RSA"; - } - - @Override - public int getState() { - return state; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/HASH.java b/src/autosaveworld/zlibs/com/jcraft/jsch/HASH.java deleted file mode 100644 index 1e9e0380..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/HASH.java +++ /dev/null @@ -1,42 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public interface HASH { - - void init() throws Exception; - - int getBlockSize(); - - void update(byte[] foo, int start, int len) throws Exception; - - byte[] digest() throws Exception; - -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/IO.java b/src/autosaveworld/zlibs/com/jcraft/jsch/IO.java deleted file mode 100644 index b0a1c6df..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/IO.java +++ /dev/null @@ -1,113 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -public class IO { - - InputStream in; - OutputStream out; - - private boolean in_dontclose = false; - private boolean out_dontclose = false; - - void setOutputStream(OutputStream out) { - this.out = out; - } - - void setOutputStream(OutputStream out, boolean dontclose) { - out_dontclose = dontclose; - setOutputStream(out); - } - - void setInputStream(InputStream in) { - this.in = in; - } - - void setInputStream(InputStream in, boolean dontclose) { - in_dontclose = dontclose; - setInputStream(in); - } - - public void put(Packet p) throws IOException, java.net.SocketException { - out.write(p.buffer.buffer, 0, p.buffer.index); - out.flush(); - } - - void put(byte[] array, int begin, int length) throws IOException { - out.write(array, begin, length); - out.flush(); - } - - int getByte() throws IOException { - return in.read(); - } - - void getByte(byte[] array) throws IOException { - getByte(array, 0, array.length); - } - - void getByte(byte[] array, int begin, int length) throws IOException { - do { - int completed = in.read(array, begin, length); - if (completed < 0) { - throw new IOException("End of IO Stream Read"); - } - begin += completed; - length -= completed; - } while (length > 0); - } - - void out_close() { - try { - if ((out != null) && !out_dontclose) { - out.close(); - } - out = null; - } catch (Exception ee) { - } - } - - public void close() { - try { - if ((in != null) && !in_dontclose) { - in.close(); - } - in = null; - } catch (Exception ee) { - } - - out_close(); - } - -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/JSch.java b/src/autosaveworld/zlibs/com/jcraft/jsch/JSch.java deleted file mode 100644 index 03fecc77..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/JSch.java +++ /dev/null @@ -1,243 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public class JSch { - /** - * The version number. - */ - public static final String VERSION = "0.1.51"; - - static java.util.Hashtable config = new java.util.Hashtable(); - static { - config.put("kex", "diffie-hellman-group1-sha1,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha1"); - config.put("server_host_key", "ssh-rsa,ssh-dss"); - - config.put("cipher.s2c", "aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc,aes192-cbc,aes256-cbc"); - config.put("cipher.c2s", "aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc,aes192-cbc,aes256-cbc"); - - config.put("mac.s2c", "hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96"); - config.put("mac.c2s", "hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96"); - config.put("compression.s2c", "none"); - config.put("compression.c2s", "none"); - - config.put("lang.s2c", ""); - config.put("lang.c2s", ""); - - config.put("compression_level", "6"); - - config.put("diffie-hellman-group-exchange-sha1", DHGEX.class.getName()); - config.put("diffie-hellman-group1-sha1", DHG1.class.getName()); - config.put("diffie-hellman-group14-sha1", DHG14.class.getName()); - config.put("diffie-hellman-group-exchange-sha256", DHGEX256.class.getName()); - - config.put("dh", autosaveworld.zlibs.com.jcraft.jsch.jce.DH.class.getName()); - config.put("3des-cbc", autosaveworld.zlibs.com.jcraft.jsch.jce.TripleDESCBC.class.getName()); - config.put("blowfish-cbc", autosaveworld.zlibs.com.jcraft.jsch.jce.cipher.BlowfishCBC.class.getName()); - config.put("hmac-sha1", autosaveworld.zlibs.com.jcraft.jsch.jce.mac.HMACSHA1.class.getName()); - config.put("hmac-sha1-96", autosaveworld.zlibs.com.jcraft.jsch.jce.mac.HMACSHA196.class.getName()); - config.put("hmac-sha2-256", autosaveworld.zlibs.com.jcraft.jsch.jce.mac.HMACSHA256.class.getName()); - - config.put("hmac-md5", autosaveworld.zlibs.com.jcraft.jsch.jce.mac.HMACMD5.class.getName()); - config.put("hmac-md5-96", autosaveworld.zlibs.com.jcraft.jsch.jce.mac.HMACMD596.class.getName()); - config.put("sha-1", autosaveworld.zlibs.com.jcraft.jsch.jce.hash.SHA1.class.getName()); - config.put("sha-256", autosaveworld.zlibs.com.jcraft.jsch.jce.hash.SHA256.class.getName()); - config.put("md5", autosaveworld.zlibs.com.jcraft.jsch.jce.hash.MD5.class.getName()); - config.put("signature.dss", autosaveworld.zlibs.com.jcraft.jsch.jce.SignatureDSA.class.getName()); - config.put("signature.rsa", autosaveworld.zlibs.com.jcraft.jsch.jce.SignatureRSA.class.getName()); - config.put("random", autosaveworld.zlibs.com.jcraft.jsch.jce.Random.class.getName()); - - config.put("none", autosaveworld.zlibs.com.jcraft.jsch.CipherNone.class.getName()); - - config.put("aes128-cbc", autosaveworld.zlibs.com.jcraft.jsch.jce.cipher.AES128CBC.class.getName()); - config.put("aes192-cbc", autosaveworld.zlibs.com.jcraft.jsch.jce.cipher.AES192CBC.class.getName()); - config.put("aes256-cbc", autosaveworld.zlibs.com.jcraft.jsch.jce.cipher.AES256CBC.class.getName()); - - config.put("aes128-ctr", autosaveworld.zlibs.com.jcraft.jsch.jce.cipher.AES128CTR.class.getName()); - config.put("aes192-ctr", autosaveworld.zlibs.com.jcraft.jsch.jce.cipher.AES192CTR.class.getName()); - config.put("aes256-ctr", autosaveworld.zlibs.com.jcraft.jsch.jce.cipher.AES256CTR.class.getName()); - config.put("3des-ctr", autosaveworld.zlibs.com.jcraft.jsch.jce.TripleDESCTR.class.getName()); - config.put("arcfour", autosaveworld.zlibs.com.jcraft.jsch.jce.cipher.ARCFOUR.class.getName()); - config.put("arcfour128", autosaveworld.zlibs.com.jcraft.jsch.jce.cipher.ARCFOUR128.class.getName()); - config.put("arcfour256", autosaveworld.zlibs.com.jcraft.jsch.jce.cipher.ARCFOUR256.class.getName()); - - config.put("userauth.none", autosaveworld.zlibs.com.jcraft.jsch.UserAuthNone.class.getName()); - config.put("userauth.password", autosaveworld.zlibs.com.jcraft.jsch.UserAuthPassword.class.getName()); - - config.put("pbkdf", autosaveworld.zlibs.com.jcraft.jsch.jce.PBKDF.class.getName()); - - config.put("StrictHostKeyChecking", "no"); - config.put("HashKnownHosts", "no"); - - config.put("PreferredAuthentications", "password"); - - config.put("CheckCiphers", "aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,3des-ctr,arcfour,arcfour128,arcfour256"); - config.put("CheckKexes", "diffie-hellman-group14-sha1"); - - config.put("MaxAuthTries", "6"); - config.put("ClearAllForwardings", "no"); - } - - private java.util.Vector sessionPool = new java.util.Vector(); - - private static final Logger DEVNULL = new Logger() { - @Override - public boolean isEnabled(int level) { - return false; - } - - @Override - public void log(int level, String message) { - } - }; - static Logger logger = DEVNULL; - - /** - * Instantiates the Session object with host. The user name and port number will be retrieved from ConfigRepository. If user name is not given, the system property "user.name" will be referred. - * - * @param host - * hostname - * - * @throws JSchException - * if username or host are invalid. - * - * @return the instance of Session class. - * - * @see #getSession(String username, String host, int port) - * @see autosaveworld.zlibs.com.jcraft.jsch.Session - * @see autosaveworld.zlibs.com.jcraft.jsch.ConfigRepository - */ - public Session getSession(String host) throws JSchException { - return getSession(null, host, 22); - } - - /** - * Instantiates the Session object with username and host. The TCP port 22 will be used in making the connection. Note that the TCP connection must not be established until Session#connect(). - * - * @param username - * user name - * @param host - * hostname - * - * @throws JSchException - * if username or host are invalid. - * - * @return the instance of Session class. - * - * @see #getSession(String username, String host, int port) - * @see autosaveworld.zlibs.com.jcraft.jsch.Session - */ - public Session getSession(String username, String host) throws JSchException { - return getSession(username, host, 22); - } - - /** - * Instantiates the Session object with given username, host and port. Note that the TCP connection must not be established until Session#connect(). - * - * @param username - * user name - * @param host - * hostname - * @param port - * port number - * - * @throws JSchException - * if username or host are invalid. - * - * @return the instance of Session class. - * - * @see #getSession(String username, String host, int port) - * @see autosaveworld.zlibs.com.jcraft.jsch.Session - */ - public Session getSession(String username, String host, int port) throws JSchException { - if (host == null) { - throw new JSchException("host must not be null."); - } - Session s = new Session(this, username, host, port); - return s; - } - - protected void addSession(Session session) { - synchronized (sessionPool) { - sessionPool.addElement(session); - } - } - - protected boolean removeSession(Session session) { - synchronized (sessionPool) { - return sessionPool.remove(session); - } - } - - /** - * Returns the config value for the specified key. - * - * @param key - * key for the configuration. - * @return config value - */ - public static String getConfig(String key) { - synchronized (config) { - return (config.get(key)); - } - } - - /** - * Sets or Overrides the configuration. - * - * @param key - * key for the configuration - * @param value - * value for the configuration - */ - public static void setConfig(String key, String value) { - config.put(key, value); - } - - /** - * Sets the logger - * - * @param logger - * logger - * - * @see autosaveworld.zlibs.com.jcraft.jsch.Logger - */ - public static void setLogger(Logger logger) { - if (logger == null) { - logger = DEVNULL; - } - JSch.logger = logger; - } - - static Logger getLogger() { - return logger; - } - -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/JSchAuthCancelException.java b/src/autosaveworld/zlibs/com/jcraft/jsch/JSchAuthCancelException.java deleted file mode 100644 index ac5d1971..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/JSchAuthCancelException.java +++ /dev/null @@ -1,51 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -class JSchAuthCancelException extends JSchException { - - private static final long serialVersionUID = 3204965907117900987L; - - String method; - - JSchAuthCancelException() { - super(); - } - - JSchAuthCancelException(String s) { - super(s); - method = s; - } - - public String getMethod() { - return method; - } - -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/JSchException.java b/src/autosaveworld/zlibs/com/jcraft/jsch/JSchException.java deleted file mode 100644 index 320451bf..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/JSchException.java +++ /dev/null @@ -1,56 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public class JSchException extends Exception { - - private static final long serialVersionUID = -1319309923966731989L; - - private Throwable cause = null; - - public JSchException() { - super(); - } - - public JSchException(String s) { - super(s); - } - - public JSchException(String s, Throwable e) { - super(s); - cause = e; - } - - @Override - public Throwable getCause() { - return cause; - } - -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/JSchPartialAuthException.java b/src/autosaveworld/zlibs/com/jcraft/jsch/JSchPartialAuthException.java deleted file mode 100644 index ae3ae2db..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/JSchPartialAuthException.java +++ /dev/null @@ -1,51 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -class JSchPartialAuthException extends JSchException { - - private static final long serialVersionUID = -378849862323360367L; - - String methods; - - public JSchPartialAuthException() { - super(); - } - - public JSchPartialAuthException(String s) { - super(s); - methods = s; - } - - public String getMethods() { - return methods; - } - -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/KeyExchange.java b/src/autosaveworld/zlibs/com/jcraft/jsch/KeyExchange.java deleted file mode 100644 index e30e3c60..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/KeyExchange.java +++ /dev/null @@ -1,187 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public abstract class KeyExchange { - - static final int PROPOSAL_KEX_ALGS = 0; - static final int PROPOSAL_SERVER_HOST_KEY_ALGS = 1; - static final int PROPOSAL_ENC_ALGS_CTOS = 2; - static final int PROPOSAL_ENC_ALGS_STOC = 3; - static final int PROPOSAL_MAC_ALGS_CTOS = 4; - static final int PROPOSAL_MAC_ALGS_STOC = 5; - static final int PROPOSAL_COMP_ALGS_CTOS = 6; - static final int PROPOSAL_COMP_ALGS_STOC = 7; - static final int PROPOSAL_LANG_CTOS = 8; - static final int PROPOSAL_LANG_STOC = 9; - static final int PROPOSAL_MAX = 10; - - // static String kex_algs="diffie-hellman-group-exchange-sha1"+ - // ",diffie-hellman-group1-sha1"; - - // static String kex="diffie-hellman-group-exchange-sha1"; - static String kex = "diffie-hellman-group1-sha1"; - static String server_host_key = "ssh-rsa,ssh-dss"; - static String enc_c2s = "blowfish-cbc"; - static String enc_s2c = "blowfish-cbc"; - static String mac_c2s = "hmac-md5"; // hmac-md5,hmac-sha1,hmac-ripemd160, - // hmac-sha1-96,hmac-md5-96 - static String mac_s2c = "hmac-md5"; - // static String comp_c2s="none"; // zlib - // static String comp_s2c="none"; - static String lang_c2s = ""; - static String lang_s2c = ""; - - public static final int STATE_END = 0; - - protected Session session = null; - protected HASH sha = null; - protected byte[] K = null; - protected byte[] H = null; - protected byte[] K_S = null; - - public abstract void init(Session session, byte[] V_S, byte[] V_C, byte[] I_S, byte[] I_C) throws Exception; - - public abstract boolean next(Buffer buf) throws Exception; - - public abstract String getKeyType(); - - public abstract int getState(); - - /* - * void dump(byte[] foo){ for(int i=0; iclient" + " " + guess[PROPOSAL_ENC_ALGS_STOC] + " " + guess[PROPOSAL_MAC_ALGS_STOC] + " " + guess[PROPOSAL_COMP_ALGS_STOC]); - JSch.getLogger().log(Logger.INFO, "kex: client->server" + " " + guess[PROPOSAL_ENC_ALGS_CTOS] + " " + guess[PROPOSAL_MAC_ALGS_CTOS] + " " + guess[PROPOSAL_COMP_ALGS_CTOS]); - } - - return guess; - } - - public String getFingerPrint() { - HASH hash = null; - try { - Class c = Class.forName(session.getConfig("md5")); - hash = (HASH) (c.newInstance()); - } catch (Exception e) { - System.err.println("getFingerPrint: " + e); - } - return Util.getFingerPrint(hash, getHostKey()); - } - - byte[] getK() { - return K; - } - - byte[] getH() { - return H; - } - - HASH getHash() { - return sha; - } - - byte[] getHostKey() { - return K_S; - } - - /* - * It seems JCE included in Oracle's Java7u6(and later) has suddenly changed its behavior. The secrete generated by KeyAgreement#generateSecret() may start with 0, even if it is a positive value. - */ - protected byte[] normalize(byte[] secret) { - if ((secret.length > 1) && (secret[0] == 0) && ((secret[1] & 0x80) == 0)) { - byte[] tmp = new byte[secret.length - 1]; - System.arraycopy(secret, 1, tmp, 0, tmp.length); - return normalize(tmp); - } else { - return secret; - } - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/Logger.java b/src/autosaveworld/zlibs/com/jcraft/jsch/Logger.java deleted file mode 100644 index 40763181..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/Logger.java +++ /dev/null @@ -1,47 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2006-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public interface Logger { - - public final int DEBUG = 0; - public final int INFO = 1; - public final int WARN = 2; - public final int ERROR = 3; - public final int FATAL = 4; - - public boolean isEnabled(int level); - - public void log(int level, String message); - - /* - * public final Logger SIMPLE_LOGGER=new Logger(){ public boolean isEnabled(int level){return true;} public void log(int level, String message){System.err.println(message);} }; final Logger DEVNULL=new Logger(){ public boolean isEnabled(int level){return false;} public void log(int level, String message){} }; - */ -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/MAC.java b/src/autosaveworld/zlibs/com/jcraft/jsch/MAC.java deleted file mode 100644 index f444265d..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/MAC.java +++ /dev/null @@ -1,44 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public interface MAC { - String getName(); - - int getBlockSize(); - - void init(byte[] key) throws Exception; - - void update(byte[] foo, int start, int len); - - void update(int foo); - - void doFinal(byte[] buf, int offset); -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/PBKDF.java b/src/autosaveworld/zlibs/com/jcraft/jsch/PBKDF.java deleted file mode 100644 index b06dda7f..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/PBKDF.java +++ /dev/null @@ -1,34 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2013-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public interface PBKDF { - byte[] getKey(byte[] pass, byte[] salt, int iteration, int size); -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/Packet.java b/src/autosaveworld/zlibs/com/jcraft/jsch/Packet.java deleted file mode 100644 index 1c0a3ad3..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/Packet.java +++ /dev/null @@ -1,118 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public class Packet { - - private static Random random = null; - - static void setRandom(Random foo) { - random = foo; - } - - Buffer buffer; - byte[] ba4 = new byte[4]; - - public Packet(Buffer buffer) { - this.buffer = buffer; - } - - public void reset() { - buffer.index = 5; - } - - void padding(int bsize) { - int len = buffer.index; - int pad = (-len) & (bsize - 1); - if (pad < bsize) { - pad += bsize; - } - len = (len + pad) - 4; - ba4[0] = (byte) (len >>> 24); - ba4[1] = (byte) (len >>> 16); - ba4[2] = (byte) (len >>> 8); - ba4[3] = (byte) (len); - System.arraycopy(ba4, 0, buffer.buffer, 0, 4); - buffer.buffer[4] = (byte) pad; - synchronized (random) { - random.fill(buffer.buffer, buffer.index, pad); - } - buffer.skip(pad); - // buffer.putPad(pad); - /* - * for(int i=0; i config = null; - - private UserInfo userinfo; - - private int serverAliveInterval = 0; - private int serverAliveCountMax = 1; - - protected boolean daemon_thread = false; - - private long kex_start_time = 0L; - - int max_auth_tries = 6; - int auth_failures = 0; - - String host = "127.0.0.1"; - int port = 22; - - String username = null; - byte[] password = null; - - JSch jsch; - - Session(JSch jsch, String username, String host, int port) throws JSchException { - super(); - this.jsch = jsch; - buf = new Buffer(); - packet = new Packet(buf); - this.username = username; - this.host = host; - this.port = port; - - if (this.username == null) { - try { - this.username = (String) (System.getProperties().get("user.name")); - } catch (SecurityException e) { - // ignore e - } - } - - if (this.username == null) { - throw new JSchException("username is not given."); - } - } - - public void connect() throws JSchException { - connect(timeout); - } - - @SuppressWarnings("resource") - public void connect(int connectTimeout) throws JSchException { - if (isConnected) { - throw new JSchException("session is already connected"); - } - - io = new IO(); - if (random == null) { - try { - Class c = Class.forName(getConfig("random")); - random = (Random) (c.newInstance()); - } catch (Exception e) { - throw new JSchException(e.toString(), e); - } - } - Packet.setRandom(random); - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "Connecting to " + host + " port " + port); - } - - try { - int i, j; - - InputStream in; - OutputStream out; - if (socket_factory == null) { - socket = Util.createSocket(host, port, connectTimeout); - in = socket.getInputStream(); - out = socket.getOutputStream(); - } else { - socket = socket_factory.createSocket(host, port); - in = socket_factory.getInputStream(socket); - out = socket_factory.getOutputStream(socket); - } - // if(timeout>0){ socket.setSoTimeout(timeout); } - socket.setTcpNoDelay(true); - io.setInputStream(in); - io.setOutputStream(out); - - if ((connectTimeout > 0) && (socket != null)) { - socket.setSoTimeout(connectTimeout); - } - - isConnected = true; - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "Connection established"); - } - - jsch.addSession(this); - - { - // Some Cisco devices will miss to read '\n' if it is sent - // separately. - byte[] foo = new byte[V_C.length + 1]; - System.arraycopy(V_C, 0, foo, 0, V_C.length); - foo[foo.length - 1] = (byte) '\n'; - io.put(foo, 0, foo.length); - } - - while (true) { - i = 0; - j = 0; - while (i < buf.buffer.length) { - j = io.getByte(); - if (j < 0) { - break; - } - buf.buffer[i] = (byte) j; - i++; - if (j == 10) { - break; - } - } - if (j < 0) { - throw new JSchException("connection is closed by foreign host"); - } - - if (buf.buffer[i - 1] == 10) { // 0x0a - i--; - if ((i > 0) && (buf.buffer[i - 1] == 13)) { // 0x0d - i--; - } - } - - if ((i <= 3) || ((i != buf.buffer.length) && ((buf.buffer[0] != 'S') || (buf.buffer[1] != 'S') || (buf.buffer[2] != 'H') || (buf.buffer[3] != '-')))) { - // It must not start with 'SSH-' - // System.err.println(new String(buf.buffer, 0, i); - continue; - } - - if ((i == buf.buffer.length) || (i < 7) || // SSH-1.99 or SSH-2.0 - ((buf.buffer[4] == '1') && (buf.buffer[6] != '9')) // SSH-1.5 - ) { - throw new JSchException("invalid server's version string"); - } - break; - } - - V_S = new byte[i]; - System.arraycopy(buf.buffer, 0, V_S, 0, i); - // System.err.println("V_S: ("+i+") ["+new String(V_S)+"]"); - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "Remote version string: " + Util.byte2str(V_S)); - JSch.getLogger().log(Logger.INFO, "Local version string: " + Util.byte2str(V_C)); - } - - send_kexinit(); - - buf = read(buf); - if (buf.getCommand() != SSH_MSG_KEXINIT) { - in_kex = false; - throw new JSchException("invalid protocol: " + buf.getCommand()); - } - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "SSH_MSG_KEXINIT received"); - } - - KeyExchange kex = receive_kexinit(buf); - - while (true) { - buf = read(buf); - if (kex.getState() == buf.getCommand()) { - kex_start_time = System.currentTimeMillis(); - boolean result = kex.next(buf); - if (!result) { - // System.err.println("verify: "+result); - in_kex = false; - throw new JSchException("verify: " + result); - } - } else { - in_kex = false; - throw new JSchException("invalid protocol(kex): " + buf.getCommand()); - } - if (kex.getState() == KeyExchange.STATE_END) { - break; - } - } - - send_newkeys(); - - // receive SSH_MSG_NEWKEYS(21) - buf = read(buf); - // System.err.println("read: 21 ? "+buf.getCommand()); - if (buf.getCommand() == SSH_MSG_NEWKEYS) { - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "SSH_MSG_NEWKEYS received"); - } - - receive_newkeys(buf, kex); - } else { - in_kex = false; - throw new JSchException("invalid protocol(newkyes): " + buf.getCommand()); - } - - try { - String s = getConfig("MaxAuthTries"); - if (s != null) { - max_auth_tries = Integer.parseInt(s); - } - } catch (NumberFormatException e) { - throw new JSchException("MaxAuthTries: " + getConfig("MaxAuthTries"), e); - } - - boolean auth = false; - boolean auth_cancel = false; - - UserAuth ua = null; - try { - Class c = Class.forName(getConfig("userauth.none")); - ua = (UserAuth) (c.newInstance()); - } catch (Exception e) { - throw new JSchException(e.toString(), e); - } - - auth = ua.start(this); - - String cmethods = getConfig("PreferredAuthentications"); - - String[] cmethoda = Util.split(cmethods, ","); - - String smethods = null; - if (!auth) { - smethods = ((UserAuthNone) ua).getMethods(); - if (smethods != null) { - smethods = smethods.toLowerCase(); - } else { - // methods: publickey,password,keyboard-interactive - // smethods="publickey,password,keyboard-interactive"; - smethods = cmethods; - } - } - - String[] smethoda = Util.split(smethods, ","); - - int methodi = 0; - - loop: while (true) { - - while (!auth && (cmethoda != null) && (methodi < cmethoda.length)) { - - String method = cmethoda[methodi++]; - boolean acceptable = false; - for (int k = 0; k < smethoda.length; k++) { - if (smethoda[k].equals(method)) { - acceptable = true; - break; - } - } - if (!acceptable) { - continue; - } - - // System.err.println(" method: "+method); - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - String str = "Authentications that can continue: "; - for (int k = methodi - 1; k < cmethoda.length; k++) { - str += cmethoda[k]; - if ((k + 1) < cmethoda.length) { - str += ","; - } - } - JSch.getLogger().log(Logger.INFO, str); - JSch.getLogger().log(Logger.INFO, "Next authentication method: " + method); - } - - ua = null; - try { - Class c = null; - if (getConfig("userauth." + method) != null) { - c = Class.forName(getConfig("userauth." + method)); - ua = (UserAuth) (c.newInstance()); - } - } catch (Exception e) { - if (JSch.getLogger().isEnabled(Logger.WARN)) { - JSch.getLogger().log(Logger.WARN, "failed to load " + method + " method"); - } - } - - if (ua != null) { - auth_cancel = false; - try { - auth = ua.start(this); - if (auth && JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "Authentication succeeded (" + method + ")."); - } - } catch (JSchAuthCancelException ee) { - auth_cancel = true; - } catch (JSchPartialAuthException ee) { - String tmp = smethods; - smethods = ee.getMethods(); - smethoda = Util.split(smethods, ","); - if (!tmp.equals(smethods)) { - methodi = 0; - } - // System.err.println("PartialAuth: "+methods); - auth_cancel = false; - continue loop; - } catch (RuntimeException ee) { - throw ee; - } catch (JSchException ee) { - throw ee; - } catch (Exception ee) { - // System.err.println("ee: "+ee); // - // SSH_MSG_DISCONNECT: 2 Too many authentication - // failures - if (JSch.getLogger().isEnabled(Logger.WARN)) { - JSch.getLogger().log(Logger.WARN, "an exception during authentication\n" + ee.toString()); - } - break loop; - } - } - } - break; - } - - if (!auth) { - if (auth_failures >= max_auth_tries) { - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "Login trials exceeds " + max_auth_tries); - } - } - if (auth_cancel) { - throw new JSchException("Auth cancel"); - } - throw new JSchException("Auth fail"); - } - - if ((socket != null) && ((connectTimeout > 0) || (timeout > 0))) { - socket.setSoTimeout(timeout); - } - - isAuthed = true; - - synchronized (lock) { - if (isConnected) { - connectThread = new Thread(this); - connectThread.setName("Connect thread " + host + " session"); - if (daemon_thread) { - connectThread.setDaemon(daemon_thread); - } - connectThread.start(); - } else { - // The session has been already down and - // we don't have to start new thread. - } - } - } catch (Exception e) { - in_kex = false; - try { - if (isConnected) { - String message = e.toString(); - packet.reset(); - buf.checkFreeSize(1 + (4 * 3) + message.length() + 2 + buffer_margin); - buf.putByte((byte) SSH_MSG_DISCONNECT); - buf.putInt(3); - buf.putString(Util.str2byte(message)); - buf.putString(Util.str2byte("en")); - write(packet); - } - } catch (Exception ee) { - } - try { - disconnect(); - } catch (Exception ee) { - } - isConnected = false; - // e.printStackTrace(); - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } - if (e instanceof JSchException) { - throw (JSchException) e; - } - throw new JSchException("Session.connect: " + e); - } finally { - Util.bzero(password); - password = null; - } - } - - private KeyExchange receive_kexinit(Buffer buf) throws Exception { - int j = buf.getInt(); - if (j != buf.getLength()) { // packet was compressed and - buf.getByte(); // j is the size of deflated packet. - I_S = new byte[buf.index - 5]; - } else { - I_S = new byte[j - 1 - buf.getByte()]; - } - System.arraycopy(buf.buffer, buf.s, I_S, 0, I_S.length); - - if (!in_kex) { // We are in rekeying activated by the remote! - send_kexinit(); - } - - guess = KeyExchange.guess(I_S, I_C); - if (guess == null) { - throw new JSchException("Algorithm negotiation fail"); - } - - if (!isAuthed && (guess[KeyExchange.PROPOSAL_ENC_ALGS_CTOS].equals("none") || (guess[KeyExchange.PROPOSAL_ENC_ALGS_STOC].equals("none")))) { - throw new JSchException("NONE Cipher should not be chosen before authentification is successed."); - } - - KeyExchange kex = null; - try { - Class c = Class.forName(getConfig(guess[KeyExchange.PROPOSAL_KEX_ALGS])); - kex = (KeyExchange) (c.newInstance()); - } catch (Exception e) { - throw new JSchException(e.toString(), e); - } - - kex.init(this, V_S, V_C, I_S, I_C); - return kex; - } - - private boolean in_kex = false; - - public void rekey() throws Exception { - send_kexinit(); - } - - private void send_kexinit() throws Exception { - if (in_kex) { - return; - } - - String cipherc2s = getConfig("cipher.c2s"); - String ciphers2c = getConfig("cipher.s2c"); - - String[] not_available_ciphers = checkCiphers(getConfig("CheckCiphers")); - if ((not_available_ciphers != null) && (not_available_ciphers.length > 0)) { - cipherc2s = Util.diffString(cipherc2s, not_available_ciphers); - ciphers2c = Util.diffString(ciphers2c, not_available_ciphers); - if ((cipherc2s == null) || (ciphers2c == null)) { - throw new JSchException("There are not any available ciphers."); - } - } - - String kex = getConfig("kex"); - String[] not_available_kexes = checkKexes(getConfig("CheckKexes")); - if ((not_available_kexes != null) && (not_available_kexes.length > 0)) { - kex = Util.diffString(kex, not_available_kexes); - if (kex == null) { - throw new JSchException("There are not any available kexes."); - } - } - - in_kex = true; - kex_start_time = System.currentTimeMillis(); - - // byte SSH_MSG_KEXINIT(20) - // byte[16] cookie (random bytes) - // string kex_algorithms - // string server_host_key_algorithms - // string encryption_algorithms_client_to_server - // string encryption_algorithms_server_to_client - // string mac_algorithms_client_to_server - // string mac_algorithms_server_to_client - // string compression_algorithms_client_to_server - // string compression_algorithms_server_to_client - // string languages_client_to_server - // string languages_server_to_client - Buffer buf = new Buffer(); // send_kexinit may be invoked - Packet packet = new Packet(buf); // by user thread. - packet.reset(); - buf.putByte((byte) SSH_MSG_KEXINIT); - synchronized (random) { - random.fill(buf.buffer, buf.index, 16); - buf.skip(16); - } - buf.putString(Util.str2byte(kex)); - buf.putString(Util.str2byte(getConfig("server_host_key"))); - buf.putString(Util.str2byte(cipherc2s)); - buf.putString(Util.str2byte(ciphers2c)); - buf.putString(Util.str2byte(getConfig("mac.c2s"))); - buf.putString(Util.str2byte(getConfig("mac.s2c"))); - buf.putString(Util.str2byte(getConfig("compression.c2s"))); - buf.putString(Util.str2byte(getConfig("compression.s2c"))); - buf.putString(Util.str2byte(getConfig("lang.c2s"))); - buf.putString(Util.str2byte(getConfig("lang.s2c"))); - buf.putByte((byte) 0); - buf.putInt(0); - - buf.setOffSet(5); - I_C = new byte[buf.getLength()]; - buf.getByte(I_C); - - write(packet); - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "SSH_MSG_KEXINIT sent"); - } - } - - private void send_newkeys() throws Exception { - // send SSH_MSG_NEWKEYS(21) - packet.reset(); - buf.putByte((byte) SSH_MSG_NEWKEYS); - write(packet); - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "SSH_MSG_NEWKEYS sent"); - } - } - - public Channel openChannel(ChannelType ctype) throws JSchException { - if (!isConnected) { - throw new JSchException("session is down"); - } - try { - Channel channel = Channel.getChannel(ctype); - addChannel(channel); - channel.init(); - return channel; - } catch (Exception e) { - // e.printStackTrace(); - } - return null; - } - - // encode will bin invoked in write with synchronization. - public void encode(Packet packet) throws Exception { - // System.err.println("encode: "+packet.buffer.getCommand()); - // System.err.println(" "+packet.buffer.index); - // if(packet.buffer.getCommand()==96){ - // Thread.dumpStack(); - // } - if (c2scipher != null) { - // packet.padding(c2scipher.getIVSize()); - packet.padding(c2scipher_size); - int pad = packet.buffer.buffer[4]; - synchronized (random) { - random.fill(packet.buffer.buffer, packet.buffer.index - pad, pad); - } - } else { - packet.padding(8); - } - - if (c2smac != null) { - c2smac.update(seqo); - c2smac.update(packet.buffer.buffer, 0, packet.buffer.index); - c2smac.doFinal(packet.buffer.buffer, packet.buffer.index); - } - if (c2scipher != null) { - byte[] buf = packet.buffer.buffer; - c2scipher.update(buf, 0, packet.buffer.index, buf, 0); - } - if (c2smac != null) { - packet.buffer.skip(c2smac.getBlockSize()); - } - } - - private int s2ccipher_size = 8; - private int c2scipher_size = 8; - - public Buffer read(Buffer buf) throws Exception { - int j = 0; - while (true) { - buf.reset(); - io.getByte(buf.buffer, buf.index, s2ccipher_size); - buf.index += s2ccipher_size; - if (s2ccipher != null) { - s2ccipher.update(buf.buffer, 0, s2ccipher_size, buf.buffer, 0); - } - j = ((buf.buffer[0] << 24) & 0xff000000) | ((buf.buffer[1] << 16) & 0x00ff0000) | ((buf.buffer[2] << 8) & 0x0000ff00) | ((buf.buffer[3]) & 0x000000ff); - // RFC 4253 6.1. Maximum Packet Length - if ((j < 5) || (j > PACKET_MAX_SIZE)) { - start_discard(buf, s2ccipher, s2cmac, j, PACKET_MAX_SIZE); - } - int need = (j + 4) - s2ccipher_size; - // if(need<0){ - // throw new IOException("invalid data"); - // } - if ((buf.index + need) > buf.buffer.length) { - byte[] foo = new byte[buf.index + need]; - System.arraycopy(buf.buffer, 0, foo, 0, buf.index); - buf.buffer = foo; - } - - if ((need % s2ccipher_size) != 0) { - String message = "Bad packet length " + need; - if (JSch.getLogger().isEnabled(Logger.FATAL)) { - JSch.getLogger().log(Logger.FATAL, message); - } - start_discard(buf, s2ccipher, s2cmac, j, PACKET_MAX_SIZE - s2ccipher_size); - } - - if (need > 0) { - io.getByte(buf.buffer, buf.index, need); - buf.index += (need); - if (s2ccipher != null) { - s2ccipher.update(buf.buffer, s2ccipher_size, need, buf.buffer, s2ccipher_size); - } - } - - if (s2cmac != null) { - s2cmac.update(seqi); - s2cmac.update(buf.buffer, 0, buf.index); - - s2cmac.doFinal(s2cmac_result1, 0); - io.getByte(s2cmac_result2, 0, s2cmac_result2.length); - if (!java.util.Arrays.equals(s2cmac_result1, s2cmac_result2)) { - if (need > PACKET_MAX_SIZE) { - throw new IOException("MAC Error"); - } - start_discard(buf, s2ccipher, s2cmac, j, PACKET_MAX_SIZE - need); - continue; - } - } - - seqi++; - - int type = buf.getCommand() & 0xff; - // System.err.println("read: "+type); - if (type == SSH_MSG_DISCONNECT) { - buf.rewind(); - buf.getInt(); - buf.getShort(); - int reason_code = buf.getInt(); - byte[] description = buf.getString(); - byte[] language_tag = buf.getString(); - throw new JSchException("SSH_MSG_DISCONNECT: " + reason_code + " " + Util.byte2str(description) + " " + Util.byte2str(language_tag)); - // break; - } else if (type == SSH_MSG_IGNORE) { - } else if (type == SSH_MSG_UNIMPLEMENTED) { - buf.rewind(); - buf.getInt(); - buf.getShort(); - int reason_id = buf.getInt(); - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "Received SSH_MSG_UNIMPLEMENTED for " + reason_id); - } - } else if (type == SSH_MSG_DEBUG) { - buf.rewind(); - buf.getInt(); - buf.getShort(); - /* - * byte always_display=(byte)buf.getByte(); byte[] message=buf.getString(); byte[] language_tag=buf.getString(); System.err.println("SSH_MSG_DEBUG:"+ " "+Util.byte2str(message)+ " "+Util.byte2str(language_tag)); - */ - } else if (type == SSH_MSG_CHANNEL_WINDOW_ADJUST) { - buf.rewind(); - buf.getInt(); - buf.getShort(); - Channel c = Channel.getChannel(buf.getInt(), this); - if (c == null) { - } else { - c.addRemoteWindowSize(buf.getUInt()); - } - } else if (type == UserAuth.SSH_MSG_USERAUTH_SUCCESS) { - isAuthed = true; - break; - } else { - break; - } - } - buf.rewind(); - return buf; - } - - private void start_discard(Buffer buf, Cipher cipher, MAC mac, int packet_length, int discard) throws JSchException, IOException { - MAC discard_mac = null; - - if (!cipher.isCBC()) { - throw new JSchException("Packet corrupt"); - } - - if ((packet_length != PACKET_MAX_SIZE) && (mac != null)) { - discard_mac = mac; - } - - discard -= buf.index; - - while (discard > 0) { - buf.reset(); - int len = discard > buf.buffer.length ? buf.buffer.length : discard; - io.getByte(buf.buffer, 0, len); - if (discard_mac != null) { - discard_mac.update(buf.buffer, 0, len); - } - discard -= len; - } - - if (discard_mac != null) { - discard_mac.doFinal(buf.buffer, 0); - } - - throw new JSchException("Packet corrupt"); - } - - byte[] getSessionId() { - return session_id; - } - - private void receive_newkeys(Buffer buf, KeyExchange kex) throws Exception { - updateKeys(kex); - in_kex = false; - } - - private void updateKeys(KeyExchange kex) throws Exception { - byte[] K = kex.getK(); - byte[] H = kex.getH(); - HASH hash = kex.getHash(); - - if (session_id == null) { - session_id = new byte[H.length]; - System.arraycopy(H, 0, session_id, 0, H.length); - } - - /* - * Initial IV client to server: HASH (K || H || "A" || session_id) Initial IV server to client: HASH (K || H || "B" || session_id) Encryption key client to server: HASH (K || H || "C" || session_id) Encryption key server to client: HASH (K || H || "D" || session_id) Integrity key client to server: HASH (K || H || "E" || session_id) Integrity key server to client: HASH (K || H || "F" || session_id) - */ - - buf.reset(); - buf.putMPInt(K); - buf.putByte(H); - buf.putByte((byte) 0x41); - buf.putByte(session_id); - hash.update(buf.buffer, 0, buf.index); - IVc2s = hash.digest(); - - int j = buf.index - session_id.length - 1; - - buf.buffer[j]++; - hash.update(buf.buffer, 0, buf.index); - IVs2c = hash.digest(); - - buf.buffer[j]++; - hash.update(buf.buffer, 0, buf.index); - Ec2s = hash.digest(); - - buf.buffer[j]++; - hash.update(buf.buffer, 0, buf.index); - Es2c = hash.digest(); - - buf.buffer[j]++; - hash.update(buf.buffer, 0, buf.index); - MACc2s = hash.digest(); - - buf.buffer[j]++; - hash.update(buf.buffer, 0, buf.index); - MACs2c = hash.digest(); - - try { - Class c; - String method; - - method = guess[KeyExchange.PROPOSAL_ENC_ALGS_STOC]; - c = Class.forName(getConfig(method)); - s2ccipher = (Cipher) (c.newInstance()); - while (s2ccipher.getBlockSize() > Es2c.length) { - buf.reset(); - buf.putMPInt(K); - buf.putByte(H); - buf.putByte(Es2c); - hash.update(buf.buffer, 0, buf.index); - byte[] foo = hash.digest(); - byte[] bar = new byte[Es2c.length + foo.length]; - System.arraycopy(Es2c, 0, bar, 0, Es2c.length); - System.arraycopy(foo, 0, bar, Es2c.length, foo.length); - Es2c = bar; - } - s2ccipher.init(Cipher.DECRYPT_MODE, Es2c, IVs2c); - s2ccipher_size = s2ccipher.getIVSize(); - - method = guess[KeyExchange.PROPOSAL_MAC_ALGS_STOC]; - c = Class.forName(getConfig(method)); - s2cmac = (MAC) (c.newInstance()); - MACs2c = expandKey(buf, K, H, MACs2c, hash, s2cmac.getBlockSize()); - s2cmac.init(MACs2c); - // mac_buf=new byte[s2cmac.getBlockSize()]; - s2cmac_result1 = new byte[s2cmac.getBlockSize()]; - s2cmac_result2 = new byte[s2cmac.getBlockSize()]; - - method = guess[KeyExchange.PROPOSAL_ENC_ALGS_CTOS]; - c = Class.forName(getConfig(method)); - c2scipher = (Cipher) (c.newInstance()); - while (c2scipher.getBlockSize() > Ec2s.length) { - buf.reset(); - buf.putMPInt(K); - buf.putByte(H); - buf.putByte(Ec2s); - hash.update(buf.buffer, 0, buf.index); - byte[] foo = hash.digest(); - byte[] bar = new byte[Ec2s.length + foo.length]; - System.arraycopy(Ec2s, 0, bar, 0, Ec2s.length); - System.arraycopy(foo, 0, bar, Ec2s.length, foo.length); - Ec2s = bar; - } - c2scipher.init(Cipher.ENCRYPT_MODE, Ec2s, IVc2s); - c2scipher_size = c2scipher.getIVSize(); - - method = guess[KeyExchange.PROPOSAL_MAC_ALGS_CTOS]; - c = Class.forName(getConfig(method)); - c2smac = (MAC) (c.newInstance()); - MACc2s = expandKey(buf, K, H, MACc2s, hash, c2smac.getBlockSize()); - c2smac.init(MACc2s); - } catch (Exception e) { - if (e instanceof JSchException) { - throw e; - } - throw new JSchException(e.toString(), e); - // System.err.println("updatekeys: "+e); - } - } - - /* - * RFC 4253 7.2. Output from Key Exchange If the key length needed is longer than the output of the HASH, the key is extended by computing HASH of the concatenation of K and H and the entire key so far, and appending the resulting bytes (as many as HASH generates) to the key. This process is repeated until enough key material is available; the key is taken from the beginning of this value. In other words: K1 = HASH(K || H || X || session_id) (X is e.g., "A") K2 = HASH(K || H || K1) K3 = - * HASH(K || H || K1 || K2) ... key = K1 || K2 || K3 || ... - */ - private byte[] expandKey(Buffer buf, byte[] K, byte[] H, byte[] key, HASH hash, int required_length) throws Exception { - byte[] result = key; - int size = hash.getBlockSize(); - while (result.length < required_length) { - buf.reset(); - buf.putMPInt(K); - buf.putByte(H); - buf.putByte(result); - hash.update(buf.buffer, 0, buf.index); - byte[] tmp = new byte[result.length + size]; - System.arraycopy(result, 0, tmp, 0, result.length); - System.arraycopy(hash.digest(), 0, tmp, result.length, size); - Util.bzero(result); - result = tmp; - } - return result; - } - - /* public *//* synchronized */void write(Packet packet, Channel c, int length) throws Exception { - long t = getTimeout(); - while (true) { - if (in_kex) { - if ((t > 0L) && ((System.currentTimeMillis() - kex_start_time) > t)) { - throw new JSchException("timeout in wating for rekeying process."); - } - try { - Thread.sleep(10); - } catch (java.lang.InterruptedException e) { - } - ; - continue; - } - synchronized (c) { - - if (c.rwsize < length) { - try { - c.notifyme++; - c.wait(100); - } catch (java.lang.InterruptedException e) { - } finally { - c.notifyme--; - } - } - - if (c.rwsize >= length) { - c.rwsize -= length; - break; - } - - } - if (c.close || !c.isConnected()) { - throw new IOException("channel is broken"); - } - - boolean sendit = false; - int s = 0; - byte command = 0; - int recipient = -1; - synchronized (c) { - if (c.rwsize > 0) { - long len = c.rwsize; - if (len > length) { - len = length; - } - if (len != length) { - s = packet.shift((int) len, (c2scipher != null ? c2scipher_size : 8), (c2smac != null ? c2smac.getBlockSize() : 0)); - } - command = packet.buffer.getCommand(); - recipient = c.getRecipient(); - length -= len; - c.rwsize -= len; - sendit = true; - } - } - if (sendit) { - _write(packet); - if (length == 0) { - return; - } - packet.unshift(command, recipient, s, length); - } - - synchronized (c) { - if (in_kex) { - continue; - } - if (c.rwsize >= length) { - c.rwsize -= length; - break; - } - - // try{ - // System.out.println("1wait: "+c.rwsize); - // c.notifyme++; - // c.wait(100); - // } - // catch(java.lang.InterruptedException e){ - // } - // finally{ - // c.notifyme--; - // } - } - } - _write(packet); - } - - public void write(Packet packet) throws Exception { - // System.err.println("in_kex="+in_kex+" "+(packet.buffer.getCommand())); - long t = getTimeout(); - while (in_kex) { - if ((t > 0L) && ((System.currentTimeMillis() - kex_start_time) > t)) { - throw new JSchException("timeout in wating for rekeying process."); - } - byte command = packet.buffer.getCommand(); - // System.err.println("command: "+command); - if ((command == SSH_MSG_KEXINIT) || (command == SSH_MSG_NEWKEYS) || (command == SSH_MSG_KEXDH_INIT) || (command == SSH_MSG_KEXDH_REPLY) || - - (// this two commands have the same number, and it is not a mistake, so find bugs warning can be ignored - command == SSH_MSG_KEX_DH_GEX_GROUP) || (command == SSH_MSG_KEX_DH_GEX_INIT) || - - (command == SSH_MSG_KEX_DH_GEX_REPLY) || (command == SSH_MSG_KEX_DH_GEX_REQUEST) || (command == SSH_MSG_DISCONNECT)) { - break; - } - try { - Thread.sleep(10); - } catch (java.lang.InterruptedException e) { - } - ; - } - _write(packet); - } - - private void _write(Packet packet) throws Exception { - synchronized (lock) { - encode(packet); - if (io != null) { - io.put(packet); - seqo++; - } - } - } - - Runnable thread; - - @Override - public void run() { - thread = this; - - byte[] foo; - Buffer buf = new Buffer(); - Packet packet = new Packet(buf); - int i = 0; - Channel channel; - int[] start = new int[1]; - int[] length = new int[1]; - KeyExchange kex = null; - - int stimeout = 0; - try { - while (isConnected && (thread != null)) { - try { - buf = read(buf); - stimeout = 0; - } catch (InterruptedIOException/* SocketTimeoutException */ee) { - if (!in_kex && (stimeout < serverAliveCountMax)) { - sendKeepAliveMsg(); - stimeout++; - continue; - } else if (in_kex && (stimeout < serverAliveCountMax)) { - stimeout++; - continue; - } - throw ee; - } - - int msgType = buf.getCommand() & 0xff; - - if ((kex != null) && (kex.getState() == msgType)) { - kex_start_time = System.currentTimeMillis(); - boolean result = kex.next(buf); - if (!result) { - throw new JSchException("verify: " + result); - } - continue; - } - - switch (msgType) { - case SSH_MSG_KEXINIT: - // System.err.println("KEXINIT"); - kex = receive_kexinit(buf); - break; - - case SSH_MSG_NEWKEYS: - // System.err.println("NEWKEYS"); - send_newkeys(); - receive_newkeys(buf, kex); - kex = null; - break; - - case SSH_MSG_CHANNEL_DATA: - buf.getInt(); - buf.getByte(); - buf.getByte(); - i = buf.getInt(); - channel = Channel.getChannel(i, this); - foo = buf.getString(start, length); - if (channel == null) { - break; - } - - if (length[0] == 0) { - break; - } - - try { - channel.write(foo, start[0], length[0]); - } catch (Exception e) { - // System.err.println(e); - try { - channel.disconnect(); - } catch (Exception ee) { - } - break; - } - int len = length[0]; - channel.setLocalWindowSize(channel.lwsize - len); - if (channel.lwsize < (channel.lwsize_max / 2)) { - packet.reset(); - buf.putByte((byte) SSH_MSG_CHANNEL_WINDOW_ADJUST); - buf.putInt(channel.getRecipient()); - buf.putInt(channel.lwsize_max - channel.lwsize); - synchronized (channel) { - if (!channel.close) { - write(packet); - } - } - channel.setLocalWindowSize(channel.lwsize_max); - } - break; - - case SSH_MSG_CHANNEL_EXTENDED_DATA: - throw new IllegalStateException("Can't operate ext data"); - - case SSH_MSG_CHANNEL_WINDOW_ADJUST: - buf.getInt(); - buf.getShort(); - i = buf.getInt(); - channel = Channel.getChannel(i, this); - if (channel == null) { - break; - } - channel.addRemoteWindowSize(buf.getUInt()); - break; - - case SSH_MSG_CHANNEL_EOF: - buf.getInt(); - buf.getShort(); - i = buf.getInt(); - channel = Channel.getChannel(i, this); - if (channel != null) { - // channel.eof_remote=true; - // channel.eof(); - channel.eof_remote(); - } - /* - * packet.reset(); buf.putByte((byte)SSH_MSG_CHANNEL_EOF); buf.putInt(channel.getRecipient()); write(packet); - */ - break; - case SSH_MSG_CHANNEL_CLOSE: - buf.getInt(); - buf.getShort(); - i = buf.getInt(); - channel = Channel.getChannel(i, this); - if (channel != null) { - // channel.close(); - channel.disconnect(); - } - /* - * if(Channel.pool.size()==0){ thread=null; } - */ - break; - case SSH_MSG_CHANNEL_OPEN_CONFIRMATION: - buf.getInt(); - buf.getShort(); - i = buf.getInt(); - channel = Channel.getChannel(i, this); - int r = buf.getInt(); - long rws = buf.getUInt(); - int rps = buf.getInt(); - if (channel != null) { - channel.setRemoteWindowSize(rws); - channel.setRemotePacketSize(rps); - channel.open_confirmation = true; - channel.setRecipient(r); - } - break; - case SSH_MSG_CHANNEL_OPEN_FAILURE: - buf.getInt(); - buf.getShort(); - i = buf.getInt(); - channel = Channel.getChannel(i, this); - if (channel != null) { - int reason_code = buf.getInt(); - // foo=buf.getString(); // additional textual - // information - // foo=buf.getString(); // language tag - channel.setExitStatus(reason_code); - channel.close = true; - channel.eof_remote = true; - channel.setRecipient(0); - } - break; - case SSH_MSG_CHANNEL_REQUEST: - buf.getInt(); - buf.getShort(); - i = buf.getInt(); - foo = buf.getString(); - boolean reply = (buf.getByte() != 0); - channel = Channel.getChannel(i, this); - if (channel != null) { - byte reply_type = (byte) SSH_MSG_CHANNEL_FAILURE; - if ((Util.byte2str(foo)).equals("exit-status")) { - i = buf.getInt(); // exit-status - channel.setExitStatus(i); - reply_type = (byte) SSH_MSG_CHANNEL_SUCCESS; - } - if (reply) { - packet.reset(); - buf.putByte(reply_type); - buf.putInt(channel.getRecipient()); - write(packet); - } - } else { - } - break; - case SSH_MSG_CHANNEL_OPEN: - buf.getInt(); - buf.getShort(); - foo = buf.getString(); - packet.reset(); - buf.putByte((byte) SSH_MSG_CHANNEL_OPEN_FAILURE); - buf.putInt(buf.getInt()); - buf.putInt(Channel.SSH_OPEN_ADMINISTRATIVELY_PROHIBITED); - buf.putString(Util.empty); - buf.putString(Util.empty); - write(packet); - break; - case SSH_MSG_CHANNEL_SUCCESS: - buf.getInt(); - buf.getShort(); - i = buf.getInt(); - channel = Channel.getChannel(i, this); - if (channel == null) { - break; - } - channel.reply = 1; - break; - case SSH_MSG_CHANNEL_FAILURE: - buf.getInt(); - buf.getShort(); - i = buf.getInt(); - channel = Channel.getChannel(i, this); - if (channel == null) { - break; - } - channel.reply = 0; - break; - case SSH_MSG_GLOBAL_REQUEST: - buf.getInt(); - buf.getShort(); - foo = buf.getString(); // request name - reply = (buf.getByte() != 0); - if (reply) { - packet.reset(); - buf.putByte((byte) SSH_MSG_REQUEST_FAILURE); - write(packet); - } - break; - case SSH_MSG_REQUEST_FAILURE: - case SSH_MSG_REQUEST_SUCCESS: - break; - default: - // System.err.println("Session.run: unsupported type "+msgType); - throw new IOException("Unknown SSH message type " + msgType); - } - } - } catch (Exception e) { - in_kex = false; - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "Caught an exception, leaving main loop due to " + e.getMessage()); - } - // System.err.println("# Session.run"); - // e.printStackTrace(); - } - try { - disconnect(); - } catch (NullPointerException e) { - // System.err.println("@1"); - // e.printStackTrace(); - } catch (Exception e) { - // System.err.println("@2"); - // e.printStackTrace(); - } - isConnected = false; - } - - public void disconnect() { - if (!isConnected) { - return; - } - // System.err.println(this+": disconnect"); - // Thread.dumpStack(); - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "Disconnecting from " + host + " port " + port); - } - /* - * for(int i=0; i(); - } - config.put(key, value); - } - } - - public String getConfig(String key) { - Object foo = null; - if (config != null) { - foo = config.get(key); - if (foo instanceof String) { - return (String) foo; - } - } - foo = JSch.getConfig(key); - if (foo instanceof String) { - return (String) foo; - } - return null; - } - - public void setSocketFactory(SocketFactory sfactory) { - socket_factory = sfactory; - } - - public boolean isConnected() { - return isConnected; - } - - public int getTimeout() { - return timeout; - } - - public void setTimeout(int timeout) throws JSchException { - if (socket == null) { - if (timeout < 0) { - throw new JSchException("invalid timeout value"); - } - this.timeout = timeout; - return; - } - try { - socket.setSoTimeout(timeout); - this.timeout = timeout; - } catch (Exception e) { - if (e instanceof Throwable) { - throw new JSchException(e.toString(), e); - } - throw new JSchException(e.toString()); - } - } - - public String getServerVersion() { - return Util.byte2str(V_S); - } - - public String getClientVersion() { - return Util.byte2str(V_C); - } - - public void setClientVersion(String cv) { - V_C = Util.str2byte(cv); - } - - public void sendIgnore() throws Exception { - Buffer buf = new Buffer(); - Packet packet = new Packet(buf); - packet.reset(); - buf.putByte((byte) SSH_MSG_IGNORE); - write(packet); - } - - private static final byte[] keepalivemsg = Util.str2byte("keepalive@jcraft.com"); - - public void sendKeepAliveMsg() throws Exception { - Buffer buf = new Buffer(); - Packet packet = new Packet(buf); - packet.reset(); - buf.putByte((byte) SSH_MSG_GLOBAL_REQUEST); - buf.putString(keepalivemsg); - buf.putByte((byte) 1); - write(packet); - } - - private static final byte[] nomoresessions = Util.str2byte("no-more-sessions@openssh.com"); - - public void noMoreSessionChannels() throws Exception { - Buffer buf = new Buffer(); - Packet packet = new Packet(buf); - packet.reset(); - buf.putByte((byte) SSH_MSG_GLOBAL_REQUEST); - buf.putString(nomoresessions); - buf.putByte((byte) 0); - write(packet); - } - - public String getHost() { - return host; - } - - public String getUserName() { - return username; - } - - public int getPort() { - return port; - } - - /** - * Sets the interval to send a keep-alive message. If zero is specified, any keep-alive message must not be sent. The default interval is zero. - * - * @param interval - * the specified interval, in milliseconds. - * @see #getServerAliveInterval() - */ - public void setServerAliveInterval(int interval) throws JSchException { - setTimeout(interval); - serverAliveInterval = interval; - } - - /** - * Returns setting for the interval to send a keep-alive message. - * - * @see #setServerAliveInterval(int) - */ - public int getServerAliveInterval() { - return serverAliveInterval; - } - - /** - * Sets the number of keep-alive messages which may be sent without receiving any messages back from the server. If this threshold is reached while keep-alive messages are being sent, the connection will be disconnected. The default value is one. - * - * @param count - * the specified count - * @see #getServerAliveCountMax() - */ - public void setServerAliveCountMax(int count) { - serverAliveCountMax = count; - } - - /** - * Returns setting for the threshold to send keep-alive messages. - * - * @see #setServerAliveCountMax(int) - */ - public int getServerAliveCountMax() { - return serverAliveCountMax; - } - - public void setDaemonThread(boolean enable) { - daemon_thread = enable; - } - - private String[] checkCiphers(String ciphers) { - if ((ciphers == null) || (ciphers.length() == 0)) { - return null; - } - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "CheckCiphers: " + ciphers); - } - - String cipherc2s = getConfig("cipher.c2s"); - String ciphers2c = getConfig("cipher.s2c"); - - Vector result = new Vector(); - String[] _ciphers = Util.split(ciphers, ","); - for (int i = 0; i < _ciphers.length; i++) { - String cipher = _ciphers[i]; - if ((ciphers2c.indexOf(cipher) == -1) && (cipherc2s.indexOf(cipher) == -1)) { - continue; - } - if (!checkCipher(getConfig(cipher))) { - result.addElement(cipher); - } - } - if (result.size() == 0) { - return null; - } - String[] foo = new String[result.size()]; - System.arraycopy(result.toArray(), 0, foo, 0, result.size()); - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - for (int i = 0; i < foo.length; i++) { - JSch.getLogger().log(Logger.INFO, foo[i] + " is not available."); - } - } - - return foo; - } - - static boolean checkCipher(String cipher) { - try { - Class c = Class.forName(cipher); - Cipher _c = (Cipher) (c.newInstance()); - _c.init(Cipher.ENCRYPT_MODE, new byte[_c.getBlockSize()], new byte[_c.getIVSize()]); - return true; - } catch (Exception e) { - return false; - } - } - - private String[] checkKexes(String kexes) { - if ((kexes == null) || (kexes.length() == 0)) { - return null; - } - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "CheckKexes: " + kexes); - } - - java.util.Vector result = new java.util.Vector(); - String[] _kexes = Util.split(kexes, ","); - for (int i = 0; i < _kexes.length; i++) { - if (!checkKex(this, getConfig(_kexes[i]))) { - result.addElement(_kexes[i]); - } - } - if (result.size() == 0) { - return null; - } - String[] foo = new String[result.size()]; - System.arraycopy(result.toArray(), 0, foo, 0, result.size()); - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - for (int i = 0; i < foo.length; i++) { - JSch.getLogger().log(Logger.INFO, foo[i] + " is not available."); - } - } - - return foo; - } - - static boolean checkKex(Session s, String kex) { - try { - Class c = Class.forName(kex); - KeyExchange _c = (KeyExchange) (c.newInstance()); - _c.init(s, null, null, null, null); - return true; - } catch (Exception e) { - return false; - } - } - -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/SftpATTRS.java b/src/autosaveworld/zlibs/com/jcraft/jsch/SftpATTRS.java deleted file mode 100644 index 6e91354a..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/SftpATTRS.java +++ /dev/null @@ -1,368 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -import java.util.Date; - -/* - uint32 flags - uint64 size present only if flag SSH_FILEXFER_ATTR_SIZE - uint32 uid present only if flag SSH_FILEXFER_ATTR_UIDGID - uint32 gid present only if flag SSH_FILEXFER_ATTR_UIDGID - uint32 permissions present only if flag SSH_FILEXFER_ATTR_PERMISSIONS - uint32 atime present only if flag SSH_FILEXFER_ACMODTIME - uint32 mtime present only if flag SSH_FILEXFER_ACMODTIME - uint32 extended_count present only if flag SSH_FILEXFER_ATTR_EXTENDED - string extended_type - string extended_data - ... more extended data (extended_type - extended_data pairs), - so that number of pairs equals extended_count - */ -public class SftpATTRS { - - static final int S_ISUID = 04000; // set user ID on execution - static final int S_ISGID = 02000; // set group ID on execution - static final int S_ISVTX = 01000; // sticky bit ****** NOT DOCUMENTED ***** - - static final int S_IRUSR = 00400; // read by owner - static final int S_IWUSR = 00200; // write by owner - static final int S_IXUSR = 00100; // execute/search by owner - static final int S_IREAD = 00400; // read by owner - static final int S_IWRITE = 00200; // write by owner - static final int S_IEXEC = 00100; // execute/search by owner - - static final int S_IRGRP = 00040; // read by group - static final int S_IWGRP = 00020; // write by group - static final int S_IXGRP = 00010; // execute/search by group - - static final int S_IROTH = 00004; // read by others - static final int S_IWOTH = 00002; // write by others - static final int S_IXOTH = 00001; // execute/search by others - - private static final int pmask = 0xFFF; - - public String getPermissionsString() { - StringBuffer buf = new StringBuffer(10); - - if (isDir()) { - buf.append('d'); - } else if (isLink()) { - buf.append('l'); - } else { - buf.append('-'); - } - - if ((permissions & S_IRUSR) != 0) { - buf.append('r'); - } else { - buf.append('-'); - } - - if ((permissions & S_IWUSR) != 0) { - buf.append('w'); - } else { - buf.append('-'); - } - - if ((permissions & S_ISUID) != 0) { - buf.append('s'); - } else if ((permissions & S_IXUSR) != 0) { - buf.append('x'); - } else { - buf.append('-'); - } - - if ((permissions & S_IRGRP) != 0) { - buf.append('r'); - } else { - buf.append('-'); - } - - if ((permissions & S_IWGRP) != 0) { - buf.append('w'); - } else { - buf.append('-'); - } - - if ((permissions & S_ISGID) != 0) { - buf.append('s'); - } else if ((permissions & S_IXGRP) != 0) { - buf.append('x'); - } else { - buf.append('-'); - } - - if ((permissions & S_IROTH) != 0) { - buf.append('r'); - } else { - buf.append('-'); - } - - if ((permissions & S_IWOTH) != 0) { - buf.append('w'); - } else { - buf.append('-'); - } - - if ((permissions & S_IXOTH) != 0) { - buf.append('x'); - } else { - buf.append('-'); - } - return (buf.toString()); - } - - public String getAtimeString() { - Date date = new Date((atime) * 1000L); - return (date.toString()); - } - - public String getMtimeString() { - Date date = new Date((mtime) * 1000L); - return (date.toString()); - } - - public static final int SSH_FILEXFER_ATTR_SIZE = 0x00000001; - public static final int SSH_FILEXFER_ATTR_UIDGID = 0x00000002; - public static final int SSH_FILEXFER_ATTR_PERMISSIONS = 0x00000004; - public static final int SSH_FILEXFER_ATTR_ACMODTIME = 0x00000008; - public static final int SSH_FILEXFER_ATTR_EXTENDED = 0x80000000; - - static final int S_IFMT = 0xf000; - static final int S_IFIFO = 0x1000; - static final int S_IFCHR = 0x2000; - static final int S_IFDIR = 0x4000; - static final int S_IFBLK = 0x6000; - static final int S_IFREG = 0x8000; - static final int S_IFLNK = 0xa000; - static final int S_IFSOCK = 0xc000; - - int flags = 0; - long size; - int uid; - int gid; - int permissions; - int atime; - int mtime; - String[] extended = null; - - private SftpATTRS() { - } - - static SftpATTRS getATTR(Buffer buf) { - SftpATTRS attr = new SftpATTRS(); - attr.flags = buf.getInt(); - if ((attr.flags & SSH_FILEXFER_ATTR_SIZE) != 0) { - attr.size = buf.getLong(); - } - if ((attr.flags & SSH_FILEXFER_ATTR_UIDGID) != 0) { - attr.uid = buf.getInt(); - attr.gid = buf.getInt(); - } - if ((attr.flags & SSH_FILEXFER_ATTR_PERMISSIONS) != 0) { - attr.permissions = buf.getInt(); - } - if ((attr.flags & SSH_FILEXFER_ATTR_ACMODTIME) != 0) { - attr.atime = buf.getInt(); - } - if ((attr.flags & SSH_FILEXFER_ATTR_ACMODTIME) != 0) { - attr.mtime = buf.getInt(); - } - if ((attr.flags & SSH_FILEXFER_ATTR_EXTENDED) != 0) { - int count = buf.getInt(); - if (count > 0) { - attr.extended = new String[count * 2]; - for (int i = 0; i < count; i++) { - attr.extended[i * 2] = Util.byte2str(buf.getString()); - attr.extended[(i * 2) + 1] = Util.byte2str(buf.getString()); - } - } - } - return attr; - } - - int length() { - int len = 4; - - if ((flags & SSH_FILEXFER_ATTR_SIZE) != 0) { - len += 8; - } - if ((flags & SSH_FILEXFER_ATTR_UIDGID) != 0) { - len += 8; - } - if ((flags & SSH_FILEXFER_ATTR_PERMISSIONS) != 0) { - len += 4; - } - if ((flags & SSH_FILEXFER_ATTR_ACMODTIME) != 0) { - len += 8; - } - if ((flags & SSH_FILEXFER_ATTR_EXTENDED) != 0) { - len += 4; - int count = extended.length / 2; - if (count > 0) { - for (int i = 0; i < count; i++) { - len += 4; - len += extended[i * 2].length(); - len += 4; - len += extended[(i * 2) + 1].length(); - } - } - } - return len; - } - - void dump(Buffer buf) { - buf.putInt(flags); - if ((flags & SSH_FILEXFER_ATTR_SIZE) != 0) { - buf.putLong(size); - } - if ((flags & SSH_FILEXFER_ATTR_UIDGID) != 0) { - buf.putInt(uid); - buf.putInt(gid); - } - if ((flags & SSH_FILEXFER_ATTR_PERMISSIONS) != 0) { - buf.putInt(permissions); - } - if ((flags & SSH_FILEXFER_ATTR_ACMODTIME) != 0) { - buf.putInt(atime); - } - if ((flags & SSH_FILEXFER_ATTR_ACMODTIME) != 0) { - buf.putInt(mtime); - } - if ((flags & SSH_FILEXFER_ATTR_EXTENDED) != 0) { - int count = extended.length / 2; - if (count > 0) { - for (int i = 0; i < count; i++) { - buf.putString(Util.str2byte(extended[i * 2])); - buf.putString(Util.str2byte(extended[(i * 2) + 1])); - } - } - } - } - - void setFLAGS(int flags) { - this.flags = flags; - } - - public void setSIZE(long size) { - flags |= SSH_FILEXFER_ATTR_SIZE; - this.size = size; - } - - public void setUIDGID(int uid, int gid) { - flags |= SSH_FILEXFER_ATTR_UIDGID; - this.uid = uid; - this.gid = gid; - } - - public void setACMODTIME(int atime, int mtime) { - flags |= SSH_FILEXFER_ATTR_ACMODTIME; - this.atime = atime; - this.mtime = mtime; - } - - public void setPERMISSIONS(int permissions) { - flags |= SSH_FILEXFER_ATTR_PERMISSIONS; - permissions = (this.permissions & ~pmask) | (permissions & pmask); - this.permissions = permissions; - } - - private boolean isType(int mask) { - return ((flags & SSH_FILEXFER_ATTR_PERMISSIONS) != 0) && ((permissions & S_IFMT) == mask); - } - - public boolean isReg() { - return isType(S_IFREG); - } - - public boolean isDir() { - return isType(S_IFDIR); - } - - public boolean isChr() { - return isType(S_IFCHR); - } - - public boolean isBlk() { - return isType(S_IFBLK); - } - - public boolean isFifo() { - return isType(S_IFIFO); - } - - public boolean isLink() { - return isType(S_IFLNK); - } - - public boolean isSock() { - return isType(S_IFSOCK); - } - - public int getFlags() { - return flags; - } - - public long getSize() { - return size; - } - - public int getUId() { - return uid; - } - - public int getGId() { - return gid; - } - - public int getPermissions() { - return permissions; - } - - public int getATime() { - return atime; - } - - public int getMTime() { - return mtime; - } - - public String[] getExtended() { - return extended; - } - - @Override - public String toString() { - return (getPermissionsString() + " " + getUId() + " " + getGId() + " " + getSize() + " " + getMtimeString()); - } - /* - * public String toString(){ return (((flags&SSH_FILEXFER_ATTR_SIZE)!=0) ? ("size:"+size+" ") : "")+ (((flags&SSH_FILEXFER_ATTR_UIDGID)!=0) ? ("uid:"+uid+",gid:"+gid+" ") : "")+ (((flags&SSH_FILEXFER_ATTR_PERMISSIONS)!=0) ? ("permissions:0x"+Integer.toHexString(permissions)+" ") : "")+ (((flags&SSH_FILEXFER_ATTR_ACMODTIME)!=0) ? ("atime:"+atime+",mtime:"+mtime+" ") : "")+ (((flags&SSH_FILEXFER_ATTR_EXTENDED)!=0) ? ("extended:?"+" ") : ""); } - */ -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/SftpException.java b/src/autosaveworld/zlibs/com/jcraft/jsch/SftpException.java deleted file mode 100644 index 16030159..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/SftpException.java +++ /dev/null @@ -1,60 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public class SftpException extends Exception { - - private static final long serialVersionUID = -5616888495583253811L; - - public int id; - private Throwable cause = null; - - public SftpException(int id, String message) { - super(message); - this.id = id; - } - - public SftpException(int id, String message, Throwable e) { - super(message); - this.id = id; - cause = e; - } - - @Override - public String toString() { - return id + ": " + getMessage(); - } - - @Override - public Throwable getCause() { - return cause; - } - -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/SftpProgressMonitor.java b/src/autosaveworld/zlibs/com/jcraft/jsch/SftpProgressMonitor.java deleted file mode 100644 index 1defda7b..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/SftpProgressMonitor.java +++ /dev/null @@ -1,42 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public interface SftpProgressMonitor { - public static final int PUT = 0; - public static final int GET = 1; - public static final long UNKNOWN_SIZE = -1L; - - void init(int op, String src, String dest, long max); - - boolean count(long count); - - void end(); -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/Signature.java b/src/autosaveworld/zlibs/com/jcraft/jsch/Signature.java deleted file mode 100644 index 4e4e9c49..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/Signature.java +++ /dev/null @@ -1,40 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2012-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public interface Signature { - void init() throws Exception; - - void update(byte[] H) throws Exception; - - boolean verify(byte[] sig) throws Exception; - - byte[] sign() throws Exception; -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/SignatureDSA.java b/src/autosaveworld/zlibs/com/jcraft/jsch/SignatureDSA.java deleted file mode 100644 index d0e6c128..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/SignatureDSA.java +++ /dev/null @@ -1,36 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public interface SignatureDSA extends Signature { - void setPubKey(byte[] y, byte[] p, byte[] q, byte[] g) throws Exception; - - void setPrvKey(byte[] x, byte[] p, byte[] q, byte[] g) throws Exception; -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/SignatureRSA.java b/src/autosaveworld/zlibs/com/jcraft/jsch/SignatureRSA.java deleted file mode 100644 index 62695ceb..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/SignatureRSA.java +++ /dev/null @@ -1,36 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public interface SignatureRSA extends Signature { - void setPubKey(byte[] e, byte[] n) throws Exception; - - void setPrvKey(byte[] d, byte[] n) throws Exception; -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/SocketFactory.java b/src/autosaveworld/zlibs/com/jcraft/jsch/SocketFactory.java deleted file mode 100644 index 050e2bcc..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/SocketFactory.java +++ /dev/null @@ -1,44 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.Socket; -import java.net.UnknownHostException; - -public interface SocketFactory { - public Socket createSocket(String host, int port) throws IOException, UnknownHostException; - - public InputStream getInputStream(Socket socket) throws IOException; - - public OutputStream getOutputStream(Socket socket) throws IOException; -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/UserAuth.java b/src/autosaveworld/zlibs/com/jcraft/jsch/UserAuth.java deleted file mode 100644 index 200758c6..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/UserAuth.java +++ /dev/null @@ -1,53 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public abstract class UserAuth { - protected static final int SSH_MSG_USERAUTH_REQUEST = 50; - protected static final int SSH_MSG_USERAUTH_FAILURE = 51; - protected static final int SSH_MSG_USERAUTH_SUCCESS = 52; - protected static final int SSH_MSG_USERAUTH_BANNER = 53; - protected static final int SSH_MSG_USERAUTH_INFO_REQUEST = 60; - protected static final int SSH_MSG_USERAUTH_INFO_RESPONSE = 61; - protected static final int SSH_MSG_USERAUTH_PK_OK = 60; - - protected UserInfo userinfo; - protected Packet packet; - protected Buffer buf; - protected String username; - - public boolean start(Session session) throws Exception { - userinfo = session.getUserInfo(); - packet = session.packet; - buf = packet.getBuffer(); - username = session.getUserName(); - return true; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/UserAuthNone.java b/src/autosaveworld/zlibs/com/jcraft/jsch/UserAuthNone.java deleted file mode 100644 index 39bfc172..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/UserAuthNone.java +++ /dev/null @@ -1,130 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -class UserAuthNone extends UserAuth { - private static final int SSH_MSG_SERVICE_ACCEPT = 6; - private String methods = null; - - @Override - public boolean start(Session session) throws Exception { - super.start(session); - - // send - // byte SSH_MSG_SERVICE_REQUEST(5) - // string service name "ssh-userauth" - packet.reset(); - buf.putByte((byte) Session.SSH_MSG_SERVICE_REQUEST); - buf.putString(Util.str2byte("ssh-userauth")); - session.write(packet); - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "SSH_MSG_SERVICE_REQUEST sent"); - } - - // receive - // byte SSH_MSG_SERVICE_ACCEPT(6) - // string service name - buf = session.read(buf); - int command = buf.getCommand(); - - boolean result = (command == SSH_MSG_SERVICE_ACCEPT); - - if (JSch.getLogger().isEnabled(Logger.INFO)) { - JSch.getLogger().log(Logger.INFO, "SSH_MSG_SERVICE_ACCEPT received"); - } - if (!result) { - return false; - } - - byte[] _username = null; - _username = Util.str2byte(username); - - // send - // byte SSH_MSG_USERAUTH_REQUEST(50) - // string user name - // string service name ("ssh-connection") - // string "none" - packet.reset(); - buf.putByte((byte) SSH_MSG_USERAUTH_REQUEST); - buf.putString(_username); - buf.putString(Util.str2byte("ssh-connection")); - buf.putString(Util.str2byte("none")); - session.write(packet); - - loop: while (true) { - buf = session.read(buf); - command = buf.getCommand() & 0xff; - - if (command == SSH_MSG_USERAUTH_SUCCESS) { - return true; - } - if (command == SSH_MSG_USERAUTH_BANNER) { - buf.getInt(); - buf.getByte(); - buf.getByte(); - byte[] _message = buf.getString(); - buf.getString(); - String message = Util.byte2str(_message); - if (userinfo != null) { - try { - userinfo.showMessage(message); - } catch (RuntimeException ee) { - } - } - continue loop; - } - if (command == SSH_MSG_USERAUTH_FAILURE) { - buf.getInt(); - buf.getByte(); - buf.getByte(); - byte[] foo = buf.getString(); - buf.getByte(); - methods = Util.byte2str(foo); - // System.err.println("UserAuthNONE: "+methods+ - // " partial_success:"+(partial_success!=0)); - // if(partial_success!=0){ - // throw new JSchPartialAuthException(new String(foo)); - // } - - break; - } else { - // System.err.println("USERAUTH fail ("+command+")"); - throw new JSchException("USERAUTH fail (" + command + ")"); - } - } - // throw new JSchException("USERAUTH fail"); - return false; - } - - String getMethods() { - return methods; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/UserAuthPassword.java b/src/autosaveworld/zlibs/com/jcraft/jsch/UserAuthPassword.java deleted file mode 100644 index cd7a9db2..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/UserAuthPassword.java +++ /dev/null @@ -1,144 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -class UserAuthPassword extends UserAuth { - - @Override - public boolean start(Session session) throws Exception { - super.start(session); - - byte[] password = session.password; - String dest = username + "@" + session.host; - if (session.port != 22) { - dest += (":" + session.port); - } - - try { - - while (true) { - - if (session.auth_failures >= session.max_auth_tries) { - return false; - } - - if (password == null) { - if (userinfo == null) { - // throw new JSchException("USERAUTH fail"); - return false; - } - if (!userinfo.promptPassword("Password for " + dest)) { - throw new JSchAuthCancelException("password"); - // break; - } - - String _password = userinfo.getPassword(); - if (_password == null) { - throw new JSchAuthCancelException("password"); - // break; - } - password = Util.str2byte(_password); - } - - byte[] _username = null; - _username = Util.str2byte(username); - - // send - // byte SSH_MSG_USERAUTH_REQUEST(50) - // string user name - // string service name ("ssh-connection") - // string "password" - // boolen FALSE - // string plaintext password (ISO-10646 UTF-8) - packet.reset(); - buf.putByte((byte) SSH_MSG_USERAUTH_REQUEST); - buf.putString(_username); - buf.putString(Util.str2byte("ssh-connection")); - buf.putString(Util.str2byte("password")); - buf.putByte((byte) 0); - buf.putString(password); - session.write(packet); - - loop: while (true) { - buf = session.read(buf); - int command = buf.getCommand() & 0xff; - - if (command == SSH_MSG_USERAUTH_SUCCESS) { - return true; - } - if (command == SSH_MSG_USERAUTH_BANNER) { - buf.getInt(); - buf.getByte(); - buf.getByte(); - byte[] _message = buf.getString(); - buf.getString(); - String message = Util.byte2str(_message); - if (userinfo != null) { - userinfo.showMessage(message); - } - continue loop; - } - if (command == SSH_MSG_USERAUTH_FAILURE) { - buf.getInt(); - buf.getByte(); - buf.getByte(); - byte[] foo = buf.getString(); - int partial_success = buf.getByte(); - // System.err.println(new String(foo)+ - // " partial_success:"+(partial_success!=0)); - if (partial_success != 0) { - throw new JSchPartialAuthException(Util.byte2str(foo)); - } - session.auth_failures++; - break; - } else { - // System.err.println("USERAUTH fail ("+buf.getCommand()+")"); - // throw new - // JSchException("USERAUTH fail ("+buf.getCommand()+")"); - return false; - } - } - - if (password != null) { - Util.bzero(password); - password = null; - } - - } - - } finally { - if (password != null) { - Util.bzero(password); - password = null; - } - } - } - -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/UserInfo.java b/src/autosaveworld/zlibs/com/jcraft/jsch/UserInfo.java deleted file mode 100644 index 734c719b..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/UserInfo.java +++ /dev/null @@ -1,44 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -public interface UserInfo { - String getPassphrase(); - - String getPassword(); - - boolean promptPassword(String message); - - boolean promptPassphrase(String message); - - boolean promptYesNo(String message); - - void showMessage(String message); -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/Util.java b/src/autosaveworld/zlibs/com/jcraft/jsch/Util.java deleted file mode 100644 index 28a57384..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/Util.java +++ /dev/null @@ -1,557 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.Socket; - -class Util { - - private static final byte[] b64 = Util.str2byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="); - - private static byte val(byte foo) { - if (foo == '=') { - return 0; - } - for (int j = 0; j < b64.length; j++) { - if (foo == b64[j]) { - return (byte) j; - } - } - return 0; - } - - static byte[] fromBase64(byte[] buf, int start, int length) throws JSchException { - try { - byte[] foo = new byte[length]; - int j = 0; - for (int i = start; i < (start + length); i += 4) { - foo[j] = (byte) ((val(buf[i]) << 2) | ((val(buf[i + 1]) & 0x30) >>> 4)); - if (buf[i + 2] == (byte) '=') { - j++; - break; - } - foo[j + 1] = (byte) (((val(buf[i + 1]) & 0x0f) << 4) | ((val(buf[i + 2]) & 0x3c) >>> 2)); - if (buf[i + 3] == (byte) '=') { - j += 2; - break; - } - foo[j + 2] = (byte) (((val(buf[i + 2]) & 0x03) << 6) | (val(buf[i + 3]) & 0x3f)); - j += 3; - } - byte[] bar = new byte[j]; - System.arraycopy(foo, 0, bar, 0, j); - return bar; - } catch (ArrayIndexOutOfBoundsException e) { - throw new JSchException("fromBase64: invalid base64 data", e); - } - } - - static byte[] toBase64(byte[] buf, int start, int length) { - - byte[] tmp = new byte[length * 2]; - int i, j, k; - - int foo = ((length / 3) * 3) + start; - i = 0; - for (j = start; j < foo; j += 3) { - k = (buf[j] >>> 2) & 0x3f; - tmp[i++] = b64[k]; - k = ((buf[j] & 0x03) << 4) | ((buf[j + 1] >>> 4) & 0x0f); - tmp[i++] = b64[k]; - k = ((buf[j + 1] & 0x0f) << 2) | ((buf[j + 2] >>> 6) & 0x03); - tmp[i++] = b64[k]; - k = buf[j + 2] & 0x3f; - tmp[i++] = b64[k]; - } - - foo = (start + length) - foo; - if (foo == 1) { - k = (buf[j] >>> 2) & 0x3f; - tmp[i++] = b64[k]; - k = ((buf[j] & 0x03) << 4) & 0x3f; - tmp[i++] = b64[k]; - tmp[i++] = (byte) '='; - tmp[i++] = (byte) '='; - } else if (foo == 2) { - k = (buf[j] >>> 2) & 0x3f; - tmp[i++] = b64[k]; - k = ((buf[j] & 0x03) << 4) | ((buf[j + 1] >>> 4) & 0x0f); - tmp[i++] = b64[k]; - k = ((buf[j + 1] & 0x0f) << 2) & 0x3f; - tmp[i++] = b64[k]; - tmp[i++] = (byte) '='; - } - byte[] bar = new byte[i]; - System.arraycopy(tmp, 0, bar, 0, i); - return bar; - - } - - static String[] split(String foo, String split) { - if (foo == null) { - return null; - } - byte[] buf = Util.str2byte(foo); - java.util.Vector bar = new java.util.Vector(); - int start = 0; - int index; - while (true) { - index = foo.indexOf(split, start); - if (index >= 0) { - bar.addElement(Util.byte2str(buf, start, index - start)); - start = index + 1; - continue; - } - bar.addElement(Util.byte2str(buf, start, buf.length - start)); - break; - } - String[] result = new String[bar.size()]; - for (int i = 0; i < result.length; i++) { - result[i] = (bar.elementAt(i)); - } - return result; - } - - static boolean glob(byte[] pattern, byte[] name) { - return glob0(pattern, 0, name, 0); - } - - static private boolean glob0(byte[] pattern, int pattern_index, byte[] name, int name_index) { - if ((name.length > 0) && (name[0] == '.')) { - if ((pattern.length > 0) && (pattern[0] == '.')) { - if ((pattern.length == 2) && (pattern[1] == '*')) { - return true; - } - return glob(pattern, pattern_index + 1, name, name_index + 1); - } - return false; - } - return glob(pattern, pattern_index, name, name_index); - } - - static private boolean glob(byte[] pattern, int pattern_index, byte[] name, int name_index) { - // System.err.println("glob: "+new - // String(pattern)+", "+pattern_index+" "+new - // String(name)+", "+name_index); - - int patternlen = pattern.length; - if (patternlen == 0) { - return false; - } - - int namelen = name.length; - int i = pattern_index; - int j = name_index; - - while ((i < patternlen) && (j < namelen)) { - if (pattern[i] == '\\') { - if ((i + 1) == patternlen) { - return false; - } - i++; - if (pattern[i] != name[j]) { - return false; - } - i += skipUTF8Char(pattern[i]); - j += skipUTF8Char(name[j]); - continue; - } - - if (pattern[i] == '*') { - while (i < patternlen) { - if (pattern[i] == '*') { - i++; - continue; - } - break; - } - if (patternlen == i) { - return true; - } - - byte foo = pattern[i]; - if (foo == '?') { - while (j < namelen) { - if (glob(pattern, i, name, j)) { - return true; - } - j += skipUTF8Char(name[j]); - } - return false; - } else if (foo == '\\') { - if ((i + 1) == patternlen) { - return false; - } - i++; - foo = pattern[i]; - while (j < namelen) { - if (foo == name[j]) { - if (glob(pattern, i + skipUTF8Char(foo), name, j + skipUTF8Char(name[j]))) { - return true; - } - } - j += skipUTF8Char(name[j]); - } - return false; - } - - while (j < namelen) { - if (foo == name[j]) { - if (glob(pattern, i, name, j)) { - return true; - } - } - j += skipUTF8Char(name[j]); - } - return false; - } - - if (pattern[i] == '?') { - i++; - j += skipUTF8Char(name[j]); - continue; - } - - if (pattern[i] != name[j]) { - return false; - } - - i += skipUTF8Char(pattern[i]); - j += skipUTF8Char(name[j]); - - if (!(j < namelen)) { // name is end - if (!(i < patternlen)) { // pattern is end - return true; - } - if (pattern[i] == '*') { - break; - } - } - continue; - } - - if ((i == patternlen) && (j == namelen)) { - return true; - } - - if (!(j < namelen) && // name is end - (pattern[i] == '*')) { - boolean ok = true; - while (i < patternlen) { - if (pattern[i++] != '*') { - ok = false; - break; - } - } - return ok; - } - - return false; - } - - static String quote(String path) { - byte[] _path = str2byte(path); - int count = 0; - for (int i = 0; i < _path.length; i++) { - byte b = _path[i]; - if ((b == '\\') || (b == '?') || (b == '*')) { - count++; - } - } - if (count == 0) { - return path; - } - byte[] _path2 = new byte[_path.length + count]; - for (int i = 0, j = 0; i < _path.length; i++) { - byte b = _path[i]; - if ((b == '\\') || (b == '?') || (b == '*')) { - _path2[j++] = '\\'; - } - _path2[j++] = b; - } - return byte2str(_path2); - } - - static String unquote(String path) { - byte[] foo = str2byte(path); - byte[] bar = unquote(foo); - if (foo.length == bar.length) { - return path; - } - return byte2str(bar); - } - - static byte[] unquote(byte[] path) { - int pathlen = path.length; - int i = 0; - while (i < pathlen) { - if (path[i] == '\\') { - if ((i + 1) == pathlen) { - break; - } - System.arraycopy(path, i + 1, path, i, path.length - (i + 1)); - pathlen--; - i++; - continue; - } - i++; - } - if (pathlen == path.length) { - return path; - } - byte[] foo = new byte[pathlen]; - System.arraycopy(path, 0, foo, 0, pathlen); - return foo; - } - - private static String[] chars = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; - - static String getFingerPrint(HASH hash, byte[] data) { - try { - hash.init(); - hash.update(data, 0, data.length); - byte[] foo = hash.digest(); - StringBuffer sb = new StringBuffer(); - int bar; - for (int i = 0; i < foo.length; i++) { - bar = foo[i] & 0xff; - sb.append(chars[(bar >>> 4) & 0xf]); - sb.append(chars[(bar) & 0xf]); - if ((i + 1) < foo.length) { - sb.append(":"); - } - } - return sb.toString(); - } catch (Exception e) { - return "???"; - } - } - - static boolean array_equals(byte[] foo, byte bar[]) { - int i = foo.length; - if (i != bar.length) { - return false; - } - for (int j = 0; j < i; j++) { - if (foo[j] != bar[j]) { - return false; - } - } - // try{while(true){i--; if(foo[i]!=bar[i])return false;}}catch(Exception - // e){} - return true; - } - - static Socket createSocket(String host, int port, int timeout) throws JSchException { - Socket socket = null; - if (timeout == 0) { - try { - socket = new Socket(host, port); - return socket; - } catch (Exception e) { - String message = e.toString(); - if (e instanceof Throwable) { - throw new JSchException(message, e); - } - throw new JSchException(message); - } - } - final String _host = host; - final int _port = port; - final Socket[] sockp = new Socket[1]; - final Exception[] ee = new Exception[1]; - String message = ""; - Thread tmp = new Thread(new Runnable() { - @Override - public void run() { - sockp[0] = null; - try { - sockp[0] = new Socket(_host, _port); - } catch (Exception e) { - ee[0] = e; - if ((sockp[0] != null) && sockp[0].isConnected()) { - try { - sockp[0].close(); - } catch (Exception eee) { - } - } - sockp[0] = null; - } - } - }); - tmp.setName("Opening Socket " + host); - tmp.start(); - try { - tmp.join(timeout); - message = "timeout: "; - } catch (java.lang.InterruptedException eee) { - } - if ((sockp[0] != null) && sockp[0].isConnected()) { - socket = sockp[0]; - } else { - message += "socket is not established"; - if (ee[0] != null) { - message = ee[0].toString(); - } - tmp.interrupt(); - tmp = null; - throw new JSchException(message, ee[0]); - } - return socket; - } - - static byte[] str2byte(String str, String encoding) { - if (str == null) { - return null; - } - try { - return str.getBytes(encoding); - } catch (java.io.UnsupportedEncodingException e) { - return str.getBytes(); - } - } - - static byte[] str2byte(String str) { - return str2byte(str, "UTF-8"); - } - - static String byte2str(byte[] str, String encoding) { - return byte2str(str, 0, str.length, encoding); - } - - static String byte2str(byte[] str, int s, int l, String encoding) { - try { - return new String(str, s, l, encoding); - } catch (java.io.UnsupportedEncodingException e) { - return new String(str, s, l); - } - } - - static String byte2str(byte[] str) { - return byte2str(str, 0, str.length, "UTF-8"); - } - - static String byte2str(byte[] str, int s, int l) { - return byte2str(str, s, l, "UTF-8"); - } - - static String toHex(byte[] str) { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < str.length; i++) { - String foo = Integer.toHexString(str[i] & 0xff); - sb.append("0x" + (foo.length() == 1 ? "0" : "") + foo); - if ((i + 1) < str.length) { - sb.append(":"); - } - } - return sb.toString(); - } - - static final byte[] empty = str2byte(""); - - /* - * static byte[] char2byte(char[] foo){ int len=0; for(int i=0; i>>8); bar[j++]=(byte)foo[i]; } } return bar; } - */ - static void bzero(byte[] foo) { - if (foo == null) { - return; - } - for (int i = 0; i < foo.length; i++) { - foo[i] = 0; - } - } - - static String diffString(String str, String[] not_available) { - String[] stra = Util.split(str, ","); - String result = null; - loop: for (int i = 0; i < stra.length; i++) { - for (int j = 0; j < not_available.length; j++) { - if (stra[i].equals(not_available[j])) { - continue loop; - } - } - if (result == null) { - result = stra[i]; - } else { - result = result + "," + stra[i]; - } - } - return result; - } - - static String checkTilde(String str) { - try { - if (str.startsWith("~")) { - str = str.replace("~", System.getProperty("user.home")); - } - } catch (SecurityException e) { - } - return str; - } - - private static int skipUTF8Char(byte b) { - if ((byte) (b & 0x80) == 0) { - return 1; - } - if ((byte) (b & 0xe0) == (byte) 0xc0) { - return 2; - } - if ((byte) (b & 0xf0) == (byte) 0xe0) { - return 3; - } - return 1; - } - - static byte[] fromFile(String _file) throws IOException { - _file = checkTilde(_file); - File file = new File(_file); - FileInputStream fis = new FileInputStream(_file); - try { - byte[] result = new byte[(int) (file.length())]; - int len = 0; - while (true) { - int i = fis.read(result, len, result.length - len); - if (i <= 0) { - break; - } - len += i; - } - fis.close(); - return result; - } finally { - if (fis != null) { - fis.close(); - } - } - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/DH.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/DH.java deleted file mode 100644 index c0f21e13..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/DH.java +++ /dev/null @@ -1,123 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce; - -import java.math.BigInteger; -import java.security.KeyFactory; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.PublicKey; - -import javax.crypto.KeyAgreement; -import javax.crypto.spec.DHParameterSpec; -import javax.crypto.spec.DHPublicKeySpec; - -public class DH implements autosaveworld.zlibs.com.jcraft.jsch.DH { - - BigInteger p; - BigInteger g; - BigInteger e; // my public key - byte[] e_array; - BigInteger f; // your public key - BigInteger K; // shared secret key - byte[] K_array; - - private KeyPairGenerator myKpairGen; - private KeyAgreement myKeyAgree; - - @Override - public void init() throws Exception { - myKpairGen = KeyPairGenerator.getInstance("DH"); - // myKpairGen=KeyPairGenerator.getInstance("DiffieHellman"); - myKeyAgree = KeyAgreement.getInstance("DH"); - // myKeyAgree=KeyAgreement.getInstance("DiffieHellman"); - } - - @Override - public byte[] getE() throws Exception { - if (e == null) { - DHParameterSpec dhSkipParamSpec = new DHParameterSpec(p, g); - myKpairGen.initialize(dhSkipParamSpec); - KeyPair myKpair = myKpairGen.generateKeyPair(); - myKeyAgree.init(myKpair.getPrivate()); - myKpair.getPublic().getEncoded(); - e = ((javax.crypto.interfaces.DHPublicKey) (myKpair.getPublic())).getY(); - e_array = e.toByteArray(); - } - return e_array; - } - - @Override - public byte[] getK() throws Exception { - if (K == null) { - KeyFactory myKeyFac = KeyFactory.getInstance("DH"); - DHPublicKeySpec keySpec = new DHPublicKeySpec(f, p, g); - PublicKey yourPubKey = myKeyFac.generatePublic(keySpec); - myKeyAgree.doPhase(yourPubKey, true); - byte[] mySharedSecret = myKeyAgree.generateSecret(); - K = new BigInteger(mySharedSecret); - K_array = K.toByteArray(); - - // System.err.println("K.signum(): "+K.signum()+ - // " "+Integer.toHexString(mySharedSecret[0]&0xff)+ - // " "+Integer.toHexString(K_array[0]&0xff)); - - K_array = mySharedSecret; - } - return K_array; - } - - @Override - public void setP(byte[] p) { - setP(new BigInteger(p)); - } - - @Override - public void setG(byte[] g) { - setG(new BigInteger(g)); - } - - @Override - public void setF(byte[] f) { - setF(new BigInteger(f)); - } - - void setP(BigInteger p) { - this.p = p; - } - - void setG(BigInteger g) { - this.g = g; - } - - void setF(BigInteger f) { - this.f = f; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/PBKDF.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/PBKDF.java deleted file mode 100644 index 0fddbd80..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/PBKDF.java +++ /dev/null @@ -1,55 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2013-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce; - -import java.security.NoSuchAlgorithmException; -import java.security.spec.InvalidKeySpecException; - -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.PBEKeySpec; - -public class PBKDF implements autosaveworld.zlibs.com.jcraft.jsch.PBKDF { - @Override - public byte[] getKey(byte[] _pass, byte[] salt, int iterations, int size) { - char[] pass = new char[_pass.length]; - for (int i = 0; i < _pass.length; i++) { - pass[i] = (char) (_pass[i] & 0xff); - } - try { - PBEKeySpec spec = new PBEKeySpec(pass, salt, iterations, size * 8); - SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); - byte[] key = skf.generateSecret(spec).getEncoded(); - return key; - } catch (InvalidKeySpecException e) { - } catch (NoSuchAlgorithmException e) { - } - return null; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/Random.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/Random.java deleted file mode 100644 index 4be992e2..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/Random.java +++ /dev/null @@ -1,70 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce; - -import java.security.SecureRandom; - -public class Random implements autosaveworld.zlibs.com.jcraft.jsch.Random { - private byte[] tmp = new byte[16]; - private SecureRandom random = null; - - public Random() { - - // We hope that 'new SecureRandom()' will use NativePRNG algorithm - // on Sun's Java5 for GNU/Linux and Solaris. - // It seems NativePRNG refers to /dev/urandom and it must not be - // blocked, - // but NativePRNG is slower than SHA1PRNG ;-< - // TIPS: By adding option '-Djava.security.egd=file:/dev/./urandom' - // SHA1PRNG will be used instead of NativePRNG. - // On MacOSX, 'new SecureRandom()' will use NativePRNG algorithm and - // it is also slower than SHA1PRNG. - // On Windows, 'new SecureRandom()' will use SHA1PRNG algorithm. - random = new SecureRandom(); - - /* - * try{ random=SecureRandom.getInstance("SHA1PRNG"); return; } catch(java.security.NoSuchAlgorithmException e){ // System.err.println(e); } - * - * // The following code is for IBM's JCE try{ random=SecureRandom.getInstance("IBMSecureRandom"); return; } catch(java.security.NoSuchAlgorithmException ee){ //System.err.println(ee); } - */ - } - - @Override - public void fill(byte[] foo, int start, int len) { - /* - * // This case will not become true in our usage. if(start==0 && foo.length==len){ random.nextBytes(foo); return; } - */ - if (len > tmp.length) { - tmp = new byte[len]; - } - random.nextBytes(tmp); - System.arraycopy(tmp, 0, foo, start, len); - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/SignatureDSA.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/SignatureDSA.java deleted file mode 100644 index 83b5ed2e..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/SignatureDSA.java +++ /dev/null @@ -1,143 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce; - -import java.math.BigInteger; -import java.security.KeyFactory; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.spec.DSAPrivateKeySpec; -import java.security.spec.DSAPublicKeySpec; - -public class SignatureDSA implements autosaveworld.zlibs.com.jcraft.jsch.SignatureDSA { - - java.security.Signature signature; - KeyFactory keyFactory; - - @Override - public void init() throws Exception { - signature = java.security.Signature.getInstance("SHA1withDSA"); - keyFactory = KeyFactory.getInstance("DSA"); - } - - @Override - public void setPubKey(byte[] y, byte[] p, byte[] q, byte[] g) throws Exception { - DSAPublicKeySpec dsaPubKeySpec = new DSAPublicKeySpec(new BigInteger(y), new BigInteger(p), new BigInteger(q), new BigInteger(g)); - PublicKey pubKey = keyFactory.generatePublic(dsaPubKeySpec); - signature.initVerify(pubKey); - } - - @Override - public void setPrvKey(byte[] x, byte[] p, byte[] q, byte[] g) throws Exception { - DSAPrivateKeySpec dsaPrivKeySpec = new DSAPrivateKeySpec(new BigInteger(x), new BigInteger(p), new BigInteger(q), new BigInteger(g)); - PrivateKey prvKey = keyFactory.generatePrivate(dsaPrivKeySpec); - signature.initSign(prvKey); - } - - @Override - public byte[] sign() throws Exception { - byte[] sig = signature.sign(); - /* - * System.err.print("sign["+sig.length+"] "); for(int i=0; i ivsize) { - tmp = new byte[ivsize]; - System.arraycopy(iv, 0, tmp, 0, tmp.length); - iv = tmp; - } - if (key.length > bsize) { - tmp = new byte[bsize]; - System.arraycopy(key, 0, tmp, 0, tmp.length); - key = tmp; - } - - try { - cipher = javax.crypto.Cipher.getInstance("DESede/CBC/" + pad); - /* - * // The following code does not work on IBM's JDK 1.4.1 SecretKeySpec skeySpec = new SecretKeySpec(key, "DESede"); cipher.init((mode==ENCRYPT_MODE? javax.crypto.Cipher.ENCRYPT_MODE: javax.crypto.Cipher.DECRYPT_MODE), skeySpec, new IvParameterSpec(iv)); - */ - DESedeKeySpec keyspec = new DESedeKeySpec(key); - SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede"); - SecretKey _key = keyfactory.generateSecret(keyspec); - synchronized (javax.crypto.Cipher.class) { - cipher.init((mode == ENCRYPT_MODE ? javax.crypto.Cipher.ENCRYPT_MODE : javax.crypto.Cipher.DECRYPT_MODE), _key, new IvParameterSpec(iv)); - } - } catch (Exception e) { - cipher = null; - throw e; - } - } - - @Override - public void update(byte[] foo, int s1, int len, byte[] bar, int s2) throws Exception { - cipher.update(foo, s1, len, bar, s2); - } - - @Override - public boolean isCBC() { - return true; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/TripleDESCTR.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/TripleDESCTR.java deleted file mode 100644 index 4718d570..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/TripleDESCTR.java +++ /dev/null @@ -1,96 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2008-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce; - -import javax.crypto.SecretKey; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.DESedeKeySpec; -import javax.crypto.spec.IvParameterSpec; - -import autosaveworld.zlibs.com.jcraft.jsch.Cipher; - -public class TripleDESCTR implements Cipher { - private static final int ivsize = 8; - private static final int bsize = 24; - private javax.crypto.Cipher cipher; - - @Override - public int getIVSize() { - return ivsize; - } - - @Override - public int getBlockSize() { - return bsize; - } - - @Override - public void init(int mode, byte[] key, byte[] iv) throws Exception { - String pad = "NoPadding"; - // if(padding) pad="PKCS5Padding"; - byte[] tmp; - if (iv.length > ivsize) { - tmp = new byte[ivsize]; - System.arraycopy(iv, 0, tmp, 0, tmp.length); - iv = tmp; - } - if (key.length > bsize) { - tmp = new byte[bsize]; - System.arraycopy(key, 0, tmp, 0, tmp.length); - key = tmp; - } - - try { - cipher = javax.crypto.Cipher.getInstance("DESede/CTR/" + pad); - /* - * // The following code does not work on IBM's JDK 1.4.1 SecretKeySpec skeySpec = new SecretKeySpec(key, "DESede"); cipher.init((mode==ENCRYPT_MODE? javax.crypto.Cipher.ENCRYPT_MODE: javax.crypto.Cipher.DECRYPT_MODE), skeySpec, new IvParameterSpec(iv)); - */ - DESedeKeySpec keyspec = new DESedeKeySpec(key); - SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede"); - SecretKey _key = keyfactory.generateSecret(keyspec); - synchronized (javax.crypto.Cipher.class) { - cipher.init((mode == ENCRYPT_MODE ? javax.crypto.Cipher.ENCRYPT_MODE : javax.crypto.Cipher.DECRYPT_MODE), _key, new IvParameterSpec(iv)); - } - } catch (Exception e) { - cipher = null; - throw e; - } - } - - @Override - public void update(byte[] foo, int s1, int len, byte[] bar, int s2) throws Exception { - cipher.update(foo, s1, len, bar, s2); - } - - @Override - public boolean isCBC() { - return false; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/AES128CBC.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/AES128CBC.java deleted file mode 100644 index fa799e24..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/AES128CBC.java +++ /dev/null @@ -1,88 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2005-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce.cipher; - -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -import autosaveworld.zlibs.com.jcraft.jsch.Cipher; - -public class AES128CBC implements Cipher { - private static final int ivsize = 16; - private static final int bsize = 16; - private javax.crypto.Cipher cipher; - - @Override - public int getIVSize() { - return ivsize; - } - - @Override - public int getBlockSize() { - return bsize; - } - - @Override - public void init(int mode, byte[] key, byte[] iv) throws Exception { - String pad = "NoPadding"; - byte[] tmp; - if (iv.length > ivsize) { - tmp = new byte[ivsize]; - System.arraycopy(iv, 0, tmp, 0, tmp.length); - iv = tmp; - } - if (key.length > bsize) { - tmp = new byte[bsize]; - System.arraycopy(key, 0, tmp, 0, tmp.length); - key = tmp; - } - - try { - SecretKeySpec keyspec = new SecretKeySpec(key, "AES"); - cipher = javax.crypto.Cipher.getInstance("AES/CBC/" + pad); - synchronized (javax.crypto.Cipher.class) { - cipher.init((mode == ENCRYPT_MODE ? javax.crypto.Cipher.ENCRYPT_MODE : javax.crypto.Cipher.DECRYPT_MODE), keyspec, new IvParameterSpec(iv)); - } - } catch (Exception e) { - cipher = null; - throw e; - } - } - - @Override - public void update(byte[] foo, int s1, int len, byte[] bar, int s2) throws Exception { - cipher.update(foo, s1, len, bar, s2); - } - - @Override - public boolean isCBC() { - return true; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/AES128CTR.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/AES128CTR.java deleted file mode 100644 index aec8a819..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/AES128CTR.java +++ /dev/null @@ -1,88 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2008-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce.cipher; - -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -import autosaveworld.zlibs.com.jcraft.jsch.Cipher; - -public class AES128CTR implements Cipher { - private static final int ivsize = 16; - private static final int bsize = 16; - private javax.crypto.Cipher cipher; - - @Override - public int getIVSize() { - return ivsize; - } - - @Override - public int getBlockSize() { - return bsize; - } - - @Override - public void init(int mode, byte[] key, byte[] iv) throws Exception { - String pad = "NoPadding"; - byte[] tmp; - if (iv.length > ivsize) { - tmp = new byte[ivsize]; - System.arraycopy(iv, 0, tmp, 0, tmp.length); - iv = tmp; - } - if (key.length > bsize) { - tmp = new byte[bsize]; - System.arraycopy(key, 0, tmp, 0, tmp.length); - key = tmp; - } - - try { - SecretKeySpec keyspec = new SecretKeySpec(key, "AES"); - cipher = javax.crypto.Cipher.getInstance("AES/CTR/" + pad); - synchronized (javax.crypto.Cipher.class) { - cipher.init((mode == ENCRYPT_MODE ? javax.crypto.Cipher.ENCRYPT_MODE : javax.crypto.Cipher.DECRYPT_MODE), keyspec, new IvParameterSpec(iv)); - } - } catch (Exception e) { - cipher = null; - throw e; - } - } - - @Override - public void update(byte[] foo, int s1, int len, byte[] bar, int s2) throws Exception { - cipher.update(foo, s1, len, bar, s2); - } - - @Override - public boolean isCBC() { - return false; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/AES192CBC.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/AES192CBC.java deleted file mode 100644 index bfdcb7c3..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/AES192CBC.java +++ /dev/null @@ -1,87 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2005-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce.cipher; - -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -import autosaveworld.zlibs.com.jcraft.jsch.Cipher; - -public class AES192CBC implements Cipher { - private static final int ivsize = 16; - private static final int bsize = 24; - private javax.crypto.Cipher cipher; - - @Override - public int getIVSize() { - return ivsize; - } - - @Override - public int getBlockSize() { - return bsize; - } - - @Override - public void init(int mode, byte[] key, byte[] iv) throws Exception { - String pad = "NoPadding"; - byte[] tmp; - if (iv.length > ivsize) { - tmp = new byte[ivsize]; - System.arraycopy(iv, 0, tmp, 0, tmp.length); - iv = tmp; - } - if (key.length > bsize) { - tmp = new byte[bsize]; - System.arraycopy(key, 0, tmp, 0, tmp.length); - key = tmp; - } - try { - SecretKeySpec keyspec = new SecretKeySpec(key, "AES"); - cipher = javax.crypto.Cipher.getInstance("AES/CBC/" + pad); - synchronized (javax.crypto.Cipher.class) { - cipher.init((mode == ENCRYPT_MODE ? javax.crypto.Cipher.ENCRYPT_MODE : javax.crypto.Cipher.DECRYPT_MODE), keyspec, new IvParameterSpec(iv)); - } - } catch (Exception e) { - cipher = null; - throw e; - } - } - - @Override - public void update(byte[] foo, int s1, int len, byte[] bar, int s2) throws Exception { - cipher.update(foo, s1, len, bar, s2); - } - - @Override - public boolean isCBC() { - return true; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/AES192CTR.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/AES192CTR.java deleted file mode 100644 index a4328e77..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/AES192CTR.java +++ /dev/null @@ -1,87 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2008-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce.cipher; - -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -import autosaveworld.zlibs.com.jcraft.jsch.Cipher; - -public class AES192CTR implements Cipher { - private static final int ivsize = 16; - private static final int bsize = 24; - private javax.crypto.Cipher cipher; - - @Override - public int getIVSize() { - return ivsize; - } - - @Override - public int getBlockSize() { - return bsize; - } - - @Override - public void init(int mode, byte[] key, byte[] iv) throws Exception { - String pad = "NoPadding"; - byte[] tmp; - if (iv.length > ivsize) { - tmp = new byte[ivsize]; - System.arraycopy(iv, 0, tmp, 0, tmp.length); - iv = tmp; - } - if (key.length > bsize) { - tmp = new byte[bsize]; - System.arraycopy(key, 0, tmp, 0, tmp.length); - key = tmp; - } - try { - SecretKeySpec keyspec = new SecretKeySpec(key, "AES"); - cipher = javax.crypto.Cipher.getInstance("AES/CTR/" + pad); - synchronized (javax.crypto.Cipher.class) { - cipher.init((mode == ENCRYPT_MODE ? javax.crypto.Cipher.ENCRYPT_MODE : javax.crypto.Cipher.DECRYPT_MODE), keyspec, new IvParameterSpec(iv)); - } - } catch (Exception e) { - cipher = null; - throw e; - } - } - - @Override - public void update(byte[] foo, int s1, int len, byte[] bar, int s2) throws Exception { - cipher.update(foo, s1, len, bar, s2); - } - - @Override - public boolean isCBC() { - return false; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/AES256CBC.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/AES256CBC.java deleted file mode 100644 index a9fc3071..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/AES256CBC.java +++ /dev/null @@ -1,87 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2005-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce.cipher; - -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -import autosaveworld.zlibs.com.jcraft.jsch.Cipher; - -public class AES256CBC implements Cipher { - private static final int ivsize = 16; - private static final int bsize = 32; - private javax.crypto.Cipher cipher; - - @Override - public int getIVSize() { - return ivsize; - } - - @Override - public int getBlockSize() { - return bsize; - } - - @Override - public void init(int mode, byte[] key, byte[] iv) throws Exception { - String pad = "NoPadding"; - byte[] tmp; - if (iv.length > ivsize) { - tmp = new byte[ivsize]; - System.arraycopy(iv, 0, tmp, 0, tmp.length); - iv = tmp; - } - if (key.length > bsize) { - tmp = new byte[bsize]; - System.arraycopy(key, 0, tmp, 0, tmp.length); - key = tmp; - } - try { - SecretKeySpec keyspec = new SecretKeySpec(key, "AES"); - cipher = javax.crypto.Cipher.getInstance("AES/CBC/" + pad); - synchronized (javax.crypto.Cipher.class) { - cipher.init((mode == ENCRYPT_MODE ? javax.crypto.Cipher.ENCRYPT_MODE : javax.crypto.Cipher.DECRYPT_MODE), keyspec, new IvParameterSpec(iv)); - } - } catch (Exception e) { - cipher = null; - throw e; - } - } - - @Override - public void update(byte[] foo, int s1, int len, byte[] bar, int s2) throws Exception { - cipher.update(foo, s1, len, bar, s2); - } - - @Override - public boolean isCBC() { - return true; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/AES256CTR.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/AES256CTR.java deleted file mode 100644 index 84287c48..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/AES256CTR.java +++ /dev/null @@ -1,87 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2008-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce.cipher; - -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -import autosaveworld.zlibs.com.jcraft.jsch.Cipher; - -public class AES256CTR implements Cipher { - private static final int ivsize = 16; - private static final int bsize = 32; - private javax.crypto.Cipher cipher; - - @Override - public int getIVSize() { - return ivsize; - } - - @Override - public int getBlockSize() { - return bsize; - } - - @Override - public void init(int mode, byte[] key, byte[] iv) throws Exception { - String pad = "NoPadding"; - byte[] tmp; - if (iv.length > ivsize) { - tmp = new byte[ivsize]; - System.arraycopy(iv, 0, tmp, 0, tmp.length); - iv = tmp; - } - if (key.length > bsize) { - tmp = new byte[bsize]; - System.arraycopy(key, 0, tmp, 0, tmp.length); - key = tmp; - } - try { - SecretKeySpec keyspec = new SecretKeySpec(key, "AES"); - cipher = javax.crypto.Cipher.getInstance("AES/CTR/" + pad); - synchronized (javax.crypto.Cipher.class) { - cipher.init((mode == ENCRYPT_MODE ? javax.crypto.Cipher.ENCRYPT_MODE : javax.crypto.Cipher.DECRYPT_MODE), keyspec, new IvParameterSpec(iv)); - } - } catch (Exception e) { - cipher = null; - throw e; - } - } - - @Override - public void update(byte[] foo, int s1, int len, byte[] bar, int s2) throws Exception { - cipher.update(foo, s1, len, bar, s2); - } - - @Override - public boolean isCBC() { - return false; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/ARCFOUR.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/ARCFOUR.java deleted file mode 100644 index ba2b99e9..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/ARCFOUR.java +++ /dev/null @@ -1,82 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2008-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce.cipher; - -import javax.crypto.spec.SecretKeySpec; - -import autosaveworld.zlibs.com.jcraft.jsch.Cipher; - -public class ARCFOUR implements Cipher { - - private static final int ivsize = 8; - private static final int bsize = 16; - private javax.crypto.Cipher cipher; - - @Override - public int getIVSize() { - return ivsize; - } - - @Override - public int getBlockSize() { - return bsize; - } - - @Override - public void init(int mode, byte[] key, byte[] iv) throws Exception { - byte[] tmp; - if (key.length > bsize) { - tmp = new byte[bsize]; - System.arraycopy(key, 0, tmp, 0, tmp.length); - key = tmp; - } - - try { - cipher = javax.crypto.Cipher.getInstance("RC4"); - SecretKeySpec _key = new SecretKeySpec(key, "RC4"); - synchronized (javax.crypto.Cipher.class) { - cipher.init((mode == ENCRYPT_MODE ? javax.crypto.Cipher.ENCRYPT_MODE : javax.crypto.Cipher.DECRYPT_MODE), _key); - } - } catch (Exception e) { - cipher = null; - throw e; - } - } - - @Override - public void update(byte[] foo, int s1, int len, byte[] bar, int s2) throws Exception { - cipher.update(foo, s1, len, bar, s2); - } - - @Override - public boolean isCBC() { - return false; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/ARCFOUR128.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/ARCFOUR128.java deleted file mode 100644 index d0ed0236..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/ARCFOUR128.java +++ /dev/null @@ -1,85 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2008-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce.cipher; - -import javax.crypto.spec.SecretKeySpec; - -import autosaveworld.zlibs.com.jcraft.jsch.Cipher; - -public class ARCFOUR128 implements Cipher { - private static final int ivsize = 8; - private static final int bsize = 16; - private static final int skip = 1536; - private javax.crypto.Cipher cipher; - - @Override - public int getIVSize() { - return ivsize; - } - - @Override - public int getBlockSize() { - return bsize; - } - - @Override - public void init(int mode, byte[] key, byte[] iv) throws Exception { - byte[] tmp; - if (key.length > bsize) { - tmp = new byte[bsize]; - System.arraycopy(key, 0, tmp, 0, tmp.length); - key = tmp; - } - try { - cipher = javax.crypto.Cipher.getInstance("RC4"); - SecretKeySpec _key = new SecretKeySpec(key, "RC4"); - synchronized (javax.crypto.Cipher.class) { - cipher.init((mode == ENCRYPT_MODE ? javax.crypto.Cipher.ENCRYPT_MODE : javax.crypto.Cipher.DECRYPT_MODE), _key); - } - byte[] foo = new byte[1]; - for (int i = 0; i < skip; i++) { - cipher.update(foo, 0, 1, foo, 0); - } - } catch (Exception e) { - cipher = null; - throw e; - } - } - - @Override - public void update(byte[] foo, int s1, int len, byte[] bar, int s2) throws Exception { - cipher.update(foo, s1, len, bar, s2); - } - - @Override - public boolean isCBC() { - return false; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/ARCFOUR256.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/ARCFOUR256.java deleted file mode 100644 index a5c00cbf..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/ARCFOUR256.java +++ /dev/null @@ -1,85 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2008-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce.cipher; - -import javax.crypto.spec.SecretKeySpec; - -import autosaveworld.zlibs.com.jcraft.jsch.Cipher; - -public class ARCFOUR256 implements Cipher { - private static final int ivsize = 8; - private static final int bsize = 32; - private static final int skip = 1536; - private javax.crypto.Cipher cipher; - - @Override - public int getIVSize() { - return ivsize; - } - - @Override - public int getBlockSize() { - return bsize; - } - - @Override - public void init(int mode, byte[] key, byte[] iv) throws Exception { - byte[] tmp; - if (key.length > bsize) { - tmp = new byte[bsize]; - System.arraycopy(key, 0, tmp, 0, tmp.length); - key = tmp; - } - try { - cipher = javax.crypto.Cipher.getInstance("RC4"); - SecretKeySpec _key = new SecretKeySpec(key, "RC4"); - synchronized (javax.crypto.Cipher.class) { - cipher.init((mode == ENCRYPT_MODE ? javax.crypto.Cipher.ENCRYPT_MODE : javax.crypto.Cipher.DECRYPT_MODE), _key); - } - byte[] foo = new byte[1]; - for (int i = 0; i < skip; i++) { - cipher.update(foo, 0, 1, foo, 0); - } - } catch (Exception e) { - cipher = null; - throw e; - } - } - - @Override - public void update(byte[] foo, int s1, int len, byte[] bar, int s2) throws Exception { - cipher.update(foo, s1, len, bar, s2); - } - - @Override - public boolean isCBC() { - return false; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/BlowfishCBC.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/BlowfishCBC.java deleted file mode 100644 index eb02bcc5..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/cipher/BlowfishCBC.java +++ /dev/null @@ -1,87 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce.cipher; - -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -import autosaveworld.zlibs.com.jcraft.jsch.Cipher; - -public class BlowfishCBC implements Cipher { - private static final int ivsize = 8; - private static final int bsize = 16; - private javax.crypto.Cipher cipher; - - @Override - public int getIVSize() { - return ivsize; - } - - @Override - public int getBlockSize() { - return bsize; - } - - @Override - public void init(int mode, byte[] key, byte[] iv) throws Exception { - String pad = "NoPadding"; - // if(padding) pad="PKCS5Padding"; - byte[] tmp; - if (iv.length > ivsize) { - tmp = new byte[ivsize]; - System.arraycopy(iv, 0, tmp, 0, tmp.length); - iv = tmp; - } - if (key.length > bsize) { - tmp = new byte[bsize]; - System.arraycopy(key, 0, tmp, 0, tmp.length); - key = tmp; - } - try { - SecretKeySpec skeySpec = new SecretKeySpec(key, "Blowfish"); - cipher = javax.crypto.Cipher.getInstance("Blowfish/CBC/" + pad); - synchronized (javax.crypto.Cipher.class) { - cipher.init((mode == ENCRYPT_MODE ? javax.crypto.Cipher.ENCRYPT_MODE : javax.crypto.Cipher.DECRYPT_MODE), skeySpec, new IvParameterSpec(iv)); - } - } catch (Exception e) { - throw e; - } - } - - @Override - public void update(byte[] foo, int s1, int len, byte[] bar, int s2) throws Exception { - cipher.update(foo, s1, len, bar, s2); - } - - @Override - public boolean isCBC() { - return true; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/hash/MD5.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/hash/MD5.java deleted file mode 100644 index c1c0aa2c..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/hash/MD5.java +++ /dev/null @@ -1,62 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce.hash; - -import java.security.MessageDigest; - -import autosaveworld.zlibs.com.jcraft.jsch.HASH; - -public class MD5 implements HASH { - MessageDigest md; - - @Override - public int getBlockSize() { - return 16; - } - - @Override - public void init() throws Exception { - try { - md = MessageDigest.getInstance("MD5"); - } catch (Exception e) { - System.err.println(e); - } - } - - @Override - public void update(byte[] foo, int start, int len) throws Exception { - md.update(foo, start, len); - } - - @Override - public byte[] digest() throws Exception { - return md.digest(); - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/hash/SHA1.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/hash/SHA1.java deleted file mode 100644 index a9fdf6fc..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/hash/SHA1.java +++ /dev/null @@ -1,62 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce.hash; - -import java.security.MessageDigest; - -import autosaveworld.zlibs.com.jcraft.jsch.HASH; - -public class SHA1 implements HASH { - MessageDigest md; - - @Override - public int getBlockSize() { - return 20; - } - - @Override - public void init() throws Exception { - try { - md = MessageDigest.getInstance("SHA-1"); - } catch (Exception e) { - System.err.println(e); - } - } - - @Override - public void update(byte[] foo, int start, int len) throws Exception { - md.update(foo, start, len); - } - - @Override - public byte[] digest() throws Exception { - return md.digest(); - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/hash/SHA256.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/hash/SHA256.java deleted file mode 100644 index 8371afbf..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/hash/SHA256.java +++ /dev/null @@ -1,62 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce.hash; - -import java.security.MessageDigest; - -import autosaveworld.zlibs.com.jcraft.jsch.HASH; - -public class SHA256 implements HASH { - MessageDigest md; - - @Override - public int getBlockSize() { - return 32; - } - - @Override - public void init() throws Exception { - try { - md = MessageDigest.getInstance("SHA-256"); - } catch (Exception e) { - System.err.println(e); - } - } - - @Override - public void update(byte[] foo, int start, int len) throws Exception { - md.update(foo, start, len); - } - - @Override - public byte[] digest() throws Exception { - return md.digest(); - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/mac/HMAC.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/mac/HMAC.java deleted file mode 100644 index 76ae9a0c..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/mac/HMAC.java +++ /dev/null @@ -1,90 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2012-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce.mac; - -import javax.crypto.Mac; -import javax.crypto.ShortBufferException; -import javax.crypto.spec.SecretKeySpec; - -import autosaveworld.zlibs.com.jcraft.jsch.MAC; - -abstract class HMAC implements MAC { - protected String name; - protected int bsize; - protected String algorithm; - private Mac mac; - - @Override - public int getBlockSize() { - return bsize; - }; - - @Override - public void init(byte[] key) throws Exception { - if (key.length > bsize) { - byte[] tmp = new byte[bsize]; - System.arraycopy(key, 0, tmp, 0, bsize); - key = tmp; - } - SecretKeySpec skey = new SecretKeySpec(key, algorithm); - mac = Mac.getInstance(algorithm); - mac.init(skey); - } - - private final byte[] tmp = new byte[4]; - - @Override - public void update(int i) { - tmp[0] = (byte) (i >>> 24); - tmp[1] = (byte) (i >>> 16); - tmp[2] = (byte) (i >>> 8); - tmp[3] = (byte) i; - update(tmp, 0, 4); - } - - @Override - public void update(byte foo[], int s, int l) { - mac.update(foo, s, l); - } - - @Override - public void doFinal(byte[] buf, int offset) { - try { - mac.doFinal(buf, offset); - } catch (ShortBufferException e) { - System.err.println(e); - } - } - - @Override - public String getName() { - return name; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/mac/HMACMD5.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/mac/HMACMD5.java deleted file mode 100644 index 2a23b5aa..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/mac/HMACMD5.java +++ /dev/null @@ -1,38 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce.mac; - -public class HMACMD5 extends HMAC { - public HMACMD5() { - name = "hmac-md5"; - bsize = 16; - algorithm = "HmacMD5"; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/mac/HMACMD596.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/mac/HMACMD596.java deleted file mode 100644 index dc5f1d01..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/mac/HMACMD596.java +++ /dev/null @@ -1,49 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce.mac; - -public class HMACMD596 extends HMACMD5 { - public HMACMD596() { - name = "hmac-md5-96"; - } - - @Override - public int getBlockSize() { - return 12; - }; - - private final byte[] _buf16 = new byte[16]; - - @Override - public void doFinal(byte[] buf, int offset) { - super.doFinal(_buf16, 0); - System.arraycopy(_buf16, 0, buf, offset, 12); - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/mac/HMACSHA1.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/mac/HMACSHA1.java deleted file mode 100644 index e225befb..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/mac/HMACSHA1.java +++ /dev/null @@ -1,38 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce.mac; - -public class HMACSHA1 extends HMAC { - public HMACSHA1() { - name = "hmac-sha1"; - bsize = 20; - algorithm = "HmacSHA1"; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/mac/HMACSHA196.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/mac/HMACSHA196.java deleted file mode 100644 index 2d037146..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/mac/HMACSHA196.java +++ /dev/null @@ -1,50 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2002-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce.mac; - -public class HMACSHA196 extends HMACSHA1 { - - public HMACSHA196() { - name = "hmac-sha1-96"; - } - - @Override - public int getBlockSize() { - return 12; - }; - - private final byte[] _buf20 = new byte[20]; - - @Override - public void doFinal(byte[] buf, int offset) { - super.doFinal(_buf20, 0); - System.arraycopy(_buf20, 0, buf, offset, 12); - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/mac/HMACSHA256.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/mac/HMACSHA256.java deleted file mode 100644 index e9cefa97..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/mac/HMACSHA256.java +++ /dev/null @@ -1,38 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2012-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce.mac; - -public class HMACSHA256 extends HMAC { - public HMACSHA256() { - name = "hmac-sha2-256"; - bsize = 32; - algorithm = "HmacSHA256"; - } -} diff --git a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/mac/HMACSHA512.java b/src/autosaveworld/zlibs/com/jcraft/jsch/jce/mac/HMACSHA512.java deleted file mode 100644 index 866c2eda..00000000 --- a/src/autosaveworld/zlibs/com/jcraft/jsch/jce/mac/HMACSHA512.java +++ /dev/null @@ -1,38 +0,0 @@ -/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ -/* - Copyright (c) 2012-2014 ymnk, JCraft,Inc. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution. - - 3. The names of the authors may not be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, - INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, - INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, - INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, - EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package autosaveworld.zlibs.com.jcraft.jsch.jce.mac; - -public class HMACSHA512 extends HMAC { - public HMACSHA512() { - name = "hmac-sha2-512"; - bsize = 64; - algorithm = "HmacSHA512"; - } -} diff --git a/src/autosaveworld/zlibs/org/apache/commons/net/DefaultSocketFactory.java b/src/autosaveworld/zlibs/org/apache/commons/net/DefaultSocketFactory.java deleted file mode 100644 index 19998048..00000000 --- a/src/autosaveworld/zlibs/org/apache/commons/net/DefaultSocketFactory.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package autosaveworld.zlibs.org.apache.commons.net; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Proxy; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.UnknownHostException; - -import javax.net.SocketFactory; - -public class DefaultSocketFactory extends SocketFactory { - - private final Proxy connProxy; - - public DefaultSocketFactory() { - this(null); - } - - public DefaultSocketFactory(Proxy proxy) { - connProxy = proxy; - } - - @Override - public Socket createSocket() throws IOException { - if (connProxy != null) { - return new Socket(connProxy); - } - return new Socket(); - } - - @Override - public Socket createSocket(String host, int port) throws UnknownHostException, IOException { - if (connProxy != null) { - Socket s = new Socket(connProxy); - s.connect(new InetSocketAddress(host, port)); - return s; - } - return new Socket(host, port); - } - - @Override - public Socket createSocket(InetAddress address, int port) throws IOException { - if (connProxy != null) { - Socket s = new Socket(connProxy); - s.connect(new InetSocketAddress(address, port)); - return s; - } - return new Socket(address, port); - } - - @Override - public Socket createSocket(String host, int port, InetAddress localAddr, int localPort) throws UnknownHostException, IOException { - if (connProxy != null) { - Socket s = new Socket(connProxy); - s.bind(new InetSocketAddress(localAddr, localPort)); - s.connect(new InetSocketAddress(host, port)); - return s; - } - return new Socket(host, port, localAddr, localPort); - } - - @Override - public Socket createSocket(InetAddress address, int port, InetAddress localAddr, int localPort) throws IOException { - if (connProxy != null) { - Socket s = new Socket(connProxy); - s.bind(new InetSocketAddress(localAddr, localPort)); - s.connect(new InetSocketAddress(address, port)); - return s; - } - return new Socket(address, port, localAddr, localPort); - } - - public ServerSocket createServerSocket(int port) throws IOException { - return new ServerSocket(port); - } - - public ServerSocket createServerSocket(int port, int backlog) throws IOException { - return new ServerSocket(port, backlog); - } - - public ServerSocket createServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException { - return new ServerSocket(port, backlog, bindAddr); - } - -} diff --git a/src/autosaveworld/zlibs/org/apache/commons/net/MalformedServerReplyException.java b/src/autosaveworld/zlibs/org/apache/commons/net/MalformedServerReplyException.java deleted file mode 100644 index dbde8275..00000000 --- a/src/autosaveworld/zlibs/org/apache/commons/net/MalformedServerReplyException.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package autosaveworld.zlibs.org.apache.commons.net; - -import java.io.IOException; - -public class MalformedServerReplyException extends IOException { - - private static final long serialVersionUID = 6006765264250543945L; - - public MalformedServerReplyException() { - super(); - } - - public MalformedServerReplyException(String message) { - super(message); - } - -} diff --git a/src/autosaveworld/zlibs/org/apache/commons/net/SocketClient.java b/src/autosaveworld/zlibs/org/apache/commons/net/SocketClient.java deleted file mode 100644 index c7f0cb7e..00000000 --- a/src/autosaveworld/zlibs/org/apache/commons/net/SocketClient.java +++ /dev/null @@ -1,337 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package autosaveworld.zlibs.org.apache.commons.net; - -import java.io.Closeable; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Proxy; -import java.net.Socket; -import java.net.SocketException; -import java.nio.charset.Charset; - -import javax.net.ServerSocketFactory; -import javax.net.SocketFactory; - -/** - * The SocketClient provides the basic operations that are required of client objects accessing sockets. It is meant to be subclassed to avoid having to rewrite the same code over and over again to open a socket, close a socket, set timeouts, etc. Of special note is the {@link #setSocketFactory setSocketFactory } method, which allows you to control the type of Socket the SocketClient creates for initiating network connections. This is especially useful for adding SSL or proxy support as well as - * better support for applets. For example, you could create a {@link javax.net.SocketFactory} that requests browser security capabilities before creating a socket. All classes derived from SocketClient should use the {@link #_socketFactory_ _socketFactory_ } member variable to create Socket and ServerSocket instances rather than instantiating them by directly invoking a constructor. By honoring this contract you guarantee that a user will always be able to provide his own Socket implementations - * by substituting his own SocketFactory. - * - * @see SocketFactory - */ -public abstract class SocketClient { - - public static final String NETASCII_EOL = "\r\n"; - - private static final SocketFactory __DEFAULT_SOCKET_FACTORY = SocketFactory.getDefault(); - - private static final ServerSocketFactory __DEFAULT_SERVER_SOCKET_FACTORY = ServerSocketFactory.getDefault(); - - protected int _timeout_; - - protected Socket _socket_; - - protected int _defaultPort_; - - protected InputStream _input_; - - protected OutputStream _output_; - - protected SocketFactory _socketFactory_; - - protected ServerSocketFactory _serverSocketFactory_; - - private static final int DEFAULT_CONNECT_TIMEOUT = 0; - protected int connectTimeout = DEFAULT_CONNECT_TIMEOUT; - - private int receiveBufferSize = -1; - - private int sendBufferSize = -1; - - private Proxy connProxy; - - private Charset charset = Charset.defaultCharset(); - - public SocketClient() { - _socket_ = null; - _input_ = null; - _output_ = null; - _timeout_ = 0; - _defaultPort_ = 0; - _socketFactory_ = __DEFAULT_SOCKET_FACTORY; - _serverSocketFactory_ = __DEFAULT_SERVER_SOCKET_FACTORY; - } - - protected void _connectAction_() throws IOException { - _socket_.setSoTimeout(_timeout_); - _input_ = _socket_.getInputStream(); - _output_ = _socket_.getOutputStream(); - } - - public void connect(InetAddress host, int port) throws SocketException, IOException { - _socket_ = _socketFactory_.createSocket(); - if (receiveBufferSize != -1) { - _socket_.setReceiveBufferSize(receiveBufferSize); - } - if (sendBufferSize != -1) { - _socket_.setSendBufferSize(sendBufferSize); - } - _socket_.connect(new InetSocketAddress(host, port), connectTimeout); - _connectAction_(); - } - - public void connect(String hostname, int port) throws SocketException, IOException { - connect(InetAddress.getByName(hostname), port); - } - - public void connect(InetAddress host, int port, InetAddress localAddr, int localPort) throws SocketException, IOException { - _socket_ = _socketFactory_.createSocket(); - if (receiveBufferSize != -1) { - _socket_.setReceiveBufferSize(receiveBufferSize); - } - if (sendBufferSize != -1) { - _socket_.setSendBufferSize(sendBufferSize); - } - _socket_.bind(new InetSocketAddress(localAddr, localPort)); - _socket_.connect(new InetSocketAddress(host, port), connectTimeout); - _connectAction_(); - } - - public void connect(String hostname, int port, InetAddress localAddr, int localPort) throws SocketException, IOException { - connect(InetAddress.getByName(hostname), port, localAddr, localPort); - } - - public void connect(InetAddress host) throws SocketException, IOException { - connect(host, _defaultPort_); - } - - public void connect(String hostname) throws SocketException, IOException { - connect(hostname, _defaultPort_); - } - - public void disconnect() throws IOException { - closeQuietly(_socket_); - closeQuietly(_input_); - closeQuietly(_output_); - _socket_ = null; - _input_ = null; - _output_ = null; - } - - private void closeQuietly(Socket socket) { - if (socket != null) { - try { - socket.close(); - } catch (IOException e) { - } - } - } - - private void closeQuietly(Closeable close) { - if (close != null) { - try { - close.close(); - } catch (IOException e) { - } - } - } - - public boolean isConnected() { - if (_socket_ == null) { - return false; - } - - return _socket_.isConnected(); - } - - public boolean isAvailable() { - if (isConnected()) { - try { - if (_socket_.getInetAddress() == null) { - return false; - } - if (_socket_.getPort() == 0) { - return false; - } - if (_socket_.getRemoteSocketAddress() == null) { - return false; - } - if (_socket_.isClosed()) { - return false; - } - if (_socket_.isInputShutdown()) { - return false; - } - if (_socket_.isOutputShutdown()) { - return false; - } - _socket_.getInputStream(); - _socket_.getOutputStream(); - } catch (IOException ioex) { - return false; - } - return true; - } else { - return false; - } - } - - public void setDefaultPort(int port) { - _defaultPort_ = port; - } - - public int getDefaultPort() { - return _defaultPort_; - } - - public void setDefaultTimeout(int timeout) { - _timeout_ = timeout; - } - - public int getDefaultTimeout() { - return _timeout_; - } - - public void setSoTimeout(int timeout) throws SocketException { - _socket_.setSoTimeout(timeout); - } - - public void setSendBufferSize(int size) throws SocketException { - sendBufferSize = size; - } - - protected int getSendBufferSize() { - return sendBufferSize; - } - - public void setReceiveBufferSize(int size) throws SocketException { - receiveBufferSize = size; - } - - protected int getReceiveBufferSize() { - return receiveBufferSize; - } - - public int getSoTimeout() throws SocketException { - return _socket_.getSoTimeout(); - } - - public void setTcpNoDelay(boolean on) throws SocketException { - _socket_.setTcpNoDelay(on); - } - - public boolean getTcpNoDelay() throws SocketException { - return _socket_.getTcpNoDelay(); - } - - public void setKeepAlive(boolean keepAlive) throws SocketException { - _socket_.setKeepAlive(keepAlive); - } - - public boolean getKeepAlive() throws SocketException { - return _socket_.getKeepAlive(); - } - - public void setSoLinger(boolean on, int val) throws SocketException { - _socket_.setSoLinger(on, val); - } - - public int getSoLinger() throws SocketException { - return _socket_.getSoLinger(); - } - - public int getLocalPort() { - return _socket_.getLocalPort(); - } - - public InetAddress getLocalAddress() { - return _socket_.getLocalAddress(); - } - - public int getRemotePort() { - return _socket_.getPort(); - } - - public InetAddress getRemoteAddress() { - return _socket_.getInetAddress(); - } - - public boolean verifyRemote(Socket socket) { - InetAddress host1, host2; - - host1 = socket.getInetAddress(); - host2 = getRemoteAddress(); - - return host1.equals(host2); - } - - public void setSocketFactory(SocketFactory factory) { - if (factory == null) { - _socketFactory_ = __DEFAULT_SOCKET_FACTORY; - } else { - _socketFactory_ = factory; - } - connProxy = null; - } - - public void setServerSocketFactory(ServerSocketFactory factory) { - if (factory == null) { - _serverSocketFactory_ = __DEFAULT_SERVER_SOCKET_FACTORY; - } else { - _serverSocketFactory_ = factory; - } - } - - public void setConnectTimeout(int connectTimeout) { - this.connectTimeout = connectTimeout; - } - - public int getConnectTimeout() { - return connectTimeout; - } - - public ServerSocketFactory getServerSocketFactory() { - return _serverSocketFactory_; - } - - public void setProxy(Proxy proxy) { - setSocketFactory(new DefaultSocketFactory(proxy)); - connProxy = proxy; - } - - public Proxy getProxy() { - return connProxy; - } - - public String getCharsetName() { - return charset.name(); - } - - public Charset getCharset() { - return charset; - } - - public void setCharset(Charset charset) { - this.charset = charset; - } - -} diff --git a/src/autosaveworld/zlibs/org/apache/commons/net/ftp/FTP.java b/src/autosaveworld/zlibs/org/apache/commons/net/ftp/FTP.java deleted file mode 100644 index 38943169..00000000 --- a/src/autosaveworld/zlibs/org/apache/commons/net/ftp/FTP.java +++ /dev/null @@ -1,537 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package autosaveworld.zlibs.org.apache.commons.net.ftp; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.net.Inet4Address; -import java.net.Inet6Address; -import java.net.InetAddress; -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.util.ArrayList; - -import autosaveworld.zlibs.org.apache.commons.net.MalformedServerReplyException; -import autosaveworld.zlibs.org.apache.commons.net.SocketClient; -import autosaveworld.zlibs.org.apache.commons.net.io.CRLFLineReader; - -public class FTP extends SocketClient { - - public static final int DEFAULT_DATA_PORT = 20; - - public static final int DEFAULT_PORT = 21; - - public static final int EBCDIC_FILE_TYPE = 1; - - public static final int BINARY_FILE_TYPE = 2; - - public static final int LOCAL_FILE_TYPE = 3; - - public static final int NON_PRINT_TEXT_FORMAT = 4; - - public static final int TELNET_TEXT_FORMAT = 5; - - public static final int CARRIAGE_CONTROL_TEXT_FORMAT = 6; - - public static final int FILE_STRUCTURE = 7; - - public static final int RECORD_STRUCTURE = 8; - - public static final int PAGE_STRUCTURE = 9; - - public static final int STREAM_TRANSFER_MODE = 10; - - public static final int BLOCK_TRANSFER_MODE = 11; - - public static final int COMPRESSED_TRANSFER_MODE = 12; - - public static final String DEFAULT_CONTROL_ENCODING = "ISO-8859-1"; - - public static final int REPLY_CODE_LEN = 3; - - private static final String __modes = "AEILNTCFRPSBC"; - - protected int _replyCode; - protected ArrayList _replyLines; - protected boolean _newReplyString; - protected String _replyString; - protected String _controlEncoding; - - protected boolean strictMultilineParsing = false; - - protected BufferedReader _controlInput_; - - protected BufferedWriter _controlOutput_; - - public FTP() { - super(); - setDefaultPort(DEFAULT_PORT); - _replyLines = new ArrayList(); - _newReplyString = false; - _replyString = null; - _controlEncoding = DEFAULT_CONTROL_ENCODING; - } - - private boolean __strictCheck(String line, String code) { - return (!(line.startsWith(code) && (line.charAt(REPLY_CODE_LEN) == ' '))); - } - - private boolean __lenientCheck(String line) { - return (!((line.length() > REPLY_CODE_LEN) && (line.charAt(REPLY_CODE_LEN) != '-') && Character.isDigit(line.charAt(0)))); - } - - private void __getReply() throws IOException { - __getReply(true); - } - - protected void __getReplyNoReport() throws IOException { - __getReply(false); - } - - private void __getReply(boolean reportReply) throws IOException { - int length; - - _newReplyString = true; - _replyLines.clear(); - - String line = _controlInput_.readLine(); - - if (line == null) { - throw new FTPConnectionClosedException("Connection closed without indication."); - } - - length = line.length(); - if (length < REPLY_CODE_LEN) { - throw new MalformedServerReplyException("Truncated server reply: " + line); - } - - String code = null; - try { - code = line.substring(0, REPLY_CODE_LEN); - _replyCode = Integer.parseInt(code); - } catch (NumberFormatException e) { - throw new MalformedServerReplyException("Could not parse response code.\nServer Reply: " + line); - } - - _replyLines.add(line); - - if ((length > REPLY_CODE_LEN) && (line.charAt(REPLY_CODE_LEN) == '-')) { - do { - line = _controlInput_.readLine(); - - if (line == null) { - throw new FTPConnectionClosedException("Connection closed without indication."); - } - - _replyLines.add(line); - - } while (isStrictMultilineParsing() ? __strictCheck(line, code) : __lenientCheck(line)); - } - - if (_replyCode == FTPReply.SERVICE_NOT_AVAILABLE) { - throw new FTPConnectionClosedException("FTP response 421 received. Server closed connection."); - } - } - - @Override - protected void _connectAction_() throws IOException { - super._connectAction_(); - _controlInput_ = new CRLFLineReader(new InputStreamReader(_input_, getControlEncoding())); - _controlOutput_ = new BufferedWriter(new OutputStreamWriter(_output_, getControlEncoding())); - if (connectTimeout > 0) { - int original = _socket_.getSoTimeout(); - _socket_.setSoTimeout(connectTimeout); - try { - __getReply(); - if (FTPReply.isPositivePreliminary(_replyCode)) { - __getReply(); - } - } catch (SocketTimeoutException e) { - IOException ioe = new IOException("Timed out waiting for initial connect reply"); - ioe.initCause(e); - throw ioe; - } finally { - _socket_.setSoTimeout(original); - } - } else { - __getReply(); - if (FTPReply.isPositivePreliminary(_replyCode)) { - __getReply(); - } - } - } - - public void setControlEncoding(String encoding) { - _controlEncoding = encoding; - } - - public String getControlEncoding() { - return _controlEncoding; - } - - @Override - public void disconnect() throws IOException { - super.disconnect(); - _controlInput_ = null; - _controlOutput_ = null; - _newReplyString = false; - _replyString = null; - } - - public int sendCommand(String command, String args) throws IOException { - if (_controlOutput_ == null) { - throw new IOException("Connection is not open"); - } - - final String message = __buildMessage(command, args); - - __send(message); - - __getReply(); - return _replyCode; - } - - private String __buildMessage(String command, String args) { - final StringBuilder __commandBuffer = new StringBuilder(); - - __commandBuffer.append(command); - - if (args != null) { - __commandBuffer.append(' '); - __commandBuffer.append(args); - } - __commandBuffer.append(SocketClient.NETASCII_EOL); - return __commandBuffer.toString(); - } - - private void __send(String message) throws IOException, FTPConnectionClosedException, SocketException { - try { - _controlOutput_.write(message); - _controlOutput_.flush(); - } catch (SocketException e) { - if (!isConnected()) { - throw new FTPConnectionClosedException("Connection unexpectedly closed."); - } else { - throw e; - } - } - } - - protected void __noop() throws IOException { - String msg = __buildMessage(FTPCmd.NOOP.getCommand(), null); - __send(msg); - __getReplyNoReport(); // This may timeout - } - - public int sendCommand(FTPCmd command) throws IOException { - return sendCommand(command, null); - } - - public int sendCommand(FTPCmd command, String args) throws IOException { - return sendCommand(command.getCommand(), args); - } - - public int sendCommand(String command) throws IOException { - return sendCommand(command, null); - } - - public int getReplyCode() { - return _replyCode; - } - - public int getReply() throws IOException { - __getReply(); - return _replyCode; - } - - public String[] getReplyStrings() { - return _replyLines.toArray(new String[_replyLines.size()]); - } - - public String getReplyString() { - StringBuilder buffer; - - if (!_newReplyString) { - return _replyString; - } - - buffer = new StringBuilder(256); - - for (String line : _replyLines) { - buffer.append(line); - buffer.append(SocketClient.NETASCII_EOL); - } - - _newReplyString = false; - - return (_replyString = buffer.toString()); - } - - public int user(String username) throws IOException { - return sendCommand(FTPCmd.USER, username); - } - - public int pass(String password) throws IOException { - return sendCommand(FTPCmd.PASS, password); - } - - public int acct(String account) throws IOException { - return sendCommand(FTPCmd.ACCT, account); - } - - public int abor() throws IOException { - return sendCommand(FTPCmd.ABOR); - } - - public int cwd(String directory) throws IOException { - return sendCommand(FTPCmd.CWD, directory); - } - - public int cdup() throws IOException { - return sendCommand(FTPCmd.CDUP); - } - - public int quit() throws IOException { - return sendCommand(FTPCmd.QUIT); - } - - public int rein() throws IOException { - return sendCommand(FTPCmd.REIN); - } - - public int smnt(String dir) throws IOException { - return sendCommand(FTPCmd.SMNT, dir); - } - - public int port(InetAddress host, int port) throws IOException { - int num; - StringBuilder info = new StringBuilder(24); - - info.append(host.getHostAddress().replace('.', ',')); - num = port >>> 8; - info.append(','); - info.append(num); - info.append(','); - num = port & 0xff; - info.append(num); - - return sendCommand(FTPCmd.PORT, info.toString()); - } - - public int eprt(InetAddress host, int port) throws IOException { - int num; - StringBuilder info = new StringBuilder(); - String h; - - // If IPv6, trim the zone index - h = host.getHostAddress(); - num = h.indexOf("%"); - if (num > 0) { - h = h.substring(0, num); - } - - info.append("|"); - - if (host instanceof Inet4Address) { - info.append("1"); - } else if (host instanceof Inet6Address) { - info.append("2"); - } - info.append("|"); - info.append(h); - info.append("|"); - info.append(port); - info.append("|"); - - return sendCommand(FTPCmd.EPRT, info.toString()); - } - - public int pasv() throws IOException { - return sendCommand(FTPCmd.PASV); - } - - public int epsv() throws IOException { - return sendCommand(FTPCmd.EPSV); - } - - public int type(int fileType, int formatOrByteSize) throws IOException { - StringBuilder arg = new StringBuilder(); - - arg.append(__modes.charAt(fileType)); - arg.append(' '); - if (fileType == LOCAL_FILE_TYPE) { - arg.append(formatOrByteSize); - } else { - arg.append(__modes.charAt(formatOrByteSize)); - } - - return sendCommand(FTPCmd.TYPE, arg.toString()); - } - - public int type(int fileType) throws IOException { - return sendCommand(FTPCmd.TYPE, __modes.substring(fileType, fileType + 1)); - } - - public int stru(int structure) throws IOException { - return sendCommand(FTPCmd.STRU, __modes.substring(structure, structure + 1)); - } - - public int mode(int mode) throws IOException { - return sendCommand(FTPCmd.MODE, __modes.substring(mode, mode + 1)); - } - - public int retr(String pathname) throws IOException { - return sendCommand(FTPCmd.RETR, pathname); - } - - public int stor(String pathname) throws IOException { - return sendCommand(FTPCmd.STOR, pathname); - } - - public int stou() throws IOException { - return sendCommand(FTPCmd.STOU); - } - - public int stou(String pathname) throws IOException { - return sendCommand(FTPCmd.STOU, pathname); - } - - public int appe(String pathname) throws IOException { - return sendCommand(FTPCmd.APPE, pathname); - } - - public int allo(int bytes) throws IOException { - return sendCommand(FTPCmd.ALLO, Integer.toString(bytes)); - } - - public int feat() throws IOException { - return sendCommand(FTPCmd.FEAT); - } - - public int allo(int bytes, int recordSize) throws IOException { - return sendCommand(FTPCmd.ALLO, Integer.toString(bytes) + " R " + Integer.toString(recordSize)); - } - - public int rest(String marker) throws IOException { - return sendCommand(FTPCmd.REST, marker); - } - - public int mdtm(String file) throws IOException { - return sendCommand(FTPCmd.MDTM, file); - } - - public int mfmt(String pathname, String timeval) throws IOException { - return sendCommand(FTPCmd.MFMT, timeval + " " + pathname); - } - - public int rnfr(String pathname) throws IOException { - return sendCommand(FTPCmd.RNFR, pathname); - } - - public int rnto(String pathname) throws IOException { - return sendCommand(FTPCmd.RNTO, pathname); - } - - public int dele(String pathname) throws IOException { - return sendCommand(FTPCmd.DELE, pathname); - } - - public int rmd(String pathname) throws IOException { - return sendCommand(FTPCmd.RMD, pathname); - } - - public int mkd(String pathname) throws IOException { - return sendCommand(FTPCmd.MKD, pathname); - } - - public int pwd() throws IOException { - return sendCommand(FTPCmd.PWD); - } - - public int list() throws IOException { - return sendCommand(FTPCmd.LIST); - } - - public int list(String pathname) throws IOException { - return sendCommand(FTPCmd.LIST, pathname); - } - - public int mlsd() throws IOException { - return sendCommand(FTPCmd.MLSD); - } - - public int mlsd(String path) throws IOException { - return sendCommand(FTPCmd.MLSD, path); - } - - public int mlst() throws IOException { - return sendCommand(FTPCmd.MLST); - } - - public int mlst(String path) throws IOException { - return sendCommand(FTPCmd.MLST, path); - } - - public int nlst() throws IOException { - return sendCommand(FTPCmd.NLST); - } - - public int nlst(String pathname) throws IOException { - return sendCommand(FTPCmd.NLST, pathname); - } - - public int site(String parameters) throws IOException { - return sendCommand(FTPCmd.SITE, parameters); - } - - public int syst() throws IOException { - return sendCommand(FTPCmd.SYST); - } - - public int stat() throws IOException { - return sendCommand(FTPCmd.STAT); - } - - public int stat(String pathname) throws IOException { - return sendCommand(FTPCmd.STAT, pathname); - } - - public int help() throws IOException { - return sendCommand(FTPCmd.HELP); - } - - public int help(String command) throws IOException { - return sendCommand(FTPCmd.HELP, command); - } - - public int noop() throws IOException { - return sendCommand(FTPCmd.NOOP); - } - - public boolean isStrictMultilineParsing() { - return strictMultilineParsing; - } - - public void setStrictMultilineParsing(boolean strictMultilineParsing) { - this.strictMultilineParsing = strictMultilineParsing; - } - -} \ No newline at end of file diff --git a/src/autosaveworld/zlibs/org/apache/commons/net/ftp/FTPClient.java b/src/autosaveworld/zlibs/org/apache/commons/net/ftp/FTPClient.java deleted file mode 100644 index bdbdf8b4..00000000 --- a/src/autosaveworld/zlibs/org/apache/commons/net/ftp/FTPClient.java +++ /dev/null @@ -1,892 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package autosaveworld.zlibs.org.apache.commons.net.ftp; - -import java.io.BufferedOutputStream; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.net.Inet6Address; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Locale; -import java.util.Random; -import java.util.Set; - -import autosaveworld.zlibs.org.apache.commons.net.MalformedServerReplyException; -import autosaveworld.zlibs.org.apache.commons.net.io.CRLFLineReader; -import autosaveworld.zlibs.org.apache.commons.net.io.Util; - -public class FTPClient extends FTP { - - public static final int ACTIVE_LOCAL_DATA_CONNECTION_MODE = 0; - - public static final int ACTIVE_REMOTE_DATA_CONNECTION_MODE = 1; - - public static final int PASSIVE_LOCAL_DATA_CONNECTION_MODE = 2; - - public static final int PASSIVE_REMOTE_DATA_CONNECTION_MODE = 3; - - private int __dataConnectionMode; - private int __dataTimeout; - private int __passivePort; - private String __passiveHost; - private final Random __random; - private int __activeMinPort; - private int __activeMaxPort; - private InetAddress __activeExternalHost; - private InetAddress __reportActiveExternalHost; - private InetAddress __passiveLocalHost; - - private boolean __remoteVerificationEnabled; - private long __restartOffset; - private int __bufferSize; - private int __sendDataSocketBufferSize; - private int __receiveDataSocketBufferSize; - private boolean __listHiddenFiles; - private boolean __useEPSVwithIPv4; - - private boolean __passiveNatWorkaround = true; - - private static final java.util.regex.Pattern __PARMS_PAT; - static { - __PARMS_PAT = java.util.regex.Pattern.compile("(\\d{1,3},\\d{1,3},\\d{1,3},\\d{1,3}),(\\d{1,3}),(\\d{1,3})"); - } - - private boolean __autodetectEncoding = false; - - private HashMap> __featuresMap; - - public FTPClient() { - __initDefaults(); - __dataTimeout = -1; - __remoteVerificationEnabled = true; - __listHiddenFiles = false; - __useEPSVwithIPv4 = false; - __random = new Random(); - __passiveLocalHost = null; - } - - private void __initDefaults() { - __dataConnectionMode = ACTIVE_LOCAL_DATA_CONNECTION_MODE; - __passiveHost = null; - __passivePort = -1; - __activeExternalHost = null; - __reportActiveExternalHost = null; - __activeMinPort = 0; - __activeMaxPort = 0; - __restartOffset = 0; - __featuresMap = null; - } - - protected void _parsePassiveModeReply(String reply) throws MalformedServerReplyException { - java.util.regex.Matcher m = __PARMS_PAT.matcher(reply); - if (!m.find()) { - throw new MalformedServerReplyException("Could not parse passive host information.\nServer Reply: " + reply); - } - - __passiveHost = m.group(1).replace(',', '.'); - - try { - int oct1 = Integer.parseInt(m.group(2)); - int oct2 = Integer.parseInt(m.group(3)); - __passivePort = (oct1 << 8) | oct2; - } catch (NumberFormatException e) { - throw new MalformedServerReplyException("Could not parse passive port information.\nServer Reply: " + reply); - } - - if (__passiveNatWorkaround) { - try { - InetAddress host = InetAddress.getByName(__passiveHost); - if (host.isSiteLocalAddress()) { - InetAddress remote = getRemoteAddress(); - if (!remote.isSiteLocalAddress()) { - String hostAddress = remote.getHostAddress(); - __passiveHost = hostAddress; - } - } - } catch (UnknownHostException e) { - throw new MalformedServerReplyException("Could not parse passive host information.\nServer Reply: " + reply); - } - } - } - - protected void _parseExtendedPassiveModeReply(String reply) throws MalformedServerReplyException { - reply = reply.substring(reply.indexOf('(') + 1, reply.indexOf(')')).trim(); - - char delim1, delim2, delim3, delim4; - delim1 = reply.charAt(0); - delim2 = reply.charAt(1); - delim3 = reply.charAt(2); - delim4 = reply.charAt(reply.length() - 1); - - if (!(delim1 == delim2) || !(delim2 == delim3) || !(delim3 == delim4)) { - throw new MalformedServerReplyException("Could not parse extended passive host information.\nServer Reply: " + reply); - } - - int port; - try { - port = Integer.parseInt(reply.substring(3, reply.length() - 1)); - } catch (NumberFormatException e) { - throw new MalformedServerReplyException("Could not parse extended passive host information.\nServer Reply: " + reply); - } - - __passiveHost = getRemoteAddress().getHostAddress(); - __passivePort = port; - } - - private boolean __storeFile(FTPCmd command, String remote, InputStream local) throws IOException { - return _storeFile(command.getCommand(), remote, local); - } - - protected boolean _storeFile(String command, String remote, InputStream local) throws IOException { - Socket socket = _openDataConnection_(command, remote); - - if (socket == null) { - return false; - } - - OutputStream output = getBufferedOutputStream(socket.getOutputStream()); - - try { - Util.copyStream(local, output); - } catch (IOException e) { - Util.closeQuietly(socket); - throw e; - } - - output.close(); - socket.close(); - boolean ok = completePendingCommand(); - return ok; - } - - private OutputStream __storeFileStream(FTPCmd command, String remote) throws IOException { - return _storeFileStream(command.getCommand(), remote); - } - - protected OutputStream _storeFileStream(String command, String remote) throws IOException { - Socket socket = _openDataConnection_(command, remote); - - if (socket == null) { - return null; - } - - OutputStream output = socket.getOutputStream(); - - return new autosaveworld.zlibs.org.apache.commons.net.io.SocketOutputStream(socket, output); - } - - protected Socket _openDataConnection_(FTPCmd command, String arg) throws IOException { - return _openDataConnection_(command.getCommand(), arg); - } - - protected Socket _openDataConnection_(String command, String arg) throws IOException { - if ((__dataConnectionMode != ACTIVE_LOCAL_DATA_CONNECTION_MODE) && (__dataConnectionMode != PASSIVE_LOCAL_DATA_CONNECTION_MODE)) { - return null; - } - - final boolean isInet6Address = getRemoteAddress() instanceof Inet6Address; - - Socket socket; - - if (__dataConnectionMode == ACTIVE_LOCAL_DATA_CONNECTION_MODE) { - ServerSocket server = _serverSocketFactory_.createServerSocket(getActivePort(), 1, getHostAddress()); - - try { - if (isInet6Address) { - if (!FTPReply.isPositiveCompletion(eprt(getReportHostAddress(), server.getLocalPort()))) { - return null; - } - } else { - if (!FTPReply.isPositiveCompletion(port(getReportHostAddress(), server.getLocalPort()))) { - return null; - } - } - - if ((__restartOffset > 0) && !restart(__restartOffset)) { - return null; - } - - if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) { - return null; - } - - if (__dataTimeout >= 0) { - server.setSoTimeout(__dataTimeout); - } - socket = server.accept(); - - if (__dataTimeout >= 0) { - socket.setSoTimeout(__dataTimeout); - } - if (__receiveDataSocketBufferSize > 0) { - socket.setReceiveBufferSize(__receiveDataSocketBufferSize); - } - if (__sendDataSocketBufferSize > 0) { - socket.setSendBufferSize(__sendDataSocketBufferSize); - } - } finally { - server.close(); - } - } else { - boolean attemptEPSV = isUseEPSVwithIPv4() || isInet6Address; - if (attemptEPSV && (epsv() == FTPReply.ENTERING_EPSV_MODE)) { - _parseExtendedPassiveModeReply(_replyLines.get(0)); - } else { - if (isInet6Address) { - return null; - } - if (pasv() != FTPReply.ENTERING_PASSIVE_MODE) { - return null; - } - _parsePassiveModeReply(_replyLines.get(0)); - } - - socket = _socketFactory_.createSocket(); - if (__receiveDataSocketBufferSize > 0) { - socket.setReceiveBufferSize(__receiveDataSocketBufferSize); - } - if (__sendDataSocketBufferSize > 0) { - socket.setSendBufferSize(__sendDataSocketBufferSize); - } - if (__passiveLocalHost != null) { - socket.bind(new InetSocketAddress(__passiveLocalHost, 0)); - } - - if (__dataTimeout >= 0) { - socket.setSoTimeout(__dataTimeout); - } - - socket.connect(new InetSocketAddress(__passiveHost, __passivePort), connectTimeout); - if ((__restartOffset > 0) && !restart(__restartOffset)) { - socket.close(); - return null; - } - - if (!FTPReply.isPositivePreliminary(sendCommand(command, arg))) { - socket.close(); - return null; - } - } - - if (__remoteVerificationEnabled && !verifyRemote(socket)) { - socket.close(); - - throw new IOException("Host attempting data connection " + socket.getInetAddress().getHostAddress() + " is not same as server " + getRemoteAddress().getHostAddress()); - } - - return socket; - } - - @Override - protected void _connectAction_() throws IOException { - super._connectAction_(); - __initDefaults(); - if (__autodetectEncoding) { - ArrayList oldReplyLines = new ArrayList(_replyLines); - int oldReplyCode = _replyCode; - if (hasFeature("UTF8") || hasFeature("UTF-8")) { - setControlEncoding("UTF-8"); - _controlInput_ = new CRLFLineReader(new InputStreamReader(_input_, getControlEncoding())); - _controlOutput_ = new BufferedWriter(new OutputStreamWriter(_output_, getControlEncoding())); - } - _replyLines.clear(); - _replyLines.addAll(oldReplyLines); - _replyCode = oldReplyCode; - } - } - - public void setDataTimeout(int timeout) { - __dataTimeout = timeout; - } - - @Override - public void disconnect() throws IOException { - super.disconnect(); - __initDefaults(); - } - - public void setRemoteVerificationEnabled(boolean enable) { - __remoteVerificationEnabled = enable; - } - - public boolean isRemoteVerificationEnabled() { - return __remoteVerificationEnabled; - } - - public boolean login(String username, String password) throws IOException { - - user(username); - - if (FTPReply.isPositiveCompletion(_replyCode)) { - if (setFileType(FTP.BINARY_FILE_TYPE)) { - return true; - } - } - - if (!FTPReply.isPositiveIntermediate(_replyCode)) { - return false; - } - - if (!FTPReply.isPositiveCompletion(pass(password))) { - return false; - } - - return setFileType(FTP.BINARY_FILE_TYPE); - } - - public boolean login(String username, String password, String account) throws IOException { - user(username); - - if (FTPReply.isPositiveCompletion(_replyCode)) { - return true; - } - - if (!FTPReply.isPositiveIntermediate(_replyCode)) { - return false; - } - - pass(password); - - if (FTPReply.isPositiveCompletion(_replyCode)) { - return true; - } - - if (!FTPReply.isPositiveIntermediate(_replyCode)) { - return false; - } - - return FTPReply.isPositiveCompletion(acct(account)); - } - - public boolean logout() throws IOException { - return FTPReply.isPositiveCompletion(quit()); - } - - public boolean changeWorkingDirectory(String pathname) throws IOException { - return FTPReply.isPositiveCompletion(cwd(pathname)); - } - - public boolean changeToParentDirectory() throws IOException { - return FTPReply.isPositiveCompletion(cdup()); - } - - public boolean structureMount(String pathname) throws IOException { - return FTPReply.isPositiveCompletion(smnt(pathname)); - } - - boolean reinitialize() throws IOException { - rein(); - - if (FTPReply.isPositiveCompletion(_replyCode) || (FTPReply.isPositivePreliminary(_replyCode) && FTPReply.isPositiveCompletion(getReply()))) { - - __initDefaults(); - - return true; - } - - return false; - } - - public void enterLocalActiveMode() { - __dataConnectionMode = ACTIVE_LOCAL_DATA_CONNECTION_MODE; - __passiveHost = null; - __passivePort = -1; - } - - public void enterLocalPassiveMode() { - __dataConnectionMode = PASSIVE_LOCAL_DATA_CONNECTION_MODE; - __passiveHost = null; - __passivePort = -1; - } - - public boolean enterRemoteActiveMode(InetAddress host, int port) throws IOException { - if (FTPReply.isPositiveCompletion(port(host, port))) { - __dataConnectionMode = ACTIVE_REMOTE_DATA_CONNECTION_MODE; - __passiveHost = null; - __passivePort = -1; - return true; - } - return false; - } - - public boolean enterRemotePassiveMode() throws IOException { - if (pasv() != FTPReply.ENTERING_PASSIVE_MODE) { - return false; - } - - __dataConnectionMode = PASSIVE_REMOTE_DATA_CONNECTION_MODE; - _parsePassiveModeReply(_replyLines.get(0)); - - return true; - } - - public String getPassiveHost() { - return __passiveHost; - } - - public int getPassivePort() { - return __passivePort; - } - - public int getDataConnectionMode() { - return __dataConnectionMode; - } - - private int getActivePort() { - if ((__activeMinPort > 0) && (__activeMaxPort >= __activeMinPort)) { - if (__activeMaxPort == __activeMinPort) { - return __activeMaxPort; - } - return __random.nextInt((__activeMaxPort - __activeMinPort) + 1) + __activeMinPort; - } else { - return 0; - } - } - - private InetAddress getHostAddress() { - if (__activeExternalHost != null) { - return __activeExternalHost; - } else { - // default local address - return getLocalAddress(); - } - } - - private InetAddress getReportHostAddress() { - if (__reportActiveExternalHost != null) { - return __reportActiveExternalHost; - } else { - return getHostAddress(); - } - } - - public void setActivePortRange(int minPort, int maxPort) { - __activeMinPort = minPort; - __activeMaxPort = maxPort; - } - - public void setActiveExternalIPAddress(String ipAddress) throws UnknownHostException { - __activeExternalHost = InetAddress.getByName(ipAddress); - } - - public void setPassiveLocalIPAddress(String ipAddress) throws UnknownHostException { - __passiveLocalHost = InetAddress.getByName(ipAddress); - } - - public void setPassiveLocalIPAddress(InetAddress inetAddress) { - __passiveLocalHost = inetAddress; - } - - public InetAddress getPassiveLocalIPAddress() { - return __passiveLocalHost; - } - - public void setReportActiveExternalIPAddress(String ipAddress) throws UnknownHostException { - __reportActiveExternalHost = InetAddress.getByName(ipAddress); - } - - public boolean setFileType(int fileType) throws IOException { - if (FTPReply.isPositiveCompletion(type(fileType))) { - return true; - } - return false; - } - - public boolean setFileType(int fileType, int formatOrByteSize) throws IOException { - if (FTPReply.isPositiveCompletion(type(fileType, formatOrByteSize))) { - return true; - } - return false; - } - - public boolean setFileStructure(int structure) throws IOException { - if (FTPReply.isPositiveCompletion(stru(structure))) { - return true; - } - return false; - } - - public boolean setFileTransferMode(int mode) throws IOException { - if (FTPReply.isPositiveCompletion(mode(mode))) { - return true; - } - return false; - } - - public boolean remoteRetrieve(String filename) throws IOException { - if ((__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE) || (__dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE)) { - return FTPReply.isPositivePreliminary(retr(filename)); - } - return false; - } - - public boolean remoteStore(String filename) throws IOException { - if ((__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE) || (__dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE)) { - return FTPReply.isPositivePreliminary(stor(filename)); - } - return false; - } - - public boolean remoteStoreUnique(String filename) throws IOException { - if ((__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE) || (__dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE)) { - return FTPReply.isPositivePreliminary(stou(filename)); - } - return false; - } - - public boolean remoteStoreUnique() throws IOException { - if ((__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE) || (__dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE)) { - return FTPReply.isPositivePreliminary(stou()); - } - return false; - } - - public boolean remoteAppend(String filename) throws IOException { - if ((__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE) || (__dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE)) { - return FTPReply.isPositivePreliminary(appe(filename)); - } - return false; - } - - public boolean completePendingCommand() throws IOException { - return FTPReply.isPositiveCompletion(getReply()); - } - - public boolean storeFile(String remote, InputStream local) throws IOException { - return __storeFile(FTPCmd.STOR, remote, local); - } - - public OutputStream storeFileStream(String remote) throws IOException { - return __storeFileStream(FTPCmd.STOR, remote); - } - - public boolean appendFile(String remote, InputStream local) throws IOException { - return __storeFile(FTPCmd.APPE, remote, local); - } - - public OutputStream appendFileStream(String remote) throws IOException { - return __storeFileStream(FTPCmd.APPE, remote); - } - - public boolean storeUniqueFile(String remote, InputStream local) throws IOException { - return __storeFile(FTPCmd.STOU, remote, local); - } - - public OutputStream storeUniqueFileStream(String remote) throws IOException { - return __storeFileStream(FTPCmd.STOU, remote); - } - - public OutputStream storeUniqueFileStream() throws IOException { - return __storeFileStream(FTPCmd.STOU, null); - } - - public boolean allocate(int bytes) throws IOException { - return FTPReply.isPositiveCompletion(allo(bytes)); - } - - public boolean features() throws IOException { - return FTPReply.isPositiveCompletion(feat()); - } - - public String[] featureValues(String feature) throws IOException { - if (!initFeatureMap()) { - return null; - } - Set entries = __featuresMap.get(feature.toUpperCase(Locale.ENGLISH)); - if (entries != null) { - return entries.toArray(new String[entries.size()]); - } - return null; - } - - public String featureValue(String feature) throws IOException { - String[] values = featureValues(feature); - if (values != null) { - return values[0]; - } - return null; - } - - public boolean hasFeature(String feature) throws IOException { - if (!initFeatureMap()) { - return false; - } - return __featuresMap.containsKey(feature.toUpperCase(Locale.ENGLISH)); - } - - public boolean hasFeature(String feature, String value) throws IOException { - if (!initFeatureMap()) { - return false; - } - Set entries = __featuresMap.get(feature.toUpperCase(Locale.ENGLISH)); - if (entries != null) { - return entries.contains(value); - } - return false; - } - - private boolean initFeatureMap() throws IOException { - if (__featuresMap == null) { - boolean success = FTPReply.isPositiveCompletion(feat()); - __featuresMap = new HashMap>(); - if (!success) { - return false; - } - for (String l : getReplyStrings()) { - if (l.startsWith(" ")) { - String key; - String value = ""; - int varsep = l.indexOf(' ', 1); - if (varsep > 0) { - key = l.substring(1, varsep); - value = l.substring(varsep + 1); - } else { - key = l.substring(1); - } - key = key.toUpperCase(Locale.ENGLISH); - Set entries = __featuresMap.get(key); - if (entries == null) { - entries = new HashSet(); - __featuresMap.put(key, entries); - } - entries.add(value); - } - } - } - return true; - } - - public boolean allocate(int bytes, int recordSize) throws IOException { - return FTPReply.isPositiveCompletion(allo(bytes, recordSize)); - } - - public boolean doCommand(String command, String params) throws IOException { - return FTPReply.isPositiveCompletion(sendCommand(command, params)); - } - - public String[] doCommandAsStrings(String command, String params) throws IOException { - boolean success = FTPReply.isPositiveCompletion(sendCommand(command, params)); - if (success) { - return getReplyStrings(); - } else { - return null; - } - } - - protected boolean restart(long offset) throws IOException { - __restartOffset = 0; - return FTPReply.isPositiveIntermediate(rest(Long.toString(offset))); - } - - public void setRestartOffset(long offset) { - if (offset >= 0) { - __restartOffset = offset; - } - } - - public long getRestartOffset() { - return __restartOffset; - } - - public boolean rename(String from, String to) throws IOException { - if (!FTPReply.isPositiveIntermediate(rnfr(from))) { - return false; - } - - return FTPReply.isPositiveCompletion(rnto(to)); - } - - public boolean abort() throws IOException { - return FTPReply.isPositiveCompletion(abor()); - } - - public boolean deleteFile(String pathname) throws IOException { - return FTPReply.isPositiveCompletion(dele(pathname)); - } - - public boolean removeDirectory(String pathname) throws IOException { - return FTPReply.isPositiveCompletion(rmd(pathname)); - } - - public boolean makeDirectory(String pathname) throws IOException { - return FTPReply.isPositiveCompletion(mkd(pathname)); - } - - public boolean sendSiteCommand(String arguments) throws IOException { - return FTPReply.isPositiveCompletion(site(arguments)); - } - - public String listHelp() throws IOException { - if (FTPReply.isPositiveCompletion(help())) { - return getReplyString(); - } - return null; - } - - public String listHelp(String command) throws IOException { - if (FTPReply.isPositiveCompletion(help(command))) { - return getReplyString(); - } - return null; - } - - public boolean sendNoOp() throws IOException { - return FTPReply.isPositiveCompletion(noop()); - } - - public String[] listNames(String pathname) throws IOException { - Socket socket = _openDataConnection_(FTPCmd.NLST, getListArguments(pathname)); - - if (socket == null) { - return null; - } - - BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), getControlEncoding())); - - ArrayList results = new ArrayList(); - String line; - while ((line = reader.readLine()) != null) { - results.add(line); - } - - reader.close(); - socket.close(); - - if (completePendingCommand()) { - String[] names = new String[results.size()]; - return results.toArray(names); - } - - return null; - } - - public String[] listNames() throws IOException { - return listNames(null); - } - - protected String getListArguments(String pathname) { - if (getListHiddenFiles()) { - if (pathname != null) { - StringBuilder sb = new StringBuilder(pathname.length() + 3); - sb.append("-a "); - sb.append(pathname); - return sb.toString(); - } else { - return "-a"; - } - } - - return pathname; - } - - public String getStatus() throws IOException { - if (FTPReply.isPositiveCompletion(stat())) { - return getReplyString(); - } - return null; - } - - public String getStatus(String pathname) throws IOException { - if (FTPReply.isPositiveCompletion(stat(pathname))) { - return getReplyString(); - } - return null; - } - - public String getModificationTime(String pathname) throws IOException { - if (FTPReply.isPositiveCompletion(mdtm(pathname))) { - return getReplyString(); - } - return null; - } - - public boolean setModificationTime(String pathname, String timeval) throws IOException { - return (FTPReply.isPositiveCompletion(mfmt(pathname, timeval))); - } - - public void setBufferSize(int bufSize) { - __bufferSize = bufSize; - } - - public int getBufferSize() { - return __bufferSize; - } - - public void setSendDataSocketBufferSize(int bufSize) { - __sendDataSocketBufferSize = bufSize; - } - - public int getSendDataSocketBufferSize() { - return __sendDataSocketBufferSize; - } - - public void setReceieveDataSocketBufferSize(int bufSize) { - __receiveDataSocketBufferSize = bufSize; - } - - public int getReceiveDataSocketBufferSize() { - return __receiveDataSocketBufferSize; - } - - public void setListHiddenFiles(boolean listHiddenFiles) { - __listHiddenFiles = listHiddenFiles; - } - - public boolean getListHiddenFiles() { - return __listHiddenFiles; - } - - public boolean isUseEPSVwithIPv4() { - return __useEPSVwithIPv4; - } - - public void setUseEPSVwithIPv4(boolean selected) { - __useEPSVwithIPv4 = selected; - } - - public void setPassiveNatWorkaround(boolean enabled) { - __passiveNatWorkaround = enabled; - } - - private OutputStream getBufferedOutputStream(OutputStream outputStream) { - if (__bufferSize > 0) { - return new BufferedOutputStream(outputStream, __bufferSize); - } - return new BufferedOutputStream(outputStream); - } - - public void setAutodetectUTF8(boolean autodetect) { - __autodetectEncoding = autodetect; - } - - public boolean getAutodetectUTF8() { - return __autodetectEncoding; - } - -} \ No newline at end of file diff --git a/src/autosaveworld/zlibs/org/apache/commons/net/ftp/FTPCmd.java b/src/autosaveworld/zlibs/org/apache/commons/net/ftp/FTPCmd.java deleted file mode 100644 index 30d4d6b9..00000000 --- a/src/autosaveworld/zlibs/org/apache/commons/net/ftp/FTPCmd.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package autosaveworld.zlibs.org.apache.commons.net.ftp; - -public enum FTPCmd { - ABOR, ACCT, ALLO, APPE, CDUP, CWD, DELE, EPRT, EPSV, FEAT, HELP, LIST, MDTM, MFMT, MKD, MLSD, MLST, MODE, NLST, NOOP, PASS, PASV, PORT, PWD, QUIT, REIN, REST, RETR, RMD, RNFR, RNTO, SITE, SMNT, STAT, STOR, STOU, STRU, SYST, TYPE, USER, ; - - public static final FTPCmd ABORT = ABOR; - public static final FTPCmd ACCOUNT = ACCT; - public static final FTPCmd ALLOCATE = ALLO; - public static final FTPCmd APPEND = APPE; - public static final FTPCmd CHANGE_TO_PARENT_DIRECTORY = CDUP; - public static final FTPCmd CHANGE_WORKING_DIRECTORY = CWD; - public static final FTPCmd DATA_PORT = PORT; - public static final FTPCmd DELETE = DELE; - public static final FTPCmd FEATURES = FEAT; - public static final FTPCmd FILE_STRUCTURE = STRU; - public static final FTPCmd GET_MOD_TIME = MDTM; - public static final FTPCmd LOGOUT = QUIT; - public static final FTPCmd MAKE_DIRECTORY = MKD; - public static final FTPCmd MOD_TIME = MDTM; - public static final FTPCmd NAME_LIST = NLST; - public static final FTPCmd PASSIVE = PASV; - public static final FTPCmd PASSWORD = PASS; - public static final FTPCmd PRINT_WORKING_DIRECTORY = PWD; - public static final FTPCmd REINITIALIZE = REIN; - public static final FTPCmd REMOVE_DIRECTORY = RMD; - public static final FTPCmd RENAME_FROM = RNFR; - public static final FTPCmd RENAME_TO = RNTO; - public static final FTPCmd REPRESENTATION_TYPE = TYPE; - public static final FTPCmd RESTART = REST; - public static final FTPCmd RETRIEVE = RETR; - public static final FTPCmd SET_MOD_TIME = MFMT; - public static final FTPCmd SITE_PARAMETERS = SITE; - public static final FTPCmd STATUS = STAT; - public static final FTPCmd STORE = STOR; - public static final FTPCmd STORE_UNIQUE = STOU; - public static final FTPCmd STRUCTURE_MOUNT = SMNT; - public static final FTPCmd SYSTEM = SYST; - public static final FTPCmd TRANSFER_MODE = MODE; - public static final FTPCmd USERNAME = USER; - - public final String getCommand() { - return name(); - } - -} diff --git a/src/autosaveworld/zlibs/org/apache/commons/net/ftp/FTPConnectionClosedException.java b/src/autosaveworld/zlibs/org/apache/commons/net/ftp/FTPConnectionClosedException.java deleted file mode 100644 index 8da1811f..00000000 --- a/src/autosaveworld/zlibs/org/apache/commons/net/ftp/FTPConnectionClosedException.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package autosaveworld.zlibs.org.apache.commons.net.ftp; - -import java.io.IOException; - -public class FTPConnectionClosedException extends IOException { - - private static final long serialVersionUID = 3500547241659379952L; - - public FTPConnectionClosedException() { - super(); - } - - public FTPConnectionClosedException(String message) { - super(message); - } - -} diff --git a/src/autosaveworld/zlibs/org/apache/commons/net/ftp/FTPReply.java b/src/autosaveworld/zlibs/org/apache/commons/net/ftp/FTPReply.java deleted file mode 100644 index 3cd741e8..00000000 --- a/src/autosaveworld/zlibs/org/apache/commons/net/ftp/FTPReply.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package autosaveworld.zlibs.org.apache.commons.net.ftp; - -public final class FTPReply { - - public static final int RESTART_MARKER = 110; - public static final int SERVICE_NOT_READY = 120; - public static final int DATA_CONNECTION_ALREADY_OPEN = 125; - public static final int FILE_STATUS_OK = 150; - public static final int COMMAND_OK = 200; - public static final int COMMAND_IS_SUPERFLUOUS = 202; - public static final int SYSTEM_STATUS = 211; - public static final int DIRECTORY_STATUS = 212; - public static final int FILE_STATUS = 213; - public static final int HELP_MESSAGE = 214; - public static final int NAME_SYSTEM_TYPE = 215; - public static final int SERVICE_READY = 220; - public static final int SERVICE_CLOSING_CONTROL_CONNECTION = 221; - public static final int DATA_CONNECTION_OPEN = 225; - public static final int CLOSING_DATA_CONNECTION = 226; - public static final int ENTERING_PASSIVE_MODE = 227; - public static final int ENTERING_EPSV_MODE = 229; - public static final int USER_LOGGED_IN = 230; - public static final int FILE_ACTION_OK = 250; - public static final int PATHNAME_CREATED = 257; - public static final int NEED_PASSWORD = 331; - public static final int NEED_ACCOUNT = 332; - public static final int FILE_ACTION_PENDING = 350; - public static final int SERVICE_NOT_AVAILABLE = 421; - public static final int CANNOT_OPEN_DATA_CONNECTION = 425; - public static final int TRANSFER_ABORTED = 426; - public static final int FILE_ACTION_NOT_TAKEN = 450; - public static final int ACTION_ABORTED = 451; - public static final int INSUFFICIENT_STORAGE = 452; - public static final int UNRECOGNIZED_COMMAND = 500; - public static final int SYNTAX_ERROR_IN_ARGUMENTS = 501; - public static final int COMMAND_NOT_IMPLEMENTED = 502; - public static final int BAD_COMMAND_SEQUENCE = 503; - public static final int COMMAND_NOT_IMPLEMENTED_FOR_PARAMETER = 504; - public static final int NOT_LOGGED_IN = 530; - public static final int NEED_ACCOUNT_FOR_STORING_FILES = 532; - public static final int FILE_UNAVAILABLE = 550; - public static final int PAGE_TYPE_UNKNOWN = 551; - public static final int STORAGE_ALLOCATION_EXCEEDED = 552; - public static final int FILE_NAME_NOT_ALLOWED = 553; - public static final int SECURITY_DATA_EXCHANGE_COMPLETE = 234; - public static final int SECURITY_DATA_EXCHANGE_SUCCESSFULLY = 235; - public static final int SECURITY_MECHANISM_IS_OK = 334; - public static final int SECURITY_DATA_IS_ACCEPTABLE = 335; - public static final int UNAVAILABLE_RESOURCE = 431; - public static final int BAD_TLS_NEGOTIATION_OR_DATA_ENCRYPTION_REQUIRED = 522; - public static final int DENIED_FOR_POLICY_REASONS = 533; - public static final int REQUEST_DENIED = 534; - public static final int FAILED_SECURITY_CHECK = 535; - public static final int REQUESTED_PROT_LEVEL_NOT_SUPPORTED = 536; - public static final int EXTENDED_PORT_FAILURE = 522; - - private FTPReply() { - } - - public static boolean isPositivePreliminary(int reply) { - return ((reply >= 100) && (reply < 200)); - } - - public static boolean isPositiveCompletion(int reply) { - return ((reply >= 200) && (reply < 300)); - } - - public static boolean isPositiveIntermediate(int reply) { - return ((reply >= 300) && (reply < 400)); - } - - public static boolean isNegativeTransient(int reply) { - return ((reply >= 400) && (reply < 500)); - } - - public static boolean isNegativePermanent(int reply) { - return ((reply >= 500) && (reply < 600)); - } - - public static boolean isProtectedReplyCode(int reply) { - return ((reply >= 600) && (reply < 700)); - } - -} diff --git a/src/autosaveworld/zlibs/org/apache/commons/net/io/CRLFLineReader.java b/src/autosaveworld/zlibs/org/apache/commons/net/io/CRLFLineReader.java deleted file mode 100644 index 9cf57656..00000000 --- a/src/autosaveworld/zlibs/org/apache/commons/net/io/CRLFLineReader.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package autosaveworld.zlibs.org.apache.commons.net.io; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.Reader; - -public final class CRLFLineReader extends BufferedReader { - - private static final char LF = '\n'; - private static final char CR = '\r'; - - public CRLFLineReader(Reader reader) { - super(reader); - } - - @Override - public String readLine() throws IOException { - StringBuilder sb = new StringBuilder(); - int intch; - boolean prevWasCR = false; - synchronized (lock) { // make thread-safe (hopefully!) - while ((intch = read()) != -1) { - if (prevWasCR && (intch == LF)) { - return sb.substring(0, sb.length() - 1); - } - if (intch == CR) { - prevWasCR = true; - } else { - prevWasCR = false; - } - sb.append((char) intch); - } - } - String string = sb.toString(); - if (string.length() == 0) { - return null; - } - return string; - } - -} diff --git a/src/autosaveworld/zlibs/org/apache/commons/net/io/SocketInputStream.java b/src/autosaveworld/zlibs/org/apache/commons/net/io/SocketInputStream.java deleted file mode 100644 index 95a33a5d..00000000 --- a/src/autosaveworld/zlibs/org/apache/commons/net/io/SocketInputStream.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package autosaveworld.zlibs.org.apache.commons.net.io; - -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.Socket; - -public class SocketInputStream extends FilterInputStream { - - private final Socket __socket; - - public SocketInputStream(Socket socket, InputStream stream) { - super(stream); - __socket = socket; - } - - @Override - public void close() throws IOException { - super.close(); - __socket.close(); - } - -} diff --git a/src/autosaveworld/zlibs/org/apache/commons/net/io/SocketOutputStream.java b/src/autosaveworld/zlibs/org/apache/commons/net/io/SocketOutputStream.java deleted file mode 100644 index 44660877..00000000 --- a/src/autosaveworld/zlibs/org/apache/commons/net/io/SocketOutputStream.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package autosaveworld.zlibs.org.apache.commons.net.io; - -import java.io.FilterOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.net.Socket; - -public class SocketOutputStream extends FilterOutputStream { - - private final Socket __socket; - - public SocketOutputStream(Socket socket, OutputStream stream) { - super(stream); - __socket = socket; - } - - @Override - public void write(byte buffer[], int offset, int length) throws IOException { - out.write(buffer, offset, length); - } - - @Override - public void close() throws IOException { - super.close(); - __socket.close(); - } - -} diff --git a/src/autosaveworld/zlibs/org/apache/commons/net/io/Util.java b/src/autosaveworld/zlibs/org/apache/commons/net/io/Util.java deleted file mode 100644 index af6d4f22..00000000 --- a/src/autosaveworld/zlibs/org/apache/commons/net/io/Util.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package autosaveworld.zlibs.org.apache.commons.net.io; - -import java.io.Closeable; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.Socket; - -public final class Util { - - private Util() { - } - - public static final void copyStream(InputStream source, OutputStream dest) throws IOException { - byte[] buf = new byte[4096]; - try { - int read; - while ((read = source.read(buf)) != -1) { - dest.write(buf, 0, read); - } - dest.flush(); - } catch (IOException e) { - throw e; - } - } - - public static void closeQuietly(Closeable closeable) { - if (closeable != null) { - try { - closeable.close(); - } catch (IOException e) { - } - } - } - - public static void closeQuietly(Socket socket) { - if (socket != null) { - try { - socket.close(); - } catch (IOException e) { - } - } - } - -} diff --git a/src/autosaveworld/commands/CommandsHandler.java b/src/main/java/autosaveworld/commands/CommandsHandler.java similarity index 100% rename from src/autosaveworld/commands/CommandsHandler.java rename to src/main/java/autosaveworld/commands/CommandsHandler.java diff --git a/src/autosaveworld/commands/ISubCommand.java b/src/main/java/autosaveworld/commands/ISubCommand.java similarity index 100% rename from src/autosaveworld/commands/ISubCommand.java rename to src/main/java/autosaveworld/commands/ISubCommand.java diff --git a/src/autosaveworld/commands/NoTabCompleteCommandsHandler.java b/src/main/java/autosaveworld/commands/NoTabCompleteCommandsHandler.java similarity index 100% rename from src/autosaveworld/commands/NoTabCompleteCommandsHandler.java rename to src/main/java/autosaveworld/commands/NoTabCompleteCommandsHandler.java diff --git a/src/autosaveworld/commands/PermissionCheck.java b/src/main/java/autosaveworld/commands/PermissionCheck.java similarity index 100% rename from src/autosaveworld/commands/PermissionCheck.java rename to src/main/java/autosaveworld/commands/PermissionCheck.java diff --git a/src/autosaveworld/commands/subcommands/BackupSubCommand.java b/src/main/java/autosaveworld/commands/subcommands/BackupSubCommand.java similarity index 100% rename from src/autosaveworld/commands/subcommands/BackupSubCommand.java rename to src/main/java/autosaveworld/commands/subcommands/BackupSubCommand.java diff --git a/src/autosaveworld/commands/subcommands/ForceGCSubCommand.java b/src/main/java/autosaveworld/commands/subcommands/ForceGCSubCommand.java similarity index 100% rename from src/autosaveworld/commands/subcommands/ForceGCSubCommand.java rename to src/main/java/autosaveworld/commands/subcommands/ForceGCSubCommand.java diff --git a/src/autosaveworld/commands/subcommands/ForceRestartSubCommand.java b/src/main/java/autosaveworld/commands/subcommands/ForceRestartSubCommand.java similarity index 100% rename from src/autosaveworld/commands/subcommands/ForceRestartSubCommand.java rename to src/main/java/autosaveworld/commands/subcommands/ForceRestartSubCommand.java diff --git a/src/autosaveworld/commands/subcommands/HelpSubCommand.java b/src/main/java/autosaveworld/commands/subcommands/HelpSubCommand.java similarity index 100% rename from src/autosaveworld/commands/subcommands/HelpSubCommand.java rename to src/main/java/autosaveworld/commands/subcommands/HelpSubCommand.java diff --git a/src/autosaveworld/commands/subcommands/LocaleSubCommand.java b/src/main/java/autosaveworld/commands/subcommands/LocaleSubCommand.java similarity index 100% rename from src/autosaveworld/commands/subcommands/LocaleSubCommand.java rename to src/main/java/autosaveworld/commands/subcommands/LocaleSubCommand.java diff --git a/src/autosaveworld/commands/subcommands/PluginManagerSubCommand.java b/src/main/java/autosaveworld/commands/subcommands/PluginManagerSubCommand.java similarity index 100% rename from src/autosaveworld/commands/subcommands/PluginManagerSubCommand.java rename to src/main/java/autosaveworld/commands/subcommands/PluginManagerSubCommand.java diff --git a/src/autosaveworld/commands/subcommands/ProcessManagerSubCommand.java b/src/main/java/autosaveworld/commands/subcommands/ProcessManagerSubCommand.java similarity index 100% rename from src/autosaveworld/commands/subcommands/ProcessManagerSubCommand.java rename to src/main/java/autosaveworld/commands/subcommands/ProcessManagerSubCommand.java diff --git a/src/autosaveworld/commands/subcommands/PurgeSubCommand.java b/src/main/java/autosaveworld/commands/subcommands/PurgeSubCommand.java similarity index 100% rename from src/autosaveworld/commands/subcommands/PurgeSubCommand.java rename to src/main/java/autosaveworld/commands/subcommands/PurgeSubCommand.java diff --git a/src/autosaveworld/commands/subcommands/ReloadAllSubCommand.java b/src/main/java/autosaveworld/commands/subcommands/ReloadAllSubCommand.java similarity index 100% rename from src/autosaveworld/commands/subcommands/ReloadAllSubCommand.java rename to src/main/java/autosaveworld/commands/subcommands/ReloadAllSubCommand.java diff --git a/src/autosaveworld/commands/subcommands/ReloadConfigMSGSubCommand.java b/src/main/java/autosaveworld/commands/subcommands/ReloadConfigMSGSubCommand.java similarity index 100% rename from src/autosaveworld/commands/subcommands/ReloadConfigMSGSubCommand.java rename to src/main/java/autosaveworld/commands/subcommands/ReloadConfigMSGSubCommand.java diff --git a/src/autosaveworld/commands/subcommands/ReloadConfigSubCommand.java b/src/main/java/autosaveworld/commands/subcommands/ReloadConfigSubCommand.java similarity index 100% rename from src/autosaveworld/commands/subcommands/ReloadConfigSubCommand.java rename to src/main/java/autosaveworld/commands/subcommands/ReloadConfigSubCommand.java diff --git a/src/autosaveworld/commands/subcommands/RestartSubCommand.java b/src/main/java/autosaveworld/commands/subcommands/RestartSubCommand.java similarity index 100% rename from src/autosaveworld/commands/subcommands/RestartSubCommand.java rename to src/main/java/autosaveworld/commands/subcommands/RestartSubCommand.java diff --git a/src/autosaveworld/commands/subcommands/SaveSubCommand.java b/src/main/java/autosaveworld/commands/subcommands/SaveSubCommand.java similarity index 100% rename from src/autosaveworld/commands/subcommands/SaveSubCommand.java rename to src/main/java/autosaveworld/commands/subcommands/SaveSubCommand.java diff --git a/src/autosaveworld/commands/subcommands/ServerStatusSubCommand.java b/src/main/java/autosaveworld/commands/subcommands/ServerStatusSubCommand.java similarity index 100% rename from src/autosaveworld/commands/subcommands/ServerStatusSubCommand.java rename to src/main/java/autosaveworld/commands/subcommands/ServerStatusSubCommand.java diff --git a/src/autosaveworld/commands/subcommands/StopCommand.java b/src/main/java/autosaveworld/commands/subcommands/StopCommand.java similarity index 100% rename from src/autosaveworld/commands/subcommands/StopCommand.java rename to src/main/java/autosaveworld/commands/subcommands/StopCommand.java diff --git a/src/autosaveworld/commands/subcommands/VersionSubCommand.java b/src/main/java/autosaveworld/commands/subcommands/VersionSubCommand.java similarity index 100% rename from src/autosaveworld/commands/subcommands/VersionSubCommand.java rename to src/main/java/autosaveworld/commands/subcommands/VersionSubCommand.java diff --git a/src/autosaveworld/commands/subcommands/WorldRegenSubCommand.java b/src/main/java/autosaveworld/commands/subcommands/WorldRegenSubCommand.java similarity index 100% rename from src/autosaveworld/commands/subcommands/WorldRegenSubCommand.java rename to src/main/java/autosaveworld/commands/subcommands/WorldRegenSubCommand.java diff --git a/src/autosaveworld/config/AutoSaveWorldConfig.java b/src/main/java/autosaveworld/config/AutoSaveWorldConfig.java similarity index 100% rename from src/autosaveworld/config/AutoSaveWorldConfig.java rename to src/main/java/autosaveworld/config/AutoSaveWorldConfig.java diff --git a/src/autosaveworld/config/AutoSaveWorldConfigMSG.java b/src/main/java/autosaveworld/config/AutoSaveWorldConfigMSG.java similarity index 100% rename from src/autosaveworld/config/AutoSaveWorldConfigMSG.java rename to src/main/java/autosaveworld/config/AutoSaveWorldConfigMSG.java diff --git a/src/autosaveworld/config/LocaleChanger.java b/src/main/java/autosaveworld/config/LocaleChanger.java similarity index 100% rename from src/autosaveworld/config/LocaleChanger.java rename to src/main/java/autosaveworld/config/LocaleChanger.java diff --git a/src/autosaveworld/config/loader/Config.java b/src/main/java/autosaveworld/config/loader/Config.java similarity index 100% rename from src/autosaveworld/config/loader/Config.java rename to src/main/java/autosaveworld/config/loader/Config.java diff --git a/src/autosaveworld/config/loader/ConfigLoader.java b/src/main/java/autosaveworld/config/loader/ConfigLoader.java similarity index 90% rename from src/autosaveworld/config/loader/ConfigLoader.java rename to src/main/java/autosaveworld/config/loader/ConfigLoader.java index 4e31f300..384259ee 100644 --- a/src/autosaveworld/config/loader/ConfigLoader.java +++ b/src/main/java/autosaveworld/config/loader/ConfigLoader.java @@ -38,7 +38,7 @@ public static void load(Config config) { field.setAccessible(true); ConfigOption option = field.getAnnotation(ConfigOption.class); if (option != null) { - YamlTransform transform = option.transform().newInstance(); + YamlTransform transform = option.transform().getDeclaredConstructor().newInstance(); String path = option.path(); Object newvalue = field.get(config); if (yconfig.contains(path)) { @@ -51,7 +51,7 @@ public static void load(Config config) { } } } - option.postload().newInstance().postLoad(newvalue); + option.postload().getDeclaredConstructor().newInstance().postLoad(newvalue); field.set(config, newvalue); } } @@ -67,7 +67,7 @@ public static void save(Config config) { field.setAccessible(true); ConfigOption option = field.getAnnotation(ConfigOption.class); if (option != null) { - YamlTransform transform = option.transform().newInstance(); + YamlTransform transform = option.transform().getDeclaredConstructor().newInstance(); yconfig.set(option.path(), transform.toYaml(field.get(config))); } } diff --git a/src/autosaveworld/config/loader/ConfigOption.java b/src/main/java/autosaveworld/config/loader/ConfigOption.java similarity index 100% rename from src/autosaveworld/config/loader/ConfigOption.java rename to src/main/java/autosaveworld/config/loader/ConfigOption.java diff --git a/src/autosaveworld/config/loader/postload/AstListAppend.java b/src/main/java/autosaveworld/config/loader/postload/AstListAppend.java similarity index 100% rename from src/autosaveworld/config/loader/postload/AstListAppend.java rename to src/main/java/autosaveworld/config/loader/postload/AstListAppend.java diff --git a/src/autosaveworld/config/loader/postload/DefaultCountdown.java b/src/main/java/autosaveworld/config/loader/postload/DefaultCountdown.java similarity index 100% rename from src/autosaveworld/config/loader/postload/DefaultCountdown.java rename to src/main/java/autosaveworld/config/loader/postload/DefaultCountdown.java diff --git a/src/autosaveworld/config/loader/postload/DefaultDestFolder.java b/src/main/java/autosaveworld/config/loader/postload/DefaultDestFolder.java similarity index 100% rename from src/autosaveworld/config/loader/postload/DefaultDestFolder.java rename to src/main/java/autosaveworld/config/loader/postload/DefaultDestFolder.java diff --git a/src/autosaveworld/config/loader/postload/NoPostLoad.java b/src/main/java/autosaveworld/config/loader/postload/NoPostLoad.java similarity index 100% rename from src/autosaveworld/config/loader/postload/NoPostLoad.java rename to src/main/java/autosaveworld/config/loader/postload/NoPostLoad.java diff --git a/src/autosaveworld/config/loader/postload/PostLoad.java b/src/main/java/autosaveworld/config/loader/postload/PostLoad.java similarity index 100% rename from src/autosaveworld/config/loader/postload/PostLoad.java rename to src/main/java/autosaveworld/config/loader/postload/PostLoad.java diff --git a/src/autosaveworld/config/loader/transform/ConfSectIntHashMap.java b/src/main/java/autosaveworld/config/loader/transform/ConfSectIntHashMap.java similarity index 100% rename from src/autosaveworld/config/loader/transform/ConfSectIntHashMap.java rename to src/main/java/autosaveworld/config/loader/transform/ConfSectIntHashMap.java diff --git a/src/autosaveworld/config/loader/transform/ConfSectStringHashMap.java b/src/main/java/autosaveworld/config/loader/transform/ConfSectStringHashMap.java similarity index 100% rename from src/autosaveworld/config/loader/transform/ConfSectStringHashMap.java rename to src/main/java/autosaveworld/config/loader/transform/ConfSectStringHashMap.java diff --git a/src/autosaveworld/config/loader/transform/ListClone.java b/src/main/java/autosaveworld/config/loader/transform/ListClone.java similarity index 100% rename from src/autosaveworld/config/loader/transform/ListClone.java rename to src/main/java/autosaveworld/config/loader/transform/ListClone.java diff --git a/src/autosaveworld/config/loader/transform/NoTrasform.java b/src/main/java/autosaveworld/config/loader/transform/NoTrasform.java similarity index 100% rename from src/autosaveworld/config/loader/transform/NoTrasform.java rename to src/main/java/autosaveworld/config/loader/transform/NoTrasform.java diff --git a/src/autosaveworld/config/loader/transform/YamlTransform.java b/src/main/java/autosaveworld/config/loader/transform/YamlTransform.java similarity index 100% rename from src/autosaveworld/config/loader/transform/YamlTransform.java rename to src/main/java/autosaveworld/config/loader/transform/YamlTransform.java diff --git a/src/autosaveworld/config/localefiles/LocaleFiles.java b/src/main/java/autosaveworld/config/localefiles/LocaleFiles.java similarity index 100% rename from src/autosaveworld/config/localefiles/LocaleFiles.java rename to src/main/java/autosaveworld/config/localefiles/LocaleFiles.java diff --git a/src/autosaveworld/config/localefiles/configmsg_en.yml b/src/main/java/autosaveworld/config/localefiles/configmsg_en.yml similarity index 100% rename from src/autosaveworld/config/localefiles/configmsg_en.yml rename to src/main/java/autosaveworld/config/localefiles/configmsg_en.yml diff --git a/src/autosaveworld/config/localefiles/configmsg_ru.yml b/src/main/java/autosaveworld/config/localefiles/configmsg_ru.yml similarity index 100% rename from src/autosaveworld/config/localefiles/configmsg_ru.yml rename to src/main/java/autosaveworld/config/localefiles/configmsg_ru.yml diff --git a/src/autosaveworld/core/AutoSaveWorld.java b/src/main/java/autosaveworld/core/AutoSaveWorld.java similarity index 100% rename from src/autosaveworld/core/AutoSaveWorld.java rename to src/main/java/autosaveworld/core/AutoSaveWorld.java diff --git a/src/autosaveworld/core/GlobalConstants.java b/src/main/java/autosaveworld/core/GlobalConstants.java similarity index 100% rename from src/autosaveworld/core/GlobalConstants.java rename to src/main/java/autosaveworld/core/GlobalConstants.java diff --git a/src/autosaveworld/core/logging/FormattingCodesParser.java b/src/main/java/autosaveworld/core/logging/FormattingCodesParser.java similarity index 100% rename from src/autosaveworld/core/logging/FormattingCodesParser.java rename to src/main/java/autosaveworld/core/logging/FormattingCodesParser.java diff --git a/src/autosaveworld/core/logging/MessageLogger.java b/src/main/java/autosaveworld/core/logging/MessageLogger.java similarity index 100% rename from src/autosaveworld/core/logging/MessageLogger.java rename to src/main/java/autosaveworld/core/logging/MessageLogger.java diff --git a/src/autosaveworld/features/backup/AutoBackupThread.java b/src/main/java/autosaveworld/features/backup/AutoBackupThread.java similarity index 100% rename from src/autosaveworld/features/backup/AutoBackupThread.java rename to src/main/java/autosaveworld/features/backup/AutoBackupThread.java diff --git a/src/autosaveworld/features/backup/Backup.java b/src/main/java/autosaveworld/features/backup/Backup.java similarity index 100% rename from src/autosaveworld/features/backup/Backup.java rename to src/main/java/autosaveworld/features/backup/Backup.java diff --git a/src/autosaveworld/features/backup/BackupUtils.java b/src/main/java/autosaveworld/features/backup/BackupUtils.java similarity index 100% rename from src/autosaveworld/features/backup/BackupUtils.java rename to src/main/java/autosaveworld/features/backup/BackupUtils.java diff --git a/src/autosaveworld/features/backup/InputStreamFactory.java b/src/main/java/autosaveworld/features/backup/InputStreamFactory.java similarity index 100% rename from src/autosaveworld/features/backup/InputStreamFactory.java rename to src/main/java/autosaveworld/features/backup/InputStreamFactory.java diff --git a/src/autosaveworld/features/backup/dropbox/DropboxBackup.java b/src/main/java/autosaveworld/features/backup/dropbox/DropboxBackup.java similarity index 94% rename from src/autosaveworld/features/backup/dropbox/DropboxBackup.java rename to src/main/java/autosaveworld/features/backup/dropbox/DropboxBackup.java index c1a30afd..f2eeb207 100644 --- a/src/autosaveworld/features/backup/dropbox/DropboxBackup.java +++ b/src/main/java/autosaveworld/features/backup/dropbox/DropboxBackup.java @@ -23,8 +23,8 @@ import autosaveworld.core.AutoSaveWorld; import autosaveworld.features.backup.Backup; import autosaveworld.features.backup.utils.virtualfilesystem.VirtualBackupManager; -import autosaveworld.zlibs.com.dropbox.core.DbxRequestConfig; -import autosaveworld.zlibs.com.dropbox.core.v2.DbxClientV2; +import com.dropbox.core.DbxRequestConfig; +import com.dropbox.core.v2.DbxClientV2; public class DropboxBackup extends Backup { diff --git a/src/autosaveworld/features/backup/dropbox/DropboxVirtualFileSystem.java b/src/main/java/autosaveworld/features/backup/dropbox/DropboxVirtualFileSystem.java similarity index 86% rename from src/autosaveworld/features/backup/dropbox/DropboxVirtualFileSystem.java rename to src/main/java/autosaveworld/features/backup/dropbox/DropboxVirtualFileSystem.java index 4759a363..975a6ffc 100644 --- a/src/autosaveworld/features/backup/dropbox/DropboxVirtualFileSystem.java +++ b/src/main/java/autosaveworld/features/backup/dropbox/DropboxVirtualFileSystem.java @@ -26,15 +26,15 @@ import autosaveworld.features.backup.utils.virtualfilesystem.VirtualFileSystem; import autosaveworld.utils.StringUtils; -import autosaveworld.zlibs.com.dropbox.core.DbxException; -import autosaveworld.zlibs.com.dropbox.core.v2.DbxClientV2; -import autosaveworld.zlibs.com.dropbox.core.v2.files.CommitInfo; -import autosaveworld.zlibs.com.dropbox.core.v2.files.FolderMetadata; -import autosaveworld.zlibs.com.dropbox.core.v2.files.GetMetadataErrorException; -import autosaveworld.zlibs.com.dropbox.core.v2.files.ListFolderResult; -import autosaveworld.zlibs.com.dropbox.core.v2.files.Metadata; -import autosaveworld.zlibs.com.dropbox.core.v2.files.UploadSessionCursor; -import autosaveworld.zlibs.com.dropbox.core.v2.files.UploadSessionStartResult; +import com.dropbox.core.DbxException; +import com.dropbox.core.v2.DbxClientV2; +import com.dropbox.core.v2.files.CommitInfo; +import com.dropbox.core.v2.files.FolderMetadata; +import com.dropbox.core.v2.files.GetMetadataErrorException; +import com.dropbox.core.v2.files.ListFolderResult; +import com.dropbox.core.v2.files.Metadata; +import com.dropbox.core.v2.files.UploadSessionCursor; +import com.dropbox.core.v2.files.UploadSessionStartResult; public class DropboxVirtualFileSystem extends VirtualFileSystem { @@ -52,7 +52,7 @@ public void enterDirectory0(String dirname) throws IOException { @Override public void createDirectory0(String dirname) throws IOException { try { - dbxclient.files().createFolder(getPath(dirname)); + dbxclient.files().createFolderV2(getPath(dirname)); } catch (DbxException e) { throw wrapException(e); } @@ -149,7 +149,7 @@ public void createFile(String name, InputStream inputsteam) throws IOException { private void delete(String name) throws IOException { try { - dbxclient.files().delete(getPath(name)); + dbxclient.files().deleteV2(getPath(name)); } catch (DbxException e) { throw wrapException(e); } diff --git a/src/autosaveworld/features/backup/ftp/FTPBackup.java b/src/main/java/autosaveworld/features/backup/ftp/FTPBackup.java similarity index 92% rename from src/autosaveworld/features/backup/ftp/FTPBackup.java rename to src/main/java/autosaveworld/features/backup/ftp/FTPBackup.java index c066fba9..3874a6d8 100644 --- a/src/autosaveworld/features/backup/ftp/FTPBackup.java +++ b/src/main/java/autosaveworld/features/backup/ftp/FTPBackup.java @@ -24,9 +24,9 @@ import autosaveworld.core.AutoSaveWorld; import autosaveworld.features.backup.Backup; import autosaveworld.features.backup.utils.virtualfilesystem.VirtualBackupManager; -import autosaveworld.zlibs.org.apache.commons.net.ftp.FTP; -import autosaveworld.zlibs.org.apache.commons.net.ftp.FTPClient; -import autosaveworld.zlibs.org.apache.commons.net.ftp.FTPReply; +import org.apache.commons.net.ftp.FTP; +import org.apache.commons.net.ftp.FTPClient; +import org.apache.commons.net.ftp.FTPReply; public class FTPBackup extends Backup { diff --git a/src/autosaveworld/features/backup/ftp/FTPVirtualFileSystem.java b/src/main/java/autosaveworld/features/backup/ftp/FTPVirtualFileSystem.java similarity index 97% rename from src/autosaveworld/features/backup/ftp/FTPVirtualFileSystem.java rename to src/main/java/autosaveworld/features/backup/ftp/FTPVirtualFileSystem.java index 05e7fc31..df93d4ff 100644 --- a/src/autosaveworld/features/backup/ftp/FTPVirtualFileSystem.java +++ b/src/main/java/autosaveworld/features/backup/ftp/FTPVirtualFileSystem.java @@ -24,7 +24,7 @@ import java.util.Set; import autosaveworld.features.backup.utils.virtualfilesystem.VirtualFileSystem; -import autosaveworld.zlibs.org.apache.commons.net.ftp.FTPClient; +import org.apache.commons.net.ftp.FTPClient; public class FTPVirtualFileSystem extends VirtualFileSystem { diff --git a/src/autosaveworld/features/backup/googledrive/GoogleDriveBackup.java b/src/main/java/autosaveworld/features/backup/googledrive/GoogleDriveBackup.java similarity index 51% rename from src/autosaveworld/features/backup/googledrive/GoogleDriveBackup.java rename to src/main/java/autosaveworld/features/backup/googledrive/GoogleDriveBackup.java index a329b2be..ecabe939 100644 --- a/src/autosaveworld/features/backup/googledrive/GoogleDriveBackup.java +++ b/src/main/java/autosaveworld/features/backup/googledrive/GoogleDriveBackup.java @@ -26,10 +26,13 @@ import autosaveworld.core.AutoSaveWorld; import autosaveworld.features.backup.Backup; import autosaveworld.features.backup.utils.virtualfilesystem.VirtualBackupManager; -import autosaveworld.zlibs.com.google.api.client.googleapis.auth.oauth2.GoogleCredential; -import autosaveworld.zlibs.com.google.api.client.json.jackson2.JacksonFactory; -import autosaveworld.zlibs.com.google.api.services.drive.Drive; -import autosaveworld.zlibs.com.google.api.services.drive.DriveScopes; +import com.google.api.client.googleapis.util.Utils; +import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.json.jackson2.JacksonFactory; +import com.google.api.services.drive.Drive; +import com.google.api.services.drive.DriveScopes; +import com.google.auth.http.HttpCredentialsAdapter; +import com.google.auth.oauth2.GoogleCredentials; public class GoogleDriveBackup extends Backup { @@ -40,22 +43,24 @@ public GoogleDriveBackup() { public void performBackup() throws IOException { AutoSaveWorldConfig config = AutoSaveWorld.getInstance().getMainConfig(); - GoogleCredential cred = GoogleCredential - .fromStream(new FileInputStream(new File(config.backupGDriveAuthFile))) - .createScoped(Collections.singletonList(DriveScopes.DRIVE)); - Drive driveclient = new Drive.Builder(cred.getTransport(), JacksonFactory.getDefaultInstance(), cred) - .setApplicationName(AutoSaveWorld.getInstance().getName()).build(); + HttpRequestInitializer httpRequestInitializer = new HttpCredentialsAdapter( + GoogleCredentials + .fromStream(new FileInputStream(new File(config.backupGDriveAuthFile))) + .createScoped(Collections.singletonList(DriveScopes.DRIVE)) + ); + Drive driveclient = new Drive.Builder(Utils.getDefaultTransport(), JacksonFactory.getDefaultInstance(), httpRequestInitializer) + .setApplicationName(AutoSaveWorld.getInstance().getName()).build(); VirtualBackupManager.builder() - .setBackupPath(config.backupGDrivePath) - .setWorldList(config.backupGDriveWorldsList) - .setBackupPlugins(config.backupGDrivePluginsFolder) - .setOtherFolders(config.backupGDriveOtherFolders) - .setExcludedFolders(config.backupGDriveExcludeFolders) - .setMaxBackupNumber(config.backupGDriveMaxNumberOfBackups) - .setZip(config.backupGDriveZipEnabled) - .setVFS(new GoogleDriveVirtualFileSystem(driveclient, config.backupGDRiveRootFolder)) - .create().backup(); + .setBackupPath(config.backupGDrivePath) + .setWorldList(config.backupGDriveWorldsList) + .setBackupPlugins(config.backupGDrivePluginsFolder) + .setOtherFolders(config.backupGDriveOtherFolders) + .setExcludedFolders(config.backupGDriveExcludeFolders) + .setMaxBackupNumber(config.backupGDriveMaxNumberOfBackups) + .setZip(config.backupGDriveZipEnabled) + .setVFS(new GoogleDriveVirtualFileSystem(driveclient, config.backupGDRiveRootFolder)) + .create().backup(); } } diff --git a/src/autosaveworld/features/backup/googledrive/GoogleDriveVirtualFileSystem.java b/src/main/java/autosaveworld/features/backup/googledrive/GoogleDriveVirtualFileSystem.java similarity index 82% rename from src/autosaveworld/features/backup/googledrive/GoogleDriveVirtualFileSystem.java rename to src/main/java/autosaveworld/features/backup/googledrive/GoogleDriveVirtualFileSystem.java index c3ed5bba..7321eeb2 100644 --- a/src/autosaveworld/features/backup/googledrive/GoogleDriveVirtualFileSystem.java +++ b/src/main/java/autosaveworld/features/backup/googledrive/GoogleDriveVirtualFileSystem.java @@ -26,10 +26,9 @@ import java.util.Set; import autosaveworld.features.backup.utils.virtualfilesystem.VirtualFileSystem; -import autosaveworld.zlibs.com.google.api.client.http.InputStreamContent; -import autosaveworld.zlibs.com.google.api.services.drive.Drive; -import autosaveworld.zlibs.com.google.api.services.drive.model.File; -import autosaveworld.zlibs.com.google.api.services.drive.model.ParentReference; +import com.google.api.client.http.InputStreamContent; +import com.google.api.services.drive.Drive; +import com.google.api.services.drive.model.File; public class GoogleDriveVirtualFileSystem extends VirtualFileSystem { @@ -58,10 +57,10 @@ protected void enterDirectory0(String dirname) throws IOException { @Override protected void createDirectory0(String dirname) throws IOException { File folder = new File(); - folder.setTitle(dirname); + folder.setName(dirname); folder.setMimeType("application/vnd.google-apps.folder"); - folder.setParents(Collections.singletonList(new ParentReference().setId(getCurrentFolder()))); - driveclient.files().insert(folder).execute(); + folder.setParents(Collections.singletonList(getCurrentFolder())); + driveclient.files().create(folder).execute(); } @Override @@ -104,8 +103,8 @@ public void deleteFile(String name) throws IOException { @Override public Set getEntries() throws IOException { HashSet result = new HashSet<>(); - for (File file : driveclient.files().list().setQ(quotes(getCurrentFolder()) + " in parents").execute().getItems()) { - result.add(file.getTitle()); + for (File file : driveclient.files().list().setQ(quotes(getCurrentFolder()) + " in parents").execute().getFiles()) { + result.add(file.getName()); } return result; } @@ -113,9 +112,9 @@ public Set getEntries() throws IOException { @Override public void createFile(String name, InputStream inputsteam) throws IOException { File file = new File(); - file.setTitle(name); - file.setParents(Collections.singletonList(new ParentReference().setId(getCurrentFolder()))); - driveclient.files().insert(file, new InputStreamContent(null, inputsteam)).execute(); + file.setName(name); + file.setParents(Collections.singletonList(getCurrentFolder())); + driveclient.files().create(file, new InputStreamContent(null, inputsteam)).execute(); } @@ -128,7 +127,7 @@ private void delete(String name) throws IOException { } private File findFile(String dirname) throws IOException { - List files = driveclient.files().list().setQ(quotes(getCurrentFolder()) + " in parents and title = " + quotes(dirname)).execute().getItems(); + List files = driveclient.files().list().setQ(quotes(getCurrentFolder()) + " in parents and name = " + quotes(dirname)).execute().getFiles(); if (files.isEmpty()) { return null; } diff --git a/src/autosaveworld/features/backup/localfs/LocalFSBackup.java b/src/main/java/autosaveworld/features/backup/localfs/LocalFSBackup.java similarity index 100% rename from src/autosaveworld/features/backup/localfs/LocalFSBackup.java rename to src/main/java/autosaveworld/features/backup/localfs/LocalFSBackup.java diff --git a/src/autosaveworld/features/backup/localfs/LocalFSBackupOperations.java b/src/main/java/autosaveworld/features/backup/localfs/LocalFSBackupOperations.java similarity index 100% rename from src/autosaveworld/features/backup/localfs/LocalFSBackupOperations.java rename to src/main/java/autosaveworld/features/backup/localfs/LocalFSBackupOperations.java diff --git a/src/autosaveworld/features/backup/localfs/LocalFSUtils.java b/src/main/java/autosaveworld/features/backup/localfs/LocalFSUtils.java similarity index 100% rename from src/autosaveworld/features/backup/localfs/LocalFSUtils.java rename to src/main/java/autosaveworld/features/backup/localfs/LocalFSUtils.java diff --git a/src/autosaveworld/features/backup/script/ScriptBackup.java b/src/main/java/autosaveworld/features/backup/script/ScriptBackup.java similarity index 100% rename from src/autosaveworld/features/backup/script/ScriptBackup.java rename to src/main/java/autosaveworld/features/backup/script/ScriptBackup.java diff --git a/src/autosaveworld/features/backup/sftp/SFTPBackup.java b/src/main/java/autosaveworld/features/backup/sftp/SFTPBackup.java similarity index 84% rename from src/autosaveworld/features/backup/sftp/SFTPBackup.java rename to src/main/java/autosaveworld/features/backup/sftp/SFTPBackup.java index 541b75ee..458753ab 100644 --- a/src/autosaveworld/features/backup/sftp/SFTPBackup.java +++ b/src/main/java/autosaveworld/features/backup/sftp/SFTPBackup.java @@ -23,12 +23,11 @@ import autosaveworld.core.AutoSaveWorld; import autosaveworld.features.backup.Backup; import autosaveworld.features.backup.utils.virtualfilesystem.VirtualBackupManager; -import autosaveworld.zlibs.com.jcraft.jsch.Channel; -import autosaveworld.zlibs.com.jcraft.jsch.Channel.ChannelType; -import autosaveworld.zlibs.com.jcraft.jsch.ChannelSftp; -import autosaveworld.zlibs.com.jcraft.jsch.JSch; -import autosaveworld.zlibs.com.jcraft.jsch.JSchException; -import autosaveworld.zlibs.com.jcraft.jsch.Session; +import com.jcraft.jsch.Channel; +import com.jcraft.jsch.ChannelSftp; +import com.jcraft.jsch.JSch; +import com.jcraft.jsch.JSchException; +import com.jcraft.jsch.Session; public class SFTPBackup extends Backup { @@ -44,7 +43,7 @@ public void performBackup() throws JSchException, IOException { session.setTimeout(10000); session.setPassword(config.backupSFTPPassworld); session.connect(); - Channel channel = session.openChannel(ChannelType.SFTP); + Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp channelSftp = (ChannelSftp) channel; diff --git a/src/autosaveworld/features/backup/sftp/SFTPVirtualFileSystem.java b/src/main/java/autosaveworld/features/backup/sftp/SFTPVirtualFileSystem.java similarity index 94% rename from src/autosaveworld/features/backup/sftp/SFTPVirtualFileSystem.java rename to src/main/java/autosaveworld/features/backup/sftp/SFTPVirtualFileSystem.java index fc709480..367101e1 100644 --- a/src/autosaveworld/features/backup/sftp/SFTPVirtualFileSystem.java +++ b/src/main/java/autosaveworld/features/backup/sftp/SFTPVirtualFileSystem.java @@ -24,9 +24,9 @@ import java.util.Vector; import autosaveworld.features.backup.utils.virtualfilesystem.VirtualFileSystem; -import autosaveworld.zlibs.com.jcraft.jsch.ChannelSftp; -import autosaveworld.zlibs.com.jcraft.jsch.ChannelSftp.LsEntry; -import autosaveworld.zlibs.com.jcraft.jsch.SftpException; +import com.jcraft.jsch.ChannelSftp; +import com.jcraft.jsch.ChannelSftp.LsEntry; +import com.jcraft.jsch.SftpException; public class SFTPVirtualFileSystem extends VirtualFileSystem { @@ -106,6 +106,7 @@ public void deleteFile(String name) throws IOException { public Set getEntries() throws IOException { try { HashSet files = new HashSet(); + @SuppressWarnings("unchecked") Vector names = sftpclient.ls("."); for (int i = 0; i < names.size(); i++) { String filename = names.get(i).getFilename(); diff --git a/src/autosaveworld/features/backup/utils/PipedZip.java b/src/main/java/autosaveworld/features/backup/utils/PipedZip.java similarity index 100% rename from src/autosaveworld/features/backup/utils/PipedZip.java rename to src/main/java/autosaveworld/features/backup/utils/PipedZip.java diff --git a/src/autosaveworld/features/backup/utils/ZipUtils.java b/src/main/java/autosaveworld/features/backup/utils/ZipUtils.java similarity index 97% rename from src/autosaveworld/features/backup/utils/ZipUtils.java rename to src/main/java/autosaveworld/features/backup/utils/ZipUtils.java index 9040e553..a591ca24 100644 --- a/src/autosaveworld/features/backup/utils/ZipUtils.java +++ b/src/main/java/autosaveworld/features/backup/utils/ZipUtils.java @@ -60,10 +60,10 @@ private static void zipDir(List excludefolders, ZipOutputStream zipOutSt if (srcFile.isDirectory()) { if (!BackupUtils.isFolderExcluded(excludefolders, srcDir.getName() + File.separator + currentDir + child)) { - zipDir(excludefolders, zipOutStream, srcDir, currentDir + child + File.separator); + zipDir(excludefolders, zipOutStream, srcDir, currentDir + child + '/'); } } else { - zipFile(zipOutStream, srcFile, srcDir.getName() + File.separator + currentDir + child); + zipFile(zipOutStream, srcFile, srcDir.getName() + '/' + currentDir + child); } } } diff --git a/src/autosaveworld/features/backup/utils/ratelimitedstreams/RateLimitedInputStream.java b/src/main/java/autosaveworld/features/backup/utils/ratelimitedstreams/RateLimitedInputStream.java similarity index 100% rename from src/autosaveworld/features/backup/utils/ratelimitedstreams/RateLimitedInputStream.java rename to src/main/java/autosaveworld/features/backup/utils/ratelimitedstreams/RateLimitedInputStream.java diff --git a/src/autosaveworld/features/backup/utils/virtualfilesystem/VirtualBackupManager.java b/src/main/java/autosaveworld/features/backup/utils/virtualfilesystem/VirtualBackupManager.java similarity index 100% rename from src/autosaveworld/features/backup/utils/virtualfilesystem/VirtualBackupManager.java rename to src/main/java/autosaveworld/features/backup/utils/virtualfilesystem/VirtualBackupManager.java diff --git a/src/autosaveworld/features/backup/utils/virtualfilesystem/VirtualFileSystem.java b/src/main/java/autosaveworld/features/backup/utils/virtualfilesystem/VirtualFileSystem.java similarity index 100% rename from src/autosaveworld/features/backup/utils/virtualfilesystem/VirtualFileSystem.java rename to src/main/java/autosaveworld/features/backup/utils/virtualfilesystem/VirtualFileSystem.java diff --git a/src/autosaveworld/features/consolecommand/AutoConsoleCommandThread.java b/src/main/java/autosaveworld/features/consolecommand/AutoConsoleCommandThread.java similarity index 100% rename from src/autosaveworld/features/consolecommand/AutoConsoleCommandThread.java rename to src/main/java/autosaveworld/features/consolecommand/AutoConsoleCommandThread.java diff --git a/src/autosaveworld/features/networkwatcher/NetworkWatcher.java b/src/main/java/autosaveworld/features/networkwatcher/NetworkWatcher.java similarity index 100% rename from src/autosaveworld/features/networkwatcher/NetworkWatcher.java rename to src/main/java/autosaveworld/features/networkwatcher/NetworkWatcher.java diff --git a/src/autosaveworld/features/networkwatcher/NetworkWatcherProxySelector.java b/src/main/java/autosaveworld/features/networkwatcher/NetworkWatcherProxySelector.java similarity index 100% rename from src/autosaveworld/features/networkwatcher/NetworkWatcherProxySelector.java rename to src/main/java/autosaveworld/features/networkwatcher/NetworkWatcherProxySelector.java diff --git a/src/autosaveworld/features/pluginmanager/InternalUtils.java b/src/main/java/autosaveworld/features/pluginmanager/InternalUtils.java similarity index 100% rename from src/autosaveworld/features/pluginmanager/InternalUtils.java rename to src/main/java/autosaveworld/features/pluginmanager/InternalUtils.java diff --git a/src/autosaveworld/features/pluginmanager/PluginManager.java b/src/main/java/autosaveworld/features/pluginmanager/PluginManager.java similarity index 100% rename from src/autosaveworld/features/pluginmanager/PluginManager.java rename to src/main/java/autosaveworld/features/pluginmanager/PluginManager.java diff --git a/src/autosaveworld/features/processmanager/ProcessManager.java b/src/main/java/autosaveworld/features/processmanager/ProcessManager.java similarity index 100% rename from src/autosaveworld/features/processmanager/ProcessManager.java rename to src/main/java/autosaveworld/features/processmanager/ProcessManager.java diff --git a/src/autosaveworld/features/processmanager/ProcessStorage.java b/src/main/java/autosaveworld/features/processmanager/ProcessStorage.java similarity index 100% rename from src/autosaveworld/features/processmanager/ProcessStorage.java rename to src/main/java/autosaveworld/features/processmanager/ProcessStorage.java diff --git a/src/autosaveworld/features/processmanager/RunningProcess.java b/src/main/java/autosaveworld/features/processmanager/RunningProcess.java similarity index 100% rename from src/autosaveworld/features/processmanager/RunningProcess.java rename to src/main/java/autosaveworld/features/processmanager/RunningProcess.java diff --git a/src/autosaveworld/features/purge/ActivePlayersList.java b/src/main/java/autosaveworld/features/purge/ActivePlayersList.java similarity index 100% rename from src/autosaveworld/features/purge/ActivePlayersList.java rename to src/main/java/autosaveworld/features/purge/ActivePlayersList.java diff --git a/src/autosaveworld/features/purge/AutoPurgeThread.java b/src/main/java/autosaveworld/features/purge/AutoPurgeThread.java similarity index 100% rename from src/autosaveworld/features/purge/AutoPurgeThread.java rename to src/main/java/autosaveworld/features/purge/AutoPurgeThread.java diff --git a/src/autosaveworld/features/purge/DataPurge.java b/src/main/java/autosaveworld/features/purge/DataPurge.java similarity index 100% rename from src/autosaveworld/features/purge/DataPurge.java rename to src/main/java/autosaveworld/features/purge/DataPurge.java diff --git a/src/autosaveworld/features/purge/plugins/DatfilePurge.java b/src/main/java/autosaveworld/features/purge/plugins/DatfilePurge.java similarity index 100% rename from src/autosaveworld/features/purge/plugins/DatfilePurge.java rename to src/main/java/autosaveworld/features/purge/plugins/DatfilePurge.java diff --git a/src/autosaveworld/features/purge/plugins/essentials/EssentialsPurge.java b/src/main/java/autosaveworld/features/purge/plugins/essentials/EssentialsPurge.java similarity index 100% rename from src/autosaveworld/features/purge/plugins/essentials/EssentialsPurge.java rename to src/main/java/autosaveworld/features/purge/plugins/essentials/EssentialsPurge.java diff --git a/src/autosaveworld/features/purge/plugins/lwc/LWCDeleteTask.java b/src/main/java/autosaveworld/features/purge/plugins/lwc/LWCDeleteTask.java similarity index 100% rename from src/autosaveworld/features/purge/plugins/lwc/LWCDeleteTask.java rename to src/main/java/autosaveworld/features/purge/plugins/lwc/LWCDeleteTask.java diff --git a/src/autosaveworld/features/purge/plugins/lwc/LWCMembersClearTask.java b/src/main/java/autosaveworld/features/purge/plugins/lwc/LWCMembersClearTask.java similarity index 100% rename from src/autosaveworld/features/purge/plugins/lwc/LWCMembersClearTask.java rename to src/main/java/autosaveworld/features/purge/plugins/lwc/LWCMembersClearTask.java diff --git a/src/autosaveworld/features/purge/plugins/lwc/LWCPurge.java b/src/main/java/autosaveworld/features/purge/plugins/lwc/LWCPurge.java similarity index 100% rename from src/autosaveworld/features/purge/plugins/lwc/LWCPurge.java rename to src/main/java/autosaveworld/features/purge/plugins/lwc/LWCPurge.java diff --git a/src/autosaveworld/features/purge/plugins/lwc/LWCRegenTask.java b/src/main/java/autosaveworld/features/purge/plugins/lwc/LWCRegenTask.java similarity index 100% rename from src/autosaveworld/features/purge/plugins/lwc/LWCRegenTask.java rename to src/main/java/autosaveworld/features/purge/plugins/lwc/LWCRegenTask.java diff --git a/src/autosaveworld/features/purge/plugins/mywarp/MyWapWarpDeleteTask.java b/src/main/java/autosaveworld/features/purge/plugins/mywarp/MyWapWarpDeleteTask.java similarity index 92% rename from src/autosaveworld/features/purge/plugins/mywarp/MyWapWarpDeleteTask.java rename to src/main/java/autosaveworld/features/purge/plugins/mywarp/MyWapWarpDeleteTask.java index 8ae28d7a..d1ca5ca7 100644 --- a/src/autosaveworld/features/purge/plugins/mywarp/MyWapWarpDeleteTask.java +++ b/src/main/java/autosaveworld/features/purge/plugins/mywarp/MyWapWarpDeleteTask.java @@ -18,8 +18,9 @@ package autosaveworld.features.purge.plugins.mywarp; import autosaveworld.features.purge.taskqueue.Task; -import me.taylorkelly.mywarp.warp.Warp; -import me.taylorkelly.mywarp.warp.WarpManager; + +import io.github.mywarp.mywarp.warp.Warp; +import io.github.mywarp.mywarp.warp.WarpManager; public class MyWapWarpDeleteTask implements Task { diff --git a/src/autosaveworld/features/purge/plugins/mywarp/MyWarpInvitesClearTask.java b/src/main/java/autosaveworld/features/purge/plugins/mywarp/MyWarpInvitesClearTask.java similarity index 67% rename from src/autosaveworld/features/purge/plugins/mywarp/MyWarpInvitesClearTask.java rename to src/main/java/autosaveworld/features/purge/plugins/mywarp/MyWarpInvitesClearTask.java index f9070ab6..a82cb885 100644 --- a/src/autosaveworld/features/purge/plugins/mywarp/MyWarpInvitesClearTask.java +++ b/src/main/java/autosaveworld/features/purge/plugins/mywarp/MyWarpInvitesClearTask.java @@ -21,8 +21,9 @@ import autosaveworld.core.logging.MessageLogger; import autosaveworld.features.purge.taskqueue.Task; -import me.taylorkelly.mywarp.util.profile.Profile; -import me.taylorkelly.mywarp.warp.Warp; + +import io.github.mywarp.mywarp.util.playermatcher.PlayerMatcher; +import io.github.mywarp.mywarp.warp.Warp; public class MyWarpInvitesClearTask implements Task { @@ -32,18 +33,18 @@ public MyWarpInvitesClearTask(Warp warp) { this.warp = warp; } - private LinkedList profiles = new LinkedList(); + private LinkedList invitations = new LinkedList(); - public void add(Profile profile) { - profiles.add(profile); + public void add(PlayerMatcher profile) { + invitations.add(profile); } public boolean hasPlayersToClear() { - return !profiles.isEmpty(); + return !invitations.isEmpty(); } public int getPlayerToClearCount() { - return profiles.size(); + return invitations.size(); } @Override @@ -53,10 +54,10 @@ public boolean doNotQueue() { @Override public void performTask() { - MessageLogger.debug("Cleaning invites for warp "+warp.getName()); - for (Profile name : profiles) { - warp.uninvitePlayer(name); + MessageLogger.debug("Cleaning invites for warp " + warp.getName()); + for (PlayerMatcher invitation : invitations) { + warp.removeInvitation(invitation); } + // warp.removeInvitation(player -> invitations.stream().map(Profile::getUuid).anyMatch(player.getUniqueId()::equals)); } - } diff --git a/src/autosaveworld/features/purge/plugins/mywarp/MyWarpPurge.java b/src/main/java/autosaveworld/features/purge/plugins/mywarp/MyWarpPurge.java similarity index 67% rename from src/autosaveworld/features/purge/plugins/mywarp/MyWarpPurge.java rename to src/main/java/autosaveworld/features/purge/plugins/mywarp/MyWarpPurge.java index 2bf9b1b6..f300df2f 100644 --- a/src/autosaveworld/features/purge/plugins/mywarp/MyWarpPurge.java +++ b/src/main/java/autosaveworld/features/purge/plugins/mywarp/MyWarpPurge.java @@ -17,21 +17,23 @@ package autosaveworld.features.purge.plugins.mywarp; -import java.util.List; +import java.util.Collection; +import java.util.UUID; import org.bukkit.plugin.java.JavaPlugin; -import com.google.common.base.Predicate; +import io.github.mywarp.mywarp.MyWarp; +import io.github.mywarp.mywarp.bukkit.MyWarpPlugin; +import io.github.mywarp.mywarp.util.playermatcher.GroupPlayerMatcher; +import io.github.mywarp.mywarp.util.playermatcher.PlayerMatcher; +import io.github.mywarp.mywarp.util.playermatcher.UuidPlayerMatcher; +import io.github.mywarp.mywarp.warp.Warp; import autosaveworld.core.logging.MessageLogger; import autosaveworld.features.purge.ActivePlayersList; import autosaveworld.features.purge.DataPurge; import autosaveworld.features.purge.taskqueue.TaskExecutor; import autosaveworld.utils.ReflectionUtils; -import me.taylorkelly.mywarp.MyWarp; -import me.taylorkelly.mywarp.bukkit.MyWarpPlugin; -import me.taylorkelly.mywarp.util.profile.Profile; -import me.taylorkelly.mywarp.warp.Warp; public class MyWarpPurge extends DataPurge { @@ -50,23 +52,22 @@ public void doPurge() { } try (TaskExecutor queue = new TaskExecutor(80)) { - List warps = mywarp.getWarpManager().getMatchingWarps("", new Predicate() { - @Override - public boolean apply(Warp warp) { - return true; - } - }).getMatches(); + Collection warps = mywarp.getWarpManager().getAll(warp -> true); for (Warp warp : warps) { MyWarpInvitesClearTask invitesClearTask = new MyWarpInvitesClearTask(warp); - for (Profile profile : warp.getInvitedPlayers()) { - if (!activeplayerslist.isActiveUUID(profile.getUniqueId())) { - MessageLogger.debug("Warp member "+profile.getUniqueId()+" is inactive"); - invitesClearTask.add(profile); + for (PlayerMatcher invitation : warp.getInvitations()) { + if (invitation instanceof GroupPlayerMatcher) { + continue; + } + UUID uuid = ((UuidPlayerMatcher) invitation).getCriteria(); + if (!activeplayerslist.isActiveUUID(uuid)) { + MessageLogger.debug("Warp member "+uuid+" is inactive"); + invitesClearTask.add(invitation); } } // delete warp if owner and members are inactive - if (!activeplayerslist.isActiveUUID(warp.getCreator().getUniqueId()) && (invitesClearTask.getPlayerToClearCount() == warp.getInvitedPlayers().size())) { - MessageLogger.debug("Warp owner "+warp.getCreator().getUniqueId()+" is inactive"); + if (!activeplayerslist.isActiveUUID(warp.getCreator()) && (invitesClearTask.getPlayerToClearCount() == warp.getInvitations().size())) { + MessageLogger.debug("Warp owner "+warp.getCreator()+" is inactive"); // delete warp MyWapWarpDeleteTask deleteTask = new MyWapWarpDeleteTask(mywarp.getWarpManager(), warp); queue.execute(deleteTask); diff --git a/src/autosaveworld/features/purge/plugins/permissions/GroupManagerPurge.java b/src/main/java/autosaveworld/features/purge/plugins/permissions/GroupManagerPurge.java similarity index 100% rename from src/autosaveworld/features/purge/plugins/permissions/GroupManagerPurge.java rename to src/main/java/autosaveworld/features/purge/plugins/permissions/GroupManagerPurge.java diff --git a/src/autosaveworld/features/purge/plugins/permissions/PermissionsPurge.java b/src/main/java/autosaveworld/features/purge/plugins/permissions/PermissionsPurge.java similarity index 100% rename from src/autosaveworld/features/purge/plugins/permissions/PermissionsPurge.java rename to src/main/java/autosaveworld/features/purge/plugins/permissions/PermissionsPurge.java diff --git a/src/autosaveworld/features/purge/plugins/permissions/VaultPurge.java b/src/main/java/autosaveworld/features/purge/plugins/permissions/VaultPurge.java similarity index 100% rename from src/autosaveworld/features/purge/plugins/permissions/VaultPurge.java rename to src/main/java/autosaveworld/features/purge/plugins/permissions/VaultPurge.java diff --git a/src/autosaveworld/features/purge/plugins/wg/DomainClearTask.java b/src/main/java/autosaveworld/features/purge/plugins/wg/DomainClearTask.java similarity index 100% rename from src/autosaveworld/features/purge/plugins/wg/DomainClearTask.java rename to src/main/java/autosaveworld/features/purge/plugins/wg/DomainClearTask.java diff --git a/src/autosaveworld/features/purge/plugins/wg/RegionDeleteTask.java b/src/main/java/autosaveworld/features/purge/plugins/wg/RegionDeleteTask.java similarity index 100% rename from src/autosaveworld/features/purge/plugins/wg/RegionDeleteTask.java rename to src/main/java/autosaveworld/features/purge/plugins/wg/RegionDeleteTask.java diff --git a/src/autosaveworld/features/purge/plugins/wg/RegionRegenTask.java b/src/main/java/autosaveworld/features/purge/plugins/wg/RegionRegenTask.java similarity index 100% rename from src/autosaveworld/features/purge/plugins/wg/RegionRegenTask.java rename to src/main/java/autosaveworld/features/purge/plugins/wg/RegionRegenTask.java diff --git a/src/autosaveworld/features/purge/plugins/wg/WGPurge.java b/src/main/java/autosaveworld/features/purge/plugins/wg/WGPurge.java similarity index 100% rename from src/autosaveworld/features/purge/plugins/wg/WGPurge.java rename to src/main/java/autosaveworld/features/purge/plugins/wg/WGPurge.java diff --git a/src/autosaveworld/features/purge/taskqueue/Task.java b/src/main/java/autosaveworld/features/purge/taskqueue/Task.java similarity index 100% rename from src/autosaveworld/features/purge/taskqueue/Task.java rename to src/main/java/autosaveworld/features/purge/taskqueue/Task.java diff --git a/src/autosaveworld/features/purge/taskqueue/TaskExecutor.java b/src/main/java/autosaveworld/features/purge/taskqueue/TaskExecutor.java similarity index 100% rename from src/autosaveworld/features/purge/taskqueue/TaskExecutor.java rename to src/main/java/autosaveworld/features/purge/taskqueue/TaskExecutor.java diff --git a/src/autosaveworld/features/purge/weregen/BukkitAPIWorldEditRegeneration.java b/src/main/java/autosaveworld/features/purge/weregen/BukkitAPIWorldEditRegeneration.java similarity index 51% rename from src/autosaveworld/features/purge/weregen/BukkitAPIWorldEditRegeneration.java rename to src/main/java/autosaveworld/features/purge/weregen/BukkitAPIWorldEditRegeneration.java index 6e3b656a..6222ccc0 100644 --- a/src/autosaveworld/features/purge/weregen/BukkitAPIWorldEditRegeneration.java +++ b/src/main/java/autosaveworld/features/purge/weregen/BukkitAPIWorldEditRegeneration.java @@ -22,16 +22,17 @@ import org.bukkit.Material; import org.bukkit.World; +import org.bukkit.util.Vector; import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.Vector2D; -import com.sk89q.worldedit.blocks.BaseBlock; -import com.sk89q.worldedit.blocks.BlockType; +import com.sk89q.worldedit.EditSessionFactory; +import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.bukkit.BukkitWorld; +import com.sk89q.worldedit.math.BlockVector2; +import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.CuboidRegion; import com.sk89q.worldedit.regions.Region; -import com.sk89q.worldguard.bukkit.BukkitUtil; +import com.sk89q.worldedit.world.block.BaseBlock; import autosaveworld.core.logging.MessageLogger; import autosaveworld.features.purge.weregen.UtilClasses.BlockToPlaceBack; @@ -39,23 +40,22 @@ import autosaveworld.features.purge.weregen.WorldEditRegeneration.WorldEditRegenrationInterface; import autosaveworld.utils.BukkitUtils; -//TODO: Migrate to new WorldEdit API public class BukkitAPIWorldEditRegeneration implements WorldEditRegenrationInterface { private ItemSpawnListener itemremover = new ItemSpawnListener(); @Override - public void regenerateRegion(World world, org.bukkit.util.Vector minpoint, org.bukkit.util.Vector maxpoint) { - Vector minbpoint = BukkitUtil.toVector(minpoint); - Vector maxbpoint = BukkitUtil.toVector(maxpoint); + public void regenerateRegion(World world, Vector minpoint, Vector maxpoint) { + BlockVector3 minbpoint = BukkitAdapter.adapt(minpoint.toLocation(world)).toVector().toBlockPoint(); + BlockVector3 maxbpoint = BukkitAdapter.adapt(maxpoint.toLocation(world)).toVector().toBlockPoint(); regenerateRegion(world, minbpoint, maxbpoint); } @Override @SuppressWarnings("deprecation") - public void regenerateRegion(World world, Vector minpoint, Vector maxpoint) { + public void regenerateRegion(World world, BlockVector3 minpoint, BlockVector3 maxpoint) { BukkitWorld bw = new BukkitWorld(world); - EditSession es = new EditSession(bw, Integer.MAX_VALUE); + EditSession es = new EditSessionFactory().getEditSession(bw, Integer.MAX_VALUE); es.setFastMode(true); int maxy = bw.getMaxY() + 1; Region region = new CuboidRegion(bw, minpoint, maxpoint); @@ -65,14 +65,14 @@ public void regenerateRegion(World world, Vector minpoint, Vector maxpoint) { BukkitUtils.registerListener(itemremover); // first save all blocks that are inside affected chunks but outside the region - for (Vector2D chunk : region.getChunks()) { - Vector min = new Vector(chunk.getBlockX() * 16, 0, chunk.getBlockZ() * 16); + for (BlockVector2 chunk : region.getChunks()) { + BlockVector3 min = BlockVector3.at(chunk.getBlockX() * 16, 0, chunk.getBlockZ() * 16); for (int x = 0; x < 16; ++x) { for (int y = 0; y < maxy; ++y) { for (int z = 0; z < 16; ++z) { - Vector pt = min.add(x, y, z); + BlockVector3 pt = min.add(x, y, z); if (!region.contains(pt)) { - placeBackQueue.add(new BlockToPlaceBack(pt, es.getBlock(pt))); + placeBackQueue.add(new BlockToPlaceBack(pt, es.getBlock(pt).toBaseBlock())); } } } @@ -82,7 +82,7 @@ public void regenerateRegion(World world, Vector minpoint, Vector maxpoint) { //TODO: Set blocks that has tileentity to air first // regenerate all affected chunks - for (Vector2D chunk : region.getChunks()) { + for (BlockVector2 chunk : region.getChunks()) { try { world.regenerateChunk(chunk.getBlockX(), chunk.getBlockZ()); } catch (Exception t) { @@ -91,73 +91,26 @@ public void regenerateRegion(World world, Vector minpoint, Vector maxpoint) { } // set all blocks that were outside the region back - for (PlaceBackStage stage : placeBackStages) { - stage.processBlockPlaceBack(world, es, placeBackQueue); - } - - // unregister listener that prevents item drop - BukkitUtils.unregisterListener(itemremover); - } - - private static PlaceBackStage[] placeBackStages = new PlaceBackStage[] { - // normal stage place back - new PlaceBackStage(new PlaceBackStage.PlaceBackCheck() { - @Override - public boolean shouldPlaceBack(BaseBlock block) { - return !BlockType.shouldPlaceLast(block.getId()) && !BlockType.shouldPlaceFinal(block.getId()); - } - }), - // last stage place back - new PlaceBackStage(new PlaceBackStage.PlaceBackCheck() { - @Override - public boolean shouldPlaceBack(BaseBlock block) { - return BlockType.shouldPlaceLast(block.getId()); - } - }), - // final stage place back - new PlaceBackStage(new PlaceBackStage.PlaceBackCheck() { - @Override - public boolean shouldPlaceBack(BaseBlock block) { - return BlockType.shouldPlaceFinal(block.getId()); - } - }) - }; - - private static class PlaceBackStage { - - public static interface PlaceBackCheck { - public boolean shouldPlaceBack(BaseBlock block); - } - - private PlaceBackCheck check; - - public PlaceBackStage(PlaceBackCheck check) { - this.check = check; - } - - public void processBlockPlaceBack(World world, EditSession es, LinkedList placeBackQueue) { - Iterator entryit = placeBackQueue.iterator(); - while (entryit.hasNext()) { - BlockToPlaceBack blockToPlaceBack = entryit.next(); - BaseBlock block = blockToPlaceBack.getBlock(); - if (check.shouldPlaceBack(block)) { - Vector pt = blockToPlaceBack.getPosition(); - try { - // set block to air to fix one really weird problem - world.getBlockAt(pt.getBlockX(), pt.getBlockY(), pt.getBlockZ()).setType(Material.AIR); - // set block back if it is not air - if (!block.isAir()) { - es.rawSetBlock(pt, block); - } - } catch (Exception t) { - MessageLogger.exception("Unable to place back block " + pt.getBlockX() + " " + pt.getBlockY() + " " + pt.getBlockZ(), t); - } finally { - entryit.remove(); - } + Iterator entryit = placeBackQueue.iterator(); + while (entryit.hasNext()) { + BlockToPlaceBack blockToPlaceBack = entryit.next(); + BaseBlock block = blockToPlaceBack.getBlock(); + BlockVector3 pt = blockToPlaceBack.getPosition(); + try { + // set block to air to fix one really weird problem + world.getBlockAt(pt.getBlockX(), pt.getBlockY(), pt.getBlockZ()).setType(Material.AIR); + // set block back if it is not air + if (!block.getBlockType().getMaterial().isAir()) { + es.rawSetBlock(pt, block); } + } catch (Exception t) { + MessageLogger.exception("Unable to place back block " + pt.getBlockX() + " " + pt.getBlockY() + " " + pt.getBlockZ(), t); + } finally { + entryit.remove(); } } + // unregister listener that prevents item drop + BukkitUtils.unregisterListener(itemremover); } - } diff --git a/src/autosaveworld/features/purge/weregen/UtilClasses.java b/src/main/java/autosaveworld/features/purge/weregen/UtilClasses.java similarity index 84% rename from src/autosaveworld/features/purge/weregen/UtilClasses.java rename to src/main/java/autosaveworld/features/purge/weregen/UtilClasses.java index 8013cc2e..5d663452 100644 --- a/src/autosaveworld/features/purge/weregen/UtilClasses.java +++ b/src/main/java/autosaveworld/features/purge/weregen/UtilClasses.java @@ -21,23 +21,23 @@ import org.bukkit.event.Listener; import org.bukkit.event.entity.ItemSpawnEvent; -import com.sk89q.worldedit.Vector; -import com.sk89q.worldedit.blocks.BaseBlock; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldedit.world.block.BaseBlock; public class UtilClasses { public static class BlockToPlaceBack { - private Vector position; + private BlockVector3 position; private BaseBlock block; - public BlockToPlaceBack(Vector position, BaseBlock block) { + public BlockToPlaceBack(BlockVector3 position, BaseBlock block) { this.position = position; this.block = block; } - public Vector getPosition() { + public BlockVector3 getPosition() { return position; } diff --git a/src/autosaveworld/features/purge/weregen/WorldEditRegeneration.java b/src/main/java/autosaveworld/features/purge/weregen/WorldEditRegeneration.java similarity index 90% rename from src/autosaveworld/features/purge/weregen/WorldEditRegeneration.java rename to src/main/java/autosaveworld/features/purge/weregen/WorldEditRegeneration.java index 2fccb640..6b93a3ab 100644 --- a/src/autosaveworld/features/purge/weregen/WorldEditRegeneration.java +++ b/src/main/java/autosaveworld/features/purge/weregen/WorldEditRegeneration.java @@ -19,7 +19,7 @@ import org.bukkit.World; -import com.sk89q.worldedit.Vector; +import com.sk89q.worldedit.math.BlockVector3; //TODO: write my own regen that pastes blocks directly to ChunkSections public class WorldEditRegeneration { @@ -36,7 +36,7 @@ public static WorldEditRegenrationInterface get() { public static interface WorldEditRegenrationInterface { public void regenerateRegion(World world, org.bukkit.util.Vector minpoint, org.bukkit.util.Vector maxpoint); - public void regenerateRegion(World world, Vector minpoint, Vector maxpoint); + public void regenerateRegion(World world, BlockVector3 minpoint, BlockVector3 maxpoint); } } diff --git a/src/autosaveworld/features/restart/AutoRestartThread.java b/src/main/java/autosaveworld/features/restart/AutoRestartThread.java similarity index 100% rename from src/autosaveworld/features/restart/AutoRestartThread.java rename to src/main/java/autosaveworld/features/restart/AutoRestartThread.java diff --git a/src/autosaveworld/features/restart/CrashRestartThread.java b/src/main/java/autosaveworld/features/restart/CrashRestartThread.java similarity index 100% rename from src/autosaveworld/features/restart/CrashRestartThread.java rename to src/main/java/autosaveworld/features/restart/CrashRestartThread.java diff --git a/src/autosaveworld/features/restart/RestartScript.java b/src/main/java/autosaveworld/features/restart/RestartScript.java similarity index 100% rename from src/autosaveworld/features/restart/RestartScript.java rename to src/main/java/autosaveworld/features/restart/RestartScript.java diff --git a/src/autosaveworld/features/restart/RestartShutdownHook.java b/src/main/java/autosaveworld/features/restart/RestartShutdownHook.java similarity index 100% rename from src/autosaveworld/features/restart/RestartShutdownHook.java rename to src/main/java/autosaveworld/features/restart/RestartShutdownHook.java diff --git a/src/autosaveworld/features/restart/RestartWaiter.java b/src/main/java/autosaveworld/features/restart/RestartWaiter.java similarity index 100% rename from src/autosaveworld/features/restart/RestartWaiter.java rename to src/main/java/autosaveworld/features/restart/RestartWaiter.java diff --git a/src/autosaveworld/features/save/AutoSaveThread.java b/src/main/java/autosaveworld/features/save/AutoSaveThread.java similarity index 97% rename from src/autosaveworld/features/save/AutoSaveThread.java rename to src/main/java/autosaveworld/features/save/AutoSaveThread.java index c67b1105..edc3d6f0 100644 --- a/src/autosaveworld/features/save/AutoSaveThread.java +++ b/src/main/java/autosaveworld/features/save/AutoSaveThread.java @@ -133,8 +133,9 @@ private void dumpRegionCache(World world) { Object worldserver = getNMSWorld(world); // invoke saveLevel method which waits for all chunks to save and than dumps RegionFileCache ReflectionUtils.getMethod(worldserver.getClass(), NMSNames.getSaveLevelMethodName(), 0).invoke(worldserver); - } catch (Exception e) { - MessageLogger.exception("Could not dump RegionFileCache", e); + } catch (Exception ignored) { + // after 1.13, this saveLevel method is removed. + // MessageLogger.exception("Could not dump RegionFileCache", e); } } } diff --git a/src/autosaveworld/features/save/NMSNames.java b/src/main/java/autosaveworld/features/save/NMSNames.java similarity index 100% rename from src/autosaveworld/features/save/NMSNames.java rename to src/main/java/autosaveworld/features/save/NMSNames.java diff --git a/src/autosaveworld/features/worldregen/AntiJoinListener.java b/src/main/java/autosaveworld/features/worldregen/AntiJoinListener.java similarity index 100% rename from src/autosaveworld/features/worldregen/AntiJoinListener.java rename to src/main/java/autosaveworld/features/worldregen/AntiJoinListener.java diff --git a/src/autosaveworld/features/worldregen/WorldRegenJVMshutdownhook.java b/src/main/java/autosaveworld/features/worldregen/WorldRegenJVMshutdownhook.java similarity index 100% rename from src/autosaveworld/features/worldregen/WorldRegenJVMshutdownhook.java rename to src/main/java/autosaveworld/features/worldregen/WorldRegenJVMshutdownhook.java diff --git a/src/autosaveworld/features/worldregen/WorldRegenTask.java b/src/main/java/autosaveworld/features/worldregen/WorldRegenTask.java similarity index 100% rename from src/autosaveworld/features/worldregen/WorldRegenTask.java rename to src/main/java/autosaveworld/features/worldregen/WorldRegenTask.java diff --git a/src/autosaveworld/features/worldregen/WorldRegenThread.java b/src/main/java/autosaveworld/features/worldregen/WorldRegenThread.java similarity index 100% rename from src/autosaveworld/features/worldregen/WorldRegenThread.java rename to src/main/java/autosaveworld/features/worldregen/WorldRegenThread.java diff --git a/src/autosaveworld/features/worldregen/plugins/DataProvider.java b/src/main/java/autosaveworld/features/worldregen/plugins/DataProvider.java similarity index 100% rename from src/autosaveworld/features/worldregen/plugins/DataProvider.java rename to src/main/java/autosaveworld/features/worldregen/plugins/DataProvider.java diff --git a/src/autosaveworld/features/worldregen/plugins/FactionsDataProvider.java b/src/main/java/autosaveworld/features/worldregen/plugins/FactionsDataProvider.java similarity index 100% rename from src/autosaveworld/features/worldregen/plugins/FactionsDataProvider.java rename to src/main/java/autosaveworld/features/worldregen/plugins/FactionsDataProvider.java diff --git a/src/autosaveworld/features/worldregen/plugins/GriefPreventionDataProvider.java b/src/main/java/autosaveworld/features/worldregen/plugins/GriefPreventionDataProvider.java similarity index 100% rename from src/autosaveworld/features/worldregen/plugins/GriefPreventionDataProvider.java rename to src/main/java/autosaveworld/features/worldregen/plugins/GriefPreventionDataProvider.java diff --git a/src/autosaveworld/features/worldregen/plugins/PStonesDataProvider.java b/src/main/java/autosaveworld/features/worldregen/plugins/PStonesDataProvider.java similarity index 95% rename from src/autosaveworld/features/worldregen/plugins/PStonesDataProvider.java rename to src/main/java/autosaveworld/features/worldregen/plugins/PStonesDataProvider.java index 7f25ddcf..1753f66a 100644 --- a/src/autosaveworld/features/worldregen/plugins/PStonesDataProvider.java +++ b/src/main/java/autosaveworld/features/worldregen/plugins/PStonesDataProvider.java @@ -20,7 +20,7 @@ import org.bukkit.World; import net.sacredlabyrinth.Phaed.PreciousStones.PreciousStones; -import net.sacredlabyrinth.Phaed.PreciousStones.vectors.Field; +import net.sacredlabyrinth.Phaed.PreciousStones.field.Field; public class PStonesDataProvider extends DataProvider { diff --git a/src/autosaveworld/features/worldregen/plugins/TownyDataProvider.java b/src/main/java/autosaveworld/features/worldregen/plugins/TownyDataProvider.java similarity index 89% rename from src/autosaveworld/features/worldregen/plugins/TownyDataProvider.java rename to src/main/java/autosaveworld/features/worldregen/plugins/TownyDataProvider.java index 0f5fec4c..15c6ea88 100644 --- a/src/autosaveworld/features/worldregen/plugins/TownyDataProvider.java +++ b/src/main/java/autosaveworld/features/worldregen/plugins/TownyDataProvider.java @@ -19,10 +19,10 @@ import org.bukkit.World; +import com.palmergames.bukkit.towny.TownyAPI; import com.palmergames.bukkit.towny.exceptions.NotRegisteredException; import com.palmergames.bukkit.towny.object.Town; import com.palmergames.bukkit.towny.object.TownBlock; -import com.palmergames.bukkit.towny.object.TownyUniverse; public class TownyDataProvider extends DataProvider { @@ -32,7 +32,7 @@ public TownyDataProvider(World world) throws Throwable { @Override protected void init() throws NotRegisteredException { - for (Town town : TownyUniverse.getDataSource().getWorld(world.getName()).getTowns()) { + for (Town town : TownyAPI.getInstance().getDataSource().getWorld(world.getName()).getTowns().values()) { for (TownBlock tb : town.getTownBlocks()) { if (tb.getWorld().getName().equalsIgnoreCase(world.getName())) { addChunkAtCoord(tb.getX(), tb.getZ()); diff --git a/src/autosaveworld/features/worldregen/plugins/WorldGuardDataProvider.java b/src/main/java/autosaveworld/features/worldregen/plugins/WorldGuardDataProvider.java similarity index 100% rename from src/autosaveworld/features/worldregen/plugins/WorldGuardDataProvider.java rename to src/main/java/autosaveworld/features/worldregen/plugins/WorldGuardDataProvider.java diff --git a/src/autosaveworld/features/worldregen/storage/AnvilRegion.java b/src/main/java/autosaveworld/features/worldregen/storage/AnvilRegion.java similarity index 100% rename from src/autosaveworld/features/worldregen/storage/AnvilRegion.java rename to src/main/java/autosaveworld/features/worldregen/storage/AnvilRegion.java diff --git a/src/autosaveworld/features/worldregen/storage/Coord.java b/src/main/java/autosaveworld/features/worldregen/storage/Coord.java similarity index 100% rename from src/autosaveworld/features/worldregen/storage/Coord.java rename to src/main/java/autosaveworld/features/worldregen/storage/Coord.java diff --git a/src/autosaveworld/features/worldregen/storage/WorldMap.java b/src/main/java/autosaveworld/features/worldregen/storage/WorldMap.java similarity index 100% rename from src/autosaveworld/features/worldregen/storage/WorldMap.java rename to src/main/java/autosaveworld/features/worldregen/storage/WorldMap.java diff --git a/src/autosaveworld/utils/BukkitUtils.java b/src/main/java/autosaveworld/utils/BukkitUtils.java similarity index 100% rename from src/autosaveworld/utils/BukkitUtils.java rename to src/main/java/autosaveworld/utils/BukkitUtils.java diff --git a/src/autosaveworld/utils/CollectionsUtils.java b/src/main/java/autosaveworld/utils/CollectionsUtils.java similarity index 100% rename from src/autosaveworld/utils/CollectionsUtils.java rename to src/main/java/autosaveworld/utils/CollectionsUtils.java diff --git a/src/autosaveworld/utils/FileUtils.java b/src/main/java/autosaveworld/utils/FileUtils.java similarity index 100% rename from src/autosaveworld/utils/FileUtils.java rename to src/main/java/autosaveworld/utils/FileUtils.java diff --git a/src/autosaveworld/utils/ReflectionUtils.java b/src/main/java/autosaveworld/utils/ReflectionUtils.java similarity index 100% rename from src/autosaveworld/utils/ReflectionUtils.java rename to src/main/java/autosaveworld/utils/ReflectionUtils.java diff --git a/src/autosaveworld/utils/SchedulerUtils.java b/src/main/java/autosaveworld/utils/SchedulerUtils.java similarity index 100% rename from src/autosaveworld/utils/SchedulerUtils.java rename to src/main/java/autosaveworld/utils/SchedulerUtils.java diff --git a/src/autosaveworld/utils/StringUtils.java b/src/main/java/autosaveworld/utils/StringUtils.java similarity index 100% rename from src/autosaveworld/utils/StringUtils.java rename to src/main/java/autosaveworld/utils/StringUtils.java diff --git a/src/autosaveworld/utils/Threads.java b/src/main/java/autosaveworld/utils/Threads.java similarity index 100% rename from src/autosaveworld/utils/Threads.java rename to src/main/java/autosaveworld/utils/Threads.java diff --git a/src/plugin.yml b/src/main/resources/plugin.yml similarity index 81% rename from src/plugin.yml rename to src/main/resources/plugin.yml index ec11037b..3d5041e7 100644 --- a/src/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,22 +1,22 @@ -name: AutoSaveWorld -main: autosaveworld.core.AutoSaveWorld -version: 4.15 -author: _Shevchik_ -load: STARTUP -commands: - autosaveworld: - description: All AutoSaveWorld commands - aliases: asw - usage: Use /asw help to show all commands available in plugin - autosave: - description: AutoSaveWorld /asw save command - aliases: save - usage: Use /save to run AutoSave - autobackup: - description: AutoSaveWorld /asw backup command - aliases: backup - usage: Use /backup to run AutoBackup - autopurge: - description: AutoSaveWorld /asw purge command - aliases: purge +name: AutoSaveWorld +main: autosaveworld.core.AutoSaveWorld +version: ${project.version} +author: _Shevchik_ +load: STARTUP +commands: + autosaveworld: + description: All AutoSaveWorld commands + aliases: ["asw"] + usage: Use /asw help to show all commands available in plugin + autosave: + description: AutoSaveWorld /asw save command + aliases: ["save"] + usage: Use /save to run AutoSave + autobackup: + description: AutoSaveWorld /asw backup command + aliases: ["backup"] + usage: Use /backup to run AutoBackup + autopurge: + description: AutoSaveWorld /asw purge command + aliases: ["purge"] usage: Use /purge to run AutoPurge \ No newline at end of file