use of com.squareup.moshi.JsonDataException in project retrofit by square.
the class MoshiResponseBodyConverter method convert.
@Override
public T convert(ResponseBody value) throws IOException {
BufferedSource source = value.source();
try {
// is delegating to it. Since it's a UTF-8-only library as well we only honor the UTF-8 BOM.
if (source.rangeEquals(0, UTF8_BOM)) {
source.skip(UTF8_BOM.size());
}
JsonReader reader = JsonReader.of(source);
T result = adapter.fromJson(reader);
if (reader.peek() != JsonReader.Token.END_DOCUMENT) {
throw new JsonDataException("JSON document was not fully consumed.");
}
return result;
} finally {
value.close();
}
}
use of com.squareup.moshi.JsonDataException in project ProxerLibJava by proxer.
the class NotificationAdapter method fromJson.
@FromJson
Notification fromJson(final IntermediateNotification json) {
final String base = ProxerUrls.webBase().toString();
final HttpUrl properContentLink = HttpUrl.parse(base.substring(0, base.length() - 1) + json.contentLink);
if (properContentLink == null) {
throw new JsonDataException("Invalid link: " + json.contentLink);
}
return new Notification(json.id, json.type, json.contentId, properContentLink, json.text, json.date, json.additionalDescription);
}
use of com.squareup.moshi.JsonDataException in project moshi by square.
the class Iso8601Utils method parse.
/**
* Parse a date from ISO-8601 formatted string. It expects a format
* [yyyy-MM-dd|yyyyMMdd][T(hh:mm[:ss[.sss]]|hhmm[ss[.sss]])]?[Z|[+-]hh:mm]]
*
* @param date ISO string to parse in the appropriate format.
* @return the parsed date
*/
public static Date parse(String date) {
try {
int offset = 0;
// extract year
int year = parseInt(date, offset, offset += 4);
if (checkOffset(date, offset, '-')) {
offset += 1;
}
// extract month
int month = parseInt(date, offset, offset += 2);
if (checkOffset(date, offset, '-')) {
offset += 1;
}
// extract day
int day = parseInt(date, offset, offset += 2);
// default time value
int hour = 0;
int minutes = 0;
int seconds = 0;
int milliseconds = // always use 0 otherwise returned date will include millis of current time
0;
// if the value has no time component (and no time zone), we are done
boolean hasT = checkOffset(date, offset, 'T');
if (!hasT && (date.length() <= offset)) {
Calendar calendar = new GregorianCalendar(year, month - 1, day);
return calendar.getTime();
}
if (hasT) {
// extract hours, minutes, seconds and milliseconds
hour = parseInt(date, offset += 1, offset += 2);
if (checkOffset(date, offset, ':')) {
offset += 1;
}
minutes = parseInt(date, offset, offset += 2);
if (checkOffset(date, offset, ':')) {
offset += 1;
}
// second and milliseconds can be optional
if (date.length() > offset) {
char c = date.charAt(offset);
if (c != 'Z' && c != '+' && c != '-') {
seconds = parseInt(date, offset, offset += 2);
// truncate up to 3 leap seconds
if (seconds > 59 && seconds < 63)
seconds = 59;
// milliseconds can be optional in the format
if (checkOffset(date, offset, '.')) {
offset += 1;
// assume at least one digit
int endOffset = indexOfNonDigit(date, offset + 1);
// parse up to 3 digits
int parseEndOffset = Math.min(endOffset, offset + 3);
int fraction = parseInt(date, offset, parseEndOffset);
milliseconds = (int) (Math.pow(10, 3 - (parseEndOffset - offset)) * fraction);
offset = endOffset;
}
}
}
}
// extract timezone
if (date.length() <= offset) {
throw new IllegalArgumentException("No time zone indicator");
}
TimeZone timezone;
char timezoneIndicator = date.charAt(offset);
if (timezoneIndicator == 'Z') {
timezone = TIMEZONE_Z;
} else if (timezoneIndicator == '+' || timezoneIndicator == '-') {
String timezoneOffset = date.substring(offset);
// 18-Jun-2015, tatu: Minor simplification, skip offset of "+0000"/"+00:00"
if ("+0000".equals(timezoneOffset) || "+00:00".equals(timezoneOffset)) {
timezone = TIMEZONE_Z;
} else {
// 18-Jun-2015, tatu: Looks like offsets only work from GMT, not UTC...
// not sure why, but it is what it is.
String timezoneId = GMT_ID + timezoneOffset;
timezone = TimeZone.getTimeZone(timezoneId);
String act = timezone.getID();
if (!act.equals(timezoneId)) {
/* 22-Jan-2015, tatu: Looks like canonical version has colons, but we may be given
* one without. If so, don't sweat.
* Yes, very inefficient. Hopefully not hit often.
* If it becomes a perf problem, add 'loose' comparison instead.
*/
String cleaned = act.replace(":", "");
if (!cleaned.equals(timezoneId)) {
throw new IndexOutOfBoundsException("Mismatching time zone indicator: " + timezoneId + " given, resolves to " + timezone.getID());
}
}
}
} else {
throw new IndexOutOfBoundsException("Invalid time zone indicator '" + timezoneIndicator + "'");
}
Calendar calendar = new GregorianCalendar(timezone);
calendar.setLenient(false);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);
calendar.set(Calendar.DAY_OF_MONTH, day);
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minutes);
calendar.set(Calendar.SECOND, seconds);
calendar.set(Calendar.MILLISECOND, milliseconds);
return calendar.getTime();
// If we get a ParseException it'll already have the right message/offset.
// Other exception types can convert here.
} catch (IndexOutOfBoundsException | IllegalArgumentException e) {
throw new JsonDataException("Not an RFC 3339 date: " + date, e);
}
}
use of com.squareup.moshi.JsonDataException in project bitcoin-wallet by bitcoin-wallet.
the class RequestWalletBalanceTask method requestWalletBalance.
public void requestWalletBalance(final AssetManager assets, final Address address) {
backgroundHandler.post(new Runnable() {
@Override
public void run() {
org.bitcoinj.core.Context.propagate(Constants.CONTEXT);
try {
final List<ElectrumServer> servers = loadElectrumServers(assets.open(Constants.Files.ELECTRUM_SERVERS_FILENAME));
final ElectrumServer server = servers.get(new Random().nextInt(servers.size()));
log.info("trying to request wallet balance from {}: {}", server.socketAddress, address);
final Socket socket;
if (server.type == ElectrumServer.Type.TLS) {
final SocketFactory sf = sslTrustAllCertificates();
socket = sf.createSocket(server.socketAddress.getHostName(), server.socketAddress.getPort());
final SSLSession sslSession = ((SSLSocket) socket).getSession();
final Certificate certificate = sslSession.getPeerCertificates()[0];
final String certificateFingerprint = sslCertificateFingerprint(certificate);
if (server.certificateFingerprint == null) {
// signed by CA
if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(server.socketAddress.getHostName(), sslSession))
throw new SSLHandshakeException("Expected " + server.socketAddress.getHostName() + ", got " + sslSession.getPeerPrincipal());
} else {
// self-signed
if (!certificateFingerprint.equals(server.certificateFingerprint))
throw new SSLHandshakeException("Expected " + server.certificateFingerprint + ", got " + certificateFingerprint);
}
} else if (server.type == ElectrumServer.Type.TCP) {
socket = new Socket();
socket.connect(server.socketAddress, 5000);
} else {
throw new IllegalStateException("Cannot handle: " + server.type);
}
final BufferedSink sink = Okio.buffer(Okio.sink(socket));
sink.timeout().timeout(5000, TimeUnit.MILLISECONDS);
final BufferedSource source = Okio.buffer(Okio.source(socket));
source.timeout().timeout(5000, TimeUnit.MILLISECONDS);
final Moshi moshi = new Moshi.Builder().build();
final JsonAdapter<JsonRpcRequest> requestAdapter = moshi.adapter(JsonRpcRequest.class);
final JsonRpcRequest request = new JsonRpcRequest("blockchain.address.listunspent", new String[] { address.toBase58() });
requestAdapter.toJson(sink, request);
sink.writeUtf8("\n").flush();
final JsonAdapter<JsonRpcResponse> responseAdapter = moshi.adapter(JsonRpcResponse.class);
final JsonRpcResponse response = responseAdapter.fromJson(source);
if (response.id == request.id) {
if (response.result == null)
throw new JsonDataException("empty response");
final Set<UTXO> utxos = new HashSet<>();
for (final JsonRpcResponse.Utxo responseUtxo : response.result) {
final Sha256Hash utxoHash = Sha256Hash.wrap(responseUtxo.tx_hash);
final int utxoIndex = responseUtxo.tx_pos;
final Coin utxoValue = Coin.valueOf(responseUtxo.value);
final Script script = ScriptBuilder.createOutputScript(address);
final UTXO utxo = new UTXO(utxoHash, utxoIndex, utxoValue, responseUtxo.height, false, script);
utxos.add(utxo);
}
log.info("fetched {} unspent outputs from {}", response.result.length, server.socketAddress);
onResult(utxos);
} else {
log.info("id mismatch response:{} vs request:{}", response.id, request.id);
onFail(R.string.error_parse, server.socketAddress.toString());
}
} catch (final JsonDataException x) {
log.info("problem parsing json", x);
onFail(R.string.error_parse, x.getMessage());
} catch (final IOException x) {
log.info("problem querying unspent outputs", x);
onFail(R.string.error_io, x.getMessage());
}
}
});
}
use of com.squareup.moshi.JsonDataException in project ProxerLibJava by proxer.
the class LoginTokenInterceptor method handleResponse.
private void handleResponse(final Response response) throws IOException {
final String responseBody = peekResponseBody(response);
final Matcher errorMatcher = ERROR_PATTERN.matcher(responseBody);
final HttpUrl url = response.request().url();
if (errorMatcher.find()) {
final int errorCode = Integer.parseInt(errorMatcher.group(1));
final ServerErrorType errorType = ServerErrorType.fromErrorCodeOrNull(errorCode);
if (errorType != null && isLoginError(errorType)) {
loginTokenManager.persist(null);
}
} else if (url.pathSegments().equals(LOGIN_PATH)) {
final Matcher loginTokenMatcher = LOGIN_TOKEN_PATTERN.matcher(responseBody);
if (loginTokenMatcher.find()) {
loginTokenManager.persist(loginTokenMatcher.group(1).trim());
} else {
throw new JsonDataException("No token found after successful login.");
}
} else if (url.pathSegments().equals(LOGOUT_PATH)) {
loginTokenManager.persist(null);
}
}
Aggregations