Search in sources :

Example 16 with Request

use of com.vodafone360.people.service.io.Request in project 360-Engine-for-Android by 360.

the class AuthenticationManager method handleAuthRequests.

/**
     * Uses the passed http connection to start a synchronous request against
     * the API. This method blocks until the request is made and the response is
     * retrieved.
     */
public void handleAuthRequests() {
    List<Request> requests = QueueManager.getInstance().getApiRequests();
    if (null == requests) {
        return;
    }
    HttpConnectionThread.logI("AuthenticationManager.handleAuthRequest()", "Looking for auth requests");
    for (int i = 0; i < requests.size(); i++) {
        Request request = requests.get(i);
        request.setActive(true);
        List<Integer> reqIds = new ArrayList<Integer>();
        reqIds.add(request.getRequestId());
        try {
            HttpConnectionThread.logI("AuthenticationManager.handleAuthRequest()", "Request: " + request.getRequestId());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            request.writeToOutputStream(baos, false);
            byte[] payload = baos.toByteArray();
            if (Settings.sEnableProtocolTrace) {
                HttpConnectionThread.logI("AuthenticationManager.handleAuthRequests()", "\n \n \nAUTHENTICATING: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + HessianUtils.getInHessian(new ByteArrayInputStream(payload), true));
            }
            HttpResponse resp = mHttpConnection.postHTTPRequest(payload, mApiUrl, Settings.HTTP_HEADER_CONTENT_TYPE);
            mHttpConnection.handleApiResponse(resp, reqIds);
        } catch (Exception e) {
            mHttpConnection.addErrorToResponseQueue(reqIds);
        }
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) Request(com.vodafone360.people.service.io.Request) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MalformedURLException(java.net.MalformedURLException) URISyntaxException(java.net.URISyntaxException)

Example 17 with Request

use of com.vodafone360.people.service.io.Request 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 18 with Request

use of com.vodafone360.people.service.io.Request 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)

Example 19 with Request

use of com.vodafone360.people.service.io.Request in project 360-Engine-for-Android by 360.

the class NativeContactsApi2 method putOrganization.

// PHOTO NOT USED
// /**
// * Do a GET request and retrieve up to maxBytes bytes
// *
// * @param url
// * @param maxBytes
// * @return
// * @throws IOException
// */
// public static byte[] doGetAndReturnBytes(URL url, int maxBytes) throws
// IOException {
// HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.setRequestMethod("GET");
// InputStream istr = null;
// try {
// int rc = conn.getResponseCode();
// if (rc != 200) {
// throw new IOException("code " + rc + " '" + conn.getResponseMessage() +
// "'");
// }
// istr = new BufferedInputStream(conn.getInputStream(), 512);
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// copy(istr, baos, maxBytes);
// return baos.toByteArray();
// } finally {
// if (istr != null) {
// istr.close();
// }
// }
// }
//    
// /**
// * Copy maxBytes from an input stream to an output stream.
// * @param in
// * @param out
// * @param maxBytes
// * @return
// * @throws IOException
// */
// private static int copy(InputStream in, OutputStream out, int maxBytes)
// throws IOException {
// byte[] buf = new byte[512];
// int bytesRead = 1;
// int totalBytes = 0;
// while (bytesRead > 0) {
// bytesRead = in.read(buf, 0, Math.min(512, maxBytes - totalBytes));
// if (bytesRead > 0) {
// out.write(buf, 0, bytesRead);
// totalBytes += bytesRead;
// }
// }
// return totalBytes;
// }
//  
// /**
// * Put Photo detail into the values
// * @param cc {@link ContactChange} to read values from
// */
// private void putPhoto(ContactChange cc) {
// try {
// // File file = new File(cc.getValue());
// // InputStream is = new FileInputStream(file);
// // byte[] bytes = new byte[(int) file.length()];
// // is.read(bytes);
// // is.close();
// final URL url = new URL(cc.getValue());
// byte[] bytes = doGetAndReturnBytes(url, 1024 * 100);
// mValues.put(Photo.PHOTO, bytes);
// mValues.put(Photo.MIMETYPE, Photo.CONTENT_ITEM_TYPE);
// } catch(Exception ex) {
// LogUtils.logE("Unable to put Photo detail because of exception:"+ex);
// }
// }
/**
     * Put Organization detail into the values
     * 
     * @param cc {@link ContactChange} to read values from
     */
private void putOrganization(ContactChange[] ccList) {
    mValues.clear();
    int flags = ContactChange.FLAG_NONE;
    if (mMarkedOrganizationIndex > -1) {
        final ContactChange cc = ccList[mMarkedOrganizationIndex];
        flags |= cc.getFlags();
        final Organisation organization = VCardHelper.getOrg(cc.getValue());
        if (organization != null) {
            mValues.put(Organization.COMPANY, organization.name);
            if (organization.unitNames.size() > 0) {
                // Only considering one unit name (department) as that's all
                // we support
                mValues.put(Organization.DEPARTMENT, organization.unitNames.get(0));
            } else {
                mValues.putNull(Organization.DEPARTMENT);
            }
        }
    }
    if (mMarkedTitleIndex > -1) {
        final ContactChange cc = ccList[mMarkedTitleIndex];
        flags |= cc.getFlags();
        // No need to check for empty values as there is only one
        mValues.put(Organization.TITLE, cc.getValue());
    }
    if (mValues.size() > 0) {
        mValues.put(Organization.LABEL, (String) null);
        mValues.put(Organization.TYPE, mapToNabOrganizationType(flags));
        mValues.put(Organization.IS_PRIMARY, flags & ContactChange.FLAG_PREFERRED);
        mValues.put(Organization.MIMETYPE, Organization.CONTENT_ITEM_TYPE);
    }
}
Also used : Organisation(com.vodafone360.people.datatypes.VCardHelper.Organisation)

Example 20 with Request

use of com.vodafone360.people.service.io.Request in project 360-Engine-for-Android by 360.

the class GroupsEngine method processCommsResponse.

@Override
protected void processCommsResponse(DecodedResponse resp) {
    LogUtils.logD("DownloadGroups.processCommsResponse()");
    ServiceStatus status = BaseEngine.getResponseStatus(BaseDataType.ITEM_LIST_DATA_TYPE, resp.mDataTypes);
    if (status == ServiceStatus.SUCCESS) {
        final List<GroupItem> tempGroupList = new ArrayList<GroupItem>();
        for (int i = 0; i < resp.mDataTypes.size(); i++) {
            ItemList itemList = (ItemList) resp.mDataTypes.get(i);
            if (itemList.mType != ItemList.Type.group_privacy) {
                completeUiRequest(ServiceStatus.ERROR_UNEXPECTED_RESPONSE);
                return;
            }
            // TODO: why cloning the list?
            for (int j = 0; j < itemList.mItemList.size(); j++) {
                tempGroupList.add((GroupItem) itemList.mItemList.get(j));
            }
        }
        LogUtils.logI("DownloadGroups.processCommsResponse() - No of groups " + tempGroupList.size());
        if (mPageNo == 0) {
            // clear old groups if we request the first groups page
            mDb.deleteAllGroups();
        }
        status = GroupsTable.addGroupList(tempGroupList, mDb.getWritableDatabase());
        if (ServiceStatus.SUCCESS != status) {
            completeUiRequest(status);
            return;
        }
        mNoOfGroupsFetched += tempGroupList.size();
        if (tempGroupList.size() < MAX_DOWN_PAGE_SIZE) {
            completeUiRequest(ServiceStatus.SUCCESS);
            return;
        }
        mPageNo++;
        requestNextGroupsPage();
        return;
    }
    LogUtils.logE("DownloadGroups.processCommsResponse() - Error requesting Zyb groups, error = " + status);
    completeUiRequest(status);
}
Also used : ServiceStatus(com.vodafone360.people.service.ServiceStatus) ItemList(com.vodafone360.people.datatypes.ItemList) ArrayList(java.util.ArrayList) GroupItem(com.vodafone360.people.datatypes.GroupItem)

Aggregations

Request (com.vodafone360.people.service.io.Request)43 QueueManager (com.vodafone360.people.service.io.QueueManager)27 ServiceStatus (com.vodafone360.people.service.ServiceStatus)16 ArrayList (java.util.ArrayList)16 BaseDataType (com.vodafone360.people.datatypes.BaseDataType)12 ServiceUiRequest (com.vodafone360.people.service.ServiceUiRequest)12 DecodedResponse (com.vodafone360.people.service.io.ResponseQueue.DecodedResponse)11 Suppress (android.test.suitebuilder.annotation.Suppress)10 DatabaseHelper (com.vodafone360.people.database.DatabaseHelper)9 IEngineEventCallback (com.vodafone360.people.engine.IEngineEventCallback)9 IContactSyncCallback (com.vodafone360.people.engine.contactsync.IContactSyncCallback)9 ProcessorFactory (com.vodafone360.people.engine.contactsync.ProcessorFactory)9 ServerError (com.vodafone360.people.datatypes.ServerError)6 IOException (java.io.IOException)6 Identity (com.vodafone360.people.datatypes.Identity)5 ByteArrayInputStream (java.io.ByteArrayInputStream)5 Bundle (android.os.Bundle)4 AuthSessionHolder (com.vodafone360.people.datatypes.AuthSessionHolder)4 ContactChanges (com.vodafone360.people.datatypes.ContactChanges)4 ResponseQueue (com.vodafone360.people.service.io.ResponseQueue)4