Search in sources :

Example 1 with JsonDataException

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();
    }
}
Also used : JsonReader(com.squareup.moshi.JsonReader) JsonDataException(com.squareup.moshi.JsonDataException) BufferedSource(okio.BufferedSource)

Example 2 with JsonDataException

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);
}
Also used : JsonDataException(com.squareup.moshi.JsonDataException) HttpUrl(okhttp3.HttpUrl) Notification(me.proxer.library.entity.notifications.Notification) FromJson(com.squareup.moshi.FromJson)

Example 3 with JsonDataException

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);
    }
}
Also used : TimeZone(java.util.TimeZone) Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) GregorianCalendar(java.util.GregorianCalendar) JsonDataException(com.squareup.moshi.JsonDataException)

Example 4 with JsonDataException

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());
            }
        }
    });
}
Also used : Moshi(com.squareup.moshi.Moshi) HashSet(java.util.HashSet) Set(java.util.Set) ScriptBuilder(org.bitcoinj.script.ScriptBuilder) Sha256Hash(org.bitcoinj.core.Sha256Hash) BufferedSink(okio.BufferedSink) JsonAdapter(com.squareup.moshi.JsonAdapter) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) Coin(org.bitcoinj.core.Coin) Random(java.util.Random) LinkedList(java.util.LinkedList) List(java.util.List) BufferedSource(okio.BufferedSource) Script(org.bitcoinj.script.Script) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) SocketFactory(javax.net.SocketFactory) SSLSession(javax.net.ssl.SSLSession) IOException(java.io.IOException) UTXO(org.bitcoinj.core.UTXO) JsonDataException(com.squareup.moshi.JsonDataException) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 5 with JsonDataException

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);
    }
}
Also used : Matcher(java.util.regex.Matcher) JsonDataException(com.squareup.moshi.JsonDataException) ServerErrorType(me.proxer.library.api.ProxerException.ServerErrorType) HttpUrl(okhttp3.HttpUrl)

Aggregations

JsonDataException (com.squareup.moshi.JsonDataException)5 HttpUrl (okhttp3.HttpUrl)2 BufferedSource (okio.BufferedSource)2 FromJson (com.squareup.moshi.FromJson)1 JsonAdapter (com.squareup.moshi.JsonAdapter)1 JsonReader (com.squareup.moshi.JsonReader)1 Moshi (com.squareup.moshi.Moshi)1 IOException (java.io.IOException)1 Socket (java.net.Socket)1 Certificate (java.security.cert.Certificate)1 X509Certificate (java.security.cert.X509Certificate)1 Calendar (java.util.Calendar)1 GregorianCalendar (java.util.GregorianCalendar)1 HashSet (java.util.HashSet)1 LinkedList (java.util.LinkedList)1 List (java.util.List)1 Random (java.util.Random)1 Set (java.util.Set)1 TimeZone (java.util.TimeZone)1 Matcher (java.util.regex.Matcher)1