-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #108 from lewisheadden/IntOrStringSupport
Add IntOrString model and GSON adapter
- Loading branch information
Showing
1 changed file
with
69 additions
and
0 deletions.
There are no files selected for viewing
69 changes: 69 additions & 0 deletions
69
kubernetes/src/main/java/io/kubernetes/client/custom/IntOrString.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
package io.kubernetes.client.custom; | ||
|
||
import com.google.gson.TypeAdapter; | ||
import com.google.gson.annotations.JsonAdapter; | ||
import com.google.gson.stream.JsonReader; | ||
import com.google.gson.stream.JsonToken; | ||
import com.google.gson.stream.JsonWriter; | ||
|
||
import java.io.IOException; | ||
|
||
@JsonAdapter(IntOrString.IntOrStringAdapter.class) | ||
public class IntOrString { | ||
private final boolean isInt; | ||
private final String strValue; | ||
private final Integer intValue; | ||
|
||
public IntOrString(final String value) { | ||
this.isInt = false; | ||
this.strValue = value; | ||
this.intValue = null; | ||
} | ||
|
||
public IntOrString(final int value) { | ||
this.isInt = true; | ||
this.intValue = value; | ||
this.strValue = null; | ||
} | ||
|
||
public boolean isInteger() { | ||
return isInt; | ||
} | ||
|
||
public String getStrValue() { | ||
if (isInt) { | ||
throw new IllegalStateException("Not a string"); | ||
} | ||
return strValue; | ||
} | ||
|
||
public Integer getIntValue() { | ||
if (!isInt) { | ||
throw new IllegalStateException("Not an integer"); | ||
} | ||
return intValue; | ||
} | ||
|
||
public static class IntOrStringAdapter extends TypeAdapter<IntOrString> { | ||
@Override | ||
public void write(JsonWriter jsonWriter, IntOrString intOrString) throws IOException { | ||
if (intOrString.isInteger()) { | ||
jsonWriter.value(intOrString.getIntValue()); | ||
} else { | ||
jsonWriter.value(intOrString.getStrValue()); | ||
} | ||
} | ||
|
||
@Override | ||
public IntOrString read(JsonReader jsonReader) throws IOException { | ||
final JsonToken nextToken = jsonReader.peek(); | ||
if (nextToken == JsonToken.NUMBER) { | ||
return new IntOrString(jsonReader.nextInt()); | ||
} else if (nextToken == JsonToken.STRING) { | ||
return new IntOrString(jsonReader.nextString()); | ||
} else { | ||
throw new IllegalStateException("Could not deserialize to IntOrString. Was " + nextToken); | ||
} | ||
} | ||
} | ||
} |