Search in sources :

Example 1 with APIException

use of im.tny.segvault.disturbances.exception.APIException in project underlx by underlx.

the class PairManager method pair.

public void pair() {
    if (isPaired()) {
        return;
    }
    API.PairRequest request = new API.PairRequest();
    request.nonce = UUID.randomUUID().toString();
    request.timestamp = Util.encodeRFC3339(new Date());
    request.androidID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    String toSign = request.nonce + request.timestamp + request.androidID;
    byte[] sigBytes;
    try {
        Signature signer = Signature.getInstance("SHA256withECDSA");
        signer.initSign(Ospylac.getPrivateKey(context, "trusted.der"));
        byte[] strByte = toSign.getBytes("UTF-8");
        signer.update(strByte);
        sigBytes = signer.sign();
    } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException | SignatureException e) {
        e.printStackTrace();
        return;
    }
    if (sigBytes == null) {
        return;
    }
    byte[] asn1sigBytes = new BigInteger(1, sigBytes).toByteArray();
    request.signature = Base64.encodeToString(asn1sigBytes, Base64.NO_WRAP);
    try {
        API.Pair response = API.getInstance().postPairRequest(request);
        SharedPreferences.Editor editor = sharedPref.edit();
        Log.d("PM API KEY", response.key);
        Log.d("PM API SEC", response.secret);
        Log.d("PM API ACT", String.valueOf(response.activation[0]));
        editor.putString(PREF_API_KEY, response.key);
        editor.putString(PREF_API_SECRET, response.secret);
        editor.putLong(PREF_API_ACTIVATION, response.activation[0] * 1000);
        editor.commit();
    } catch (APIException e) {
        e.printStackTrace();
    }
}
Also used : SharedPreferences(android.content.SharedPreferences) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) InvalidKeyException(java.security.InvalidKeyException) Date(java.util.Date) APIException(im.tny.segvault.disturbances.exception.APIException) Signature(java.security.Signature) BigInteger(java.math.BigInteger)

Example 2 with APIException

use of im.tny.segvault.disturbances.exception.APIException in project underlx by underlx.

the class Synchronizer method sync.

private void sync() {
    Log.d("sync", "Waiting for lock");
    synchronized (lock) {
        Log.d("sync", "Lock acquired");
        if (!Connectivity.isConnected(context)) {
            Log.d("sync", "Not connected, abort");
            return;
        }
        if (lastSync != null && new Date().getTime() - lastSync.getTime() < TimeUnit.SECONDS.toMillis(2)) {
            Log.d("sync", "Last sync was right now, abort");
            // avoid looping on ACTION_TRIP_REALM_UPDATED broadcasts
            return;
        }
        Realm realm = Application.getDefaultRealmInstance(context);
        realm.executeTransaction(new Realm.Transaction() {

            @Override
            public void execute(Realm realm) {
                RealmResults<Trip> unsyncedTrips = realm.where(Trip.class).equalTo("synced", false).findAll();
                for (Trip t : unsyncedTrips) {
                    API.TripRequest request = tripToAPIRequest(t);
                    try {
                        if (t.isSubmitted()) {
                            // submit update, if possible
                            if (t.canBeCorrected()) {
                                API.getInstance().putTrip(request);
                                t.setSynced(true);
                                t.setSubmitted(true);
                            }
                        } else {
                            // submit new
                            API.getInstance().postTrip(request);
                            t.setSynced(true);
                            t.setSubmitted(true);
                        }
                    } catch (APIException e) {
                        t.registerSyncFailure();
                        if (t.isFailedToSync()) {
                            // give up on this one
                            t.setSynced(true);
                        }
                    }
                }
                RealmResults<im.tny.segvault.disturbances.model.Feedback> unsyncedFeedback = realm.where(im.tny.segvault.disturbances.model.Feedback.class).equalTo("synced", false).findAll();
                for (im.tny.segvault.disturbances.model.Feedback f : unsyncedFeedback) {
                    API.Feedback request = feedbackToAPIRequest(f);
                    try {
                        API.getInstance().postFeedback(request);
                        f.setSynced(true);
                    } catch (APIException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        realm.close();
        lastSync = new Date();
        Log.d("sync", "Sync done");
    }
}
Also used : Trip(im.tny.segvault.disturbances.model.Trip) Date(java.util.Date) APIException(im.tny.segvault.disturbances.exception.APIException) Realm(io.realm.Realm) RealmResults(io.realm.RealmResults)

Example 3 with APIException

use of im.tny.segvault.disturbances.exception.APIException in project underlx by underlx.

the class API method doInputRequest.

private InputStream doInputRequest(URI uri, byte[] content, boolean authenticate, String method) throws APIException {
    try {
        HttpURLConnection h = (HttpURLConnection) uri.toURL().openConnection();
        h.setConnectTimeout(timeoutMs);
        h.setReadTimeout(timeoutMs);
        h.setRequestProperty("Accept", "application/msgpack");
        h.setRequestProperty("Accept-Encoding", "gzip");
        h.setRequestProperty("Content-Type", "application/msgpack");
        if (authenticate && pairManager != null) {
            String toEncode = pairManager.getPairKey() + ":" + pairManager.getPairSecret();
            h.setRequestProperty("Authorization", "Basic " + Base64.encodeToString(toEncode.getBytes("UTF-8"), Base64.NO_WRAP));
        }
        h.setRequestMethod(method);
        h.setDoInput(true);
        h.setDoOutput(true);
        h.setFixedLengthStreamingMode(content.length);
        OutputStream out = new BufferedOutputStream(h.getOutputStream());
        out.write(content);
        out.close();
        InputStream is;
        int code;
        try {
            // Will throw IOException if server responds with 401.
            code = h.getResponseCode();
        } catch (IOException e) {
            // Will return 401, because now connection has the correct internal state.
            code = h.getResponseCode();
        }
        if (code < HttpURLConnection.HTTP_BAD_REQUEST) {
            is = h.getInputStream();
        } else {
            is = h.getErrorStream();
        }
        if ("gzip".equals(h.getContentEncoding())) {
            return new GZIPInputStream(is);
        }
        return is;
    } catch (MalformedURLException e) {
        throw new APIException(e).addInfo("Malformed URL on " + method + " request");
    } catch (IOException e) {
        throw new APIException(e).addInfo("IOException on " + method + " request");
    }
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) MalformedURLException(java.net.MalformedURLException) HttpURLConnection(java.net.HttpURLConnection) APIException(im.tny.segvault.disturbances.exception.APIException) GZIPInputStream(java.util.zip.GZIPInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) BufferedOutputStream(java.io.BufferedOutputStream) IOException(java.io.IOException) BufferedOutputStream(java.io.BufferedOutputStream)

Example 4 with APIException

use of im.tny.segvault.disturbances.exception.APIException in project underlx by underlx.

the class API method getRequest.

private InputStream getRequest(URI uri, boolean authenticate) throws APIException {
    try {
        HttpURLConnection h = (HttpURLConnection) uri.toURL().openConnection();
        h.setConnectTimeout(timeoutMs);
        h.setReadTimeout(timeoutMs);
        h.setRequestProperty("Accept", "application/msgpack");
        h.setRequestProperty("Accept-Encoding", "gzip");
        if (authenticate && pairManager != null) {
            String toEncode = pairManager.getPairKey() + ":" + pairManager.getPairSecret();
            h.setRequestProperty("Authorization", "Basic " + Base64.encodeToString(toEncode.getBytes("UTF-8"), Base64.NO_WRAP));
        }
        h.setRequestMethod("GET");
        h.setDoInput(true);
        InputStream is;
        int code;
        try {
            // Will throw IOException if server responds with 401.
            code = h.getResponseCode();
        } catch (IOException e) {
            // Will return 401, because now connection has the correct internal state.
            code = h.getResponseCode();
        }
        if (code < HttpURLConnection.HTTP_BAD_REQUEST) {
            is = h.getInputStream();
        } else {
            is = h.getErrorStream();
        }
        if ("gzip".equals(h.getContentEncoding())) {
            return new GZIPInputStream(is);
        }
        return is;
    } catch (MalformedURLException e) {
        throw new APIException(e).addInfo("Malformed URL on GET request");
    } catch (IOException e) {
        throw new APIException(e).addInfo("IOException on GET request");
    }
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) MalformedURLException(java.net.MalformedURLException) HttpURLConnection(java.net.HttpURLConnection) APIException(im.tny.segvault.disturbances.exception.APIException) GZIPInputStream(java.util.zip.GZIPInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException)

Example 5 with APIException

use of im.tny.segvault.disturbances.exception.APIException in project underlx by underlx.

the class API method postPairRequest.

public Pair postPairRequest(PairRequest request) throws APIException {
    try {
        byte[] content = mapper.writeValueAsBytes(request);
        InputStream is = postRequest(endpoint.resolve("pair"), content, false);
        return mapper.readValue(is, Pair.class);
    } catch (JsonParseException e) {
        throw new APIException(e).addInfo("Parse exception");
    } catch (JsonMappingException e) {
        throw new APIException(e).addInfo("Mapping exception");
    } catch (IOException e) {
        throw new APIException(e).addInfo("IOException");
    }
}
Also used : APIException(im.tny.segvault.disturbances.exception.APIException) GZIPInputStream(java.util.zip.GZIPInputStream) InputStream(java.io.InputStream) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException) IOException(java.io.IOException) JsonParseException(com.fasterxml.jackson.core.JsonParseException)

Aggregations

APIException (im.tny.segvault.disturbances.exception.APIException)10 IOException (java.io.IOException)7 InputStream (java.io.InputStream)7 GZIPInputStream (java.util.zip.GZIPInputStream)7 JsonParseException (com.fasterxml.jackson.core.JsonParseException)5 JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)5 HttpURLConnection (java.net.HttpURLConnection)2 MalformedURLException (java.net.MalformedURLException)2 Date (java.util.Date)2 SharedPreferences (android.content.SharedPreferences)1 SpannableString (android.text.SpannableString)1 Trip (im.tny.segvault.disturbances.model.Trip)1 InNetworkState (im.tny.segvault.s2ls.InNetworkState)1 S2LS (im.tny.segvault.s2ls.S2LS)1 Connection (im.tny.segvault.subway.Connection)1 Network (im.tny.segvault.subway.Network)1 Stop (im.tny.segvault.subway.Stop)1 Realm (io.realm.Realm)1 RealmResults (io.realm.RealmResults)1 BufferedOutputStream (java.io.BufferedOutputStream)1