Search in sources :

Example 1 with AuthSessionHolder

use of com.vodafone360.people.datatypes.AuthSessionHolder in project 360-Engine-for-Android by 360.

the class LoginEngine method run.

/**
 * Do some work but anything that takes longer than 1 second must be broken
 * up. The type of work done includes:
 * <ul>
 * <li>If a comms response from server is outstanding, process it</li>
 * <li>If a timeout is pending, process it</li>
 * <li>If an SMS activation code has been received, process it</li>
 * <li>Retry auto login if necessary</li>
 * </ul>
 */
@Override
public void run() {
    LogUtils.logD("LoginEngine.run()");
    if (isCommsResponseOutstanding() && processCommsInQueue()) {
        return;
    }
    if (processTimeout()) {
        return;
    }
    switch(mState) {
        case NOT_INITIALISED:
            initializeEngine();
            return;
        case REQUESTING_ACTIVATION_CODE:
        case SIGNING_UP:
            if (mActivationCode != null) {
                handleSmsResponse();
                return;
            }
            break;
        case RETRIEVING_PUBLIC_KEY:
            break;
        case LOGGED_OFF:
        case LOGGED_OFF_WAITING_FOR_NETWORK:
            AuthSessionHolder session = StateTable.fetchSession(mDb.getReadableDatabase());
            // if session is null we try to login automatically again
            if (null == session) {
                if (retryAutoLogin()) {
                    return;
                }
            } else {
                // otherwise we try to reuse the session
                sActivatedSession = session;
                newState(State.LOGGED_ON);
            }
        default:
            // do nothing.
            break;
    }
    if (uiRequestReady() && processUiQueue()) {
        return;
    }
}
Also used : AuthSessionHolder(com.vodafone360.people.datatypes.AuthSessionHolder)

Example 2 with AuthSessionHolder

use of com.vodafone360.people.datatypes.AuthSessionHolder in project 360-Engine-for-Android by 360.

the class ConnectionTester method getConnectionTestHessianPayload.

/**
 * Returns a byte-array containing the data needed for sending a connection
 * test to the RPG.
 *
 * @throws IOException If there was an exception serializing the hash map to
 *             a hessian byte array.
 * @return A byte array representing the connection test request.
 */
private byte[] getConnectionTestHessianPayload() throws IOException {
    // hash table for parameters to Hessian encode
    final Hashtable<String, Object> ht = new Hashtable<String, Object>();
    final AuthSessionHolder auth = LoginEngine.getSession();
    ht.put("userid", auth.userID);
    // do Hessian encoding
    final byte[] payload = HessianEncoder.createHessianByteArray("", ht);
    payload[1] = (byte) 1;
    payload[2] = (byte) 0;
    final int reqLength = RpgHeader.HEADER_LENGTH + payload.length;
    final RpgHeader rpgHeader = new RpgHeader();
    rpgHeader.setPayloadLength(payload.length);
    rpgHeader.setReqType(RpgMessageTypes.RPG_TCP_CONNECTION_TEST);
    final byte[] rpgMsg = new byte[reqLength];
    System.arraycopy(rpgHeader.createHeader(), 0, rpgMsg, 0, RpgHeader.HEADER_LENGTH);
    if (null != payload) {
        System.arraycopy(payload, 0, rpgMsg, RpgHeader.HEADER_LENGTH, payload.length);
    }
    return rpgMsg;
}
Also used : AuthSessionHolder(com.vodafone360.people.datatypes.AuthSessionHolder) Hashtable(java.util.Hashtable) RpgHeader(com.vodafone360.people.service.io.rpg.RpgHeader)

Example 3 with AuthSessionHolder

use of com.vodafone360.people.datatypes.AuthSessionHolder in project 360-Engine-for-Android by 360.

the class TcpConnectionThread method run.

public void run() {
    QueueManager queueManager = QueueManager.getInstance();
    setFailedRetrying(false);
    setIsRetrying(false);
    try {
        // start the initial connection
        reconnectSocket();
        HeartbeatSenderThread hbSender = new HeartbeatSenderThread(this, mService, mSocket);
        hbSender.setOutputStream(mOs);
        hbSender.sendHeartbeat();
        hbSender = null;
        // TODO run this when BE supports it but keep HB in front!
        /*
             * ConnectionTester connTester = new ConnectionTester(mIs, mOs); if
             * (connTester.runTest()) { } else {}
             */
        startHelperThreads();
        ConnectionManager.getInstance().onConnectionStateChanged(ITcpConnectionListener.STATE_CONNECTED);
    } catch (IOException e) {
        haltAndRetryConnection(FIRST_ATTEMPT);
    } catch (Exception e) {
        haltAndRetryConnection(FIRST_ATTEMPT);
    }
    while (mConnectionShouldBeRunning) {
        try {
            if ((null != mOs) && (!getFailedRetrying())) {
                List<Request> reqs = QueueManager.getInstance().getRpgRequests();
                int reqNum = reqs.size();
                List<Integer> reqIdList = null;
                if (Settings.sEnableProtocolTrace || Settings.sEnableSuperExpensiveResponseFileLogging) {
                    reqIdList = new ArrayList<Integer>();
                }
                if (reqNum > 0) {
                    mBaos.reset();
                    // batch payloads
                    for (int i = 0; i < reqNum; i++) {
                        Request req = reqs.get(i);
                        if ((null == req) || (req.getAuthenticationType() == Request.USE_API)) {
                            HttpConnectionThread.logV("TcpConnectionThread.run()", "Ignoring non-RPG method");
                            continue;
                        }
                        HttpConnectionThread.logD("TcpConnectionThread.run()", "Preparing [" + req.getRequestId() + "] for sending via RPG...");
                        req.setActive(true);
                        req.writeToOutputStream(mBaos, true);
                        // so we should not remove it from the queue otherwise there will be no timeout triggered.
                        if (req.isFireAndForget() && (req.mType != Request.Type.AVAILABILITY)) {
                            // f-a-f, no response,
                            // remove from queue
                            HttpConnectionThread.logD("TcpConnectionThread.run()", "Removed F&F-Request: " + req.getRequestId());
                            queueManager.removeRequest(req.getRequestId());
                        }
                        if (Settings.sEnableProtocolTrace) {
                            reqIdList.add(req.getRequestId());
                            HttpConnectionThread.logD("HttpConnectionThread.run()", "Req ID: " + req.getRequestId() + " <-> Auth: " + req.getAuth());
                        }
                    }
                    mBaos.flush();
                    byte[] payload = mBaos.toByteArray();
                    if (null != payload) {
                        // log file containing response to SD card
                        if (Settings.sEnableSuperExpensiveResponseFileLogging) {
                            StringBuffer sb = new StringBuffer();
                            for (int i = 0; i < reqIdList.size(); i++) {
                                sb.append(reqIdList.get(i));
                                sb.append("_");
                            }
                            LogUtils.logE("XXXXXXYYYXXXXXX Do not Remove this!");
                            LogUtils.logToFile(payload, "people_" + (reqIdList.size() > 0 ? reqIdList.get(0) : 0) + "_" + System.currentTimeMillis() + "_req_" + // message
                            ((int) payload[2]) + // type
                            ".txt");
                        }
                        if (Settings.sEnableProtocolTrace) {
                            Long userID = null;
                            AuthSessionHolder auth = LoginEngine.getSession();
                            if (auth != null) {
                                userID = auth.userID;
                            }
                            HttpConnectionThread.logI("TcpConnectionThread.run()", "\n  > Sending request(s) " + reqIdList.toString() + ", for user ID " + userID + " >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + HessianUtils.getInHessian(new ByteArrayInputStream(payload), true) + "\n  ");
                        }
                        try {
                            synchronized (mOs) {
                                mOs.write(payload);
                                mOs.flush();
                            }
                        } catch (IOException ioe) {
                            HttpConnectionThread.logE("TcpConnectionThread.run()", "Could not send request", ioe);
                            notifyOfNetworkProblems();
                        }
                        payload = null;
                    }
                }
            }
            if (!getFailedRetrying()) {
                synchronized (requestLock) {
                    requestLock.wait();
                }
            } else {
                while (getFailedRetrying()) {
                    // loop until a retry
                    // succeeds
                    HttpConnectionThread.logI("TcpConnectionThread.run()", "Wait() for next connection retry has started.");
                    synchronized (errorLock) {
                        errorLock.wait(Settings.TCP_RETRY_BROKEN_CONNECTION_INTERVAL);
                    }
                    if (mConnectionShouldBeRunning) {
                        haltAndRetryConnection(FIRST_ATTEMPT);
                    }
                }
            }
        } catch (Throwable t) {
            HttpConnectionThread.logE("TcpConnectionThread.run()", "Unknown Error: ", t);
        }
    }
    stopConnection();
    ConnectionManager.getInstance().onConnectionStateChanged(ITcpConnectionListener.STATE_DISCONNECTED);
}
Also used : Request(com.vodafone360.people.service.io.Request) IOException(java.io.IOException) IOException(java.io.IOException) QueueManager(com.vodafone360.people.service.io.QueueManager) AuthSessionHolder(com.vodafone360.people.datatypes.AuthSessionHolder) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 4 with AuthSessionHolder

use of com.vodafone360.people.datatypes.AuthSessionHolder in project 360-Engine-for-Android by 360.

the class HeartbeatSenderThread method getHeartbeatHessianPayload.

/**
 * Returns a byte-array containing the data needed for sending a heartbeat
 * to the RPG.
 *
 * @throws IOException If there was an exception serializing the hash map to
 *             a hessian byte array.
 * @return A byte array representing the heartbeat.
 */
private byte[] getHeartbeatHessianPayload() throws IOException {
    // hash table for parameters to Hessian encode
    final Hashtable<String, Object> ht = new Hashtable<String, Object>();
    final String timestamp = "" + ((long) System.currentTimeMillis() / MILLIS_PER_SEC);
    final AuthSessionHolder auth = LoginEngine.getSession();
    if (auth == null) {
        throw new NullPointerException();
    }
    ht.put("auth", AuthUtils.calculateAuth("", new Hashtable<String, Object>(), timestamp, auth));
    ht.put("userid", auth.userID);
    // do Hessian encoding
    final byte[] payload = HessianEncoder.createHessianByteArray("", ht);
    payload[1] = (byte) 1;
    payload[2] = (byte) 0;
    final int reqLength = RpgHeader.HEADER_LENGTH + payload.length;
    final RpgHeader rpgHeader = new RpgHeader();
    rpgHeader.setPayloadLength(payload.length);
    rpgHeader.setReqType(RpgMessageTypes.RPG_TCP_HEARTBEAT);
    final byte[] rpgMsg = new byte[reqLength];
    System.arraycopy(rpgHeader.createHeader(), 0, rpgMsg, 0, RpgHeader.HEADER_LENGTH);
    if (null != payload) {
        System.arraycopy(payload, 0, rpgMsg, RpgHeader.HEADER_LENGTH, payload.length);
    }
    return rpgMsg;
}
Also used : AuthSessionHolder(com.vodafone360.people.datatypes.AuthSessionHolder) Hashtable(java.util.Hashtable) RpgHeader(com.vodafone360.people.service.io.rpg.RpgHeader)

Example 5 with AuthSessionHolder

use of com.vodafone360.people.datatypes.AuthSessionHolder in project 360-Engine-for-Android by 360.

the class HessianDecoder method decodeResponse.

/**
 * @param is
 * @param requestId
 * @param type
 * @param isZipped
 * @param engineId
 *
 * @return
 *
 * @throws IOException
 */
@SuppressWarnings("unchecked")
private DecodedResponse decodeResponse(InputStream is, int requestId, Request.Type type, boolean isZipped, EngineId engineId) throws IOException {
    boolean usesReplyTag = false;
    int responseType = DecodedResponse.ResponseType.UNKNOWN.ordinal();
    List<BaseDataType> resultList = new ArrayList<BaseDataType>();
    mMicroHessianInput.init(is);
    // skip start
    // initial map tag or fail
    int tag = is.read();
    if (tag == 'r') {
        // reply / response
        // read major and minor
        is.read();
        is.read();
        // read next tag
        tag = is.read();
        usesReplyTag = true;
    }
    if (tag == -1) {
        return null;
    }
    // read reason string and throw exception
    if (tag == 'f') {
        ServerError zybErr = new ServerError(mMicroHessianInput.readFault().errString());
        resultList.add(zybErr);
        DecodedResponse decodedResponse = new DecodedResponse(requestId, resultList, engineId, DecodedResponse.ResponseType.SERVER_ERROR.ordinal());
        return decodedResponse;
    }
    // this is not wrapped up in a hashtable
    if (type == Request.Type.EXTERNAL_RPG_RESPONSE) {
        LogUtils.logV("HessianDecoder.decodeResponse() EXTERNAL_RPG_RESPONSE");
        if (tag != 'I') {
            LogUtils.logE("HessianDecoder.decodeResponse() " + "tag!='I' Unexpected Hessian type:" + tag);
        }
        parseExternalResponse(resultList, is, tag);
        DecodedResponse decodedResponse = new DecodedResponse(requestId, resultList, engineId, DecodedResponse.ResponseType.SERVER_ERROR.ordinal());
        return decodedResponse;
    }
    // internal response: should contain a Map type - i.e. Hashtable
    if (tag != 'M') {
        LogUtils.logE("HessianDecoder.decodeResponse() tag!='M' Unexpected Hessian type:" + tag);
        throw new IOException("Unexpected Hessian type");
    } else if (// if we have a common request or sign in request
    (type == Request.Type.COMMON) || (type == Request.Type.SIGN_IN) || (type == Request.Type.GET_MY_IDENTITIES) || (type == Request.Type.GET_AVAILABLE_IDENTITIES)) {
        Hashtable<String, Object> map = (Hashtable<String, Object>) mMicroHessianInput.readHashMap(tag);
        if (null == map) {
            return null;
        }
        if (map.containsKey(KEY_SESSION)) {
            AuthSessionHolder auth = new AuthSessionHolder();
            Hashtable<String, Object> authHash = (Hashtable<String, Object>) map.get(KEY_SESSION);
            resultList.add(auth.createFromHashtable(authHash));
            responseType = DecodedResponse.ResponseType.LOGIN_RESPONSE.ordinal();
        } else if (map.containsKey(KEY_CONTACT_LIST)) {
            // contact list
            getContacts(resultList, ((Vector<?>) map.get(KEY_CONTACT_LIST)));
            responseType = DecodedResponse.ResponseType.GET_CONTACTCHANGES_RESPONSE.ordinal();
        } else if (map.containsKey(KEY_USER_PROFILE_LIST)) {
            Vector<Hashtable<String, Object>> upVect = (Vector<Hashtable<String, Object>>) map.get(KEY_USER_PROFILE_LIST);
            for (Hashtable<String, Object> obj : upVect) {
                resultList.add(UserProfile.createFromHashtable(obj));
            }
            responseType = DecodedResponse.ResponseType.GETME_RESPONSE.ordinal();
        } else if (map.containsKey(KEY_USER_PROFILE)) {
            Hashtable<String, Object> userProfileHash = (Hashtable<String, Object>) map.get(KEY_USER_PROFILE);
            resultList.add(UserProfile.createFromHashtable(userProfileHash));
            responseType = DecodedResponse.ResponseType.GETME_RESPONSE.ordinal();
        } else if (// we have identity items in the map which we can parse
        (map.containsKey(KEY_IDENTITY_LIST)) || (map.containsKey(KEY_AVAILABLE_IDENTITY_LIST))) {
            int identityType = 0;
            Vector<Hashtable<String, Object>> idcap = null;
            if (map.containsKey(KEY_IDENTITY_LIST)) {
                idcap = (Vector<Hashtable<String, Object>>) map.get(KEY_IDENTITY_LIST);
                identityType = BaseDataType.MY_IDENTITY_DATA_TYPE;
                responseType = DecodedResponse.ResponseType.GET_MY_IDENTITIES_RESPONSE.ordinal();
            } else {
                idcap = (Vector<Hashtable<String, Object>>) map.get(KEY_AVAILABLE_IDENTITY_LIST);
                identityType = BaseDataType.AVAILABLE_IDENTITY_DATA_TYPE;
                responseType = DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITIES_RESPONSE.ordinal();
            }
            for (Hashtable<String, Object> obj : idcap) {
                Identity id = new Identity(identityType);
                resultList.add(id.createFromHashtable(obj));
            }
        } else if (type == Request.Type.GET_AVAILABLE_IDENTITIES) {
            // we have an available identities response, but it is empty
            responseType = DecodedResponse.ResponseType.GET_AVAILABLE_IDENTITIES_RESPONSE.ordinal();
        } else if (type == Request.Type.GET_MY_IDENTITIES) {
            // we have a my identities response, but it is empty
            responseType = DecodedResponse.ResponseType.GET_MY_IDENTITIES_RESPONSE.ordinal();
        } else if (map.containsKey(KEY_ACTIVITY_LIST)) {
            Vector<Hashtable<String, Object>> activityList = (Vector<Hashtable<String, Object>>) map.get(KEY_ACTIVITY_LIST);
            for (Hashtable<String, Object> obj : activityList) {
                resultList.add(ActivityItem.createFromHashtable(obj));
            }
            responseType = DecodedResponse.ResponseType.GET_ACTIVITY_RESPONSE.ordinal();
        }
    } else if ((type != Request.Type.COMMON) && (type != Request.Type.SIGN_IN)) {
        // get initial hash table
        // TODO: we cast every response to a Map, losing e.g. push event
        // "c0" which only contains a string - to fix
        Hashtable<String, Object> hash = (Hashtable<String, Object>) mMicroHessianInput.decodeType(tag);
        responseType = decodeResponseByRequestType(resultList, hash, type);
    }
    if (usesReplyTag) {
        // read the last 'z'
        is.read();
    }
    DecodedResponse decodedResponse = new DecodedResponse(requestId, resultList, engineId, responseType);
    return decodedResponse;
}
Also used : DecodedResponse(com.vodafone360.people.service.io.ResponseQueue.DecodedResponse) ServerError(com.vodafone360.people.datatypes.ServerError) Hashtable(java.util.Hashtable) ArrayList(java.util.ArrayList) IOException(java.io.IOException) AuthSessionHolder(com.vodafone360.people.datatypes.AuthSessionHolder) BaseDataType(com.vodafone360.people.datatypes.BaseDataType) ExternalResponseObject(com.vodafone360.people.datatypes.ExternalResponseObject) Identity(com.vodafone360.people.datatypes.Identity) Vector(java.util.Vector)

Aggregations

AuthSessionHolder (com.vodafone360.people.datatypes.AuthSessionHolder)15 IOException (java.io.IOException)6 MediumTest (android.test.suitebuilder.annotation.MediumTest)4 ServiceStatus (com.vodafone360.people.service.ServiceStatus)4 ArrayList (java.util.ArrayList)4 BaseDataType (com.vodafone360.people.datatypes.BaseDataType)3 DecodedResponse (com.vodafone360.people.service.io.ResponseQueue.DecodedResponse)3 Hashtable (java.util.Hashtable)3 ServerError (com.vodafone360.people.datatypes.ServerError)2 RpgHeader (com.vodafone360.people.service.io.rpg.RpgHeader)2 DecoderThread (com.vodafone360.people.service.transport.DecoderThread)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 Cursor (android.database.Cursor)1 SQLException (android.database.SQLException)1 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)1 SQLiteException (android.database.sqlite.SQLiteException)1 Bundle (android.os.Bundle)1 ExternalResponseObject (com.vodafone360.people.datatypes.ExternalResponseObject)1 Identity (com.vodafone360.people.datatypes.Identity)1 SimpleText (com.vodafone360.people.datatypes.SimpleText)1