⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 simplesessionhandler.java

📁 实现了SyncML无线同步协议
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
            syncInit.setDatabases(dbs);            //            // Setting server capabilities            //            syncInit.setServerCapabilities(                syncEngine.getServerCapabilities(syncInit.getDTDVersion())            );        } else {            if (isAccountExpired()) {                syncInit.setAuthorizedStatusCode(StatusCode.PAYMENT_REQUIRED);            } else if (!isGuestEnabled() && isValidCredential()) {                syncInit.setAuthorizedStatusCode(StatusCode.MISSING_CREDENTIALS);            } else if (!isValidCredential()) {                syncInit.setAuthorizedStatusCode(StatusCode.INVALID_CREDENTIALS);            } else {                syncInit.setAuthorizedStatusCode(StatusCode.FORBIDDEN);            }        }        return syncInit.getResponse();    }    /**     * Processes the given synchronization message.     *     * @param syncRequest the message to be processed     *     * @return the response message     *     * @throws ProtocolException     */    private SyncML processSyncMessage(SyncML syncRequest)    throws ProtocolException {        if (log.isLoggable(Level.FINEST)) {            log.finest("client sources: " + syncEngine.getClientSources());        }        try {            modifications =                    new ClientModifications(syncRequest.getSyncHdr() ,                                            syncRequest.getSyncBody(),                                            syncEngine.getDbs());            Sync[] syncCommands = modifications.getClientSyncCommands();            if (syncCommands == null || syncCommands.length == 0) {                throw new ProtocolException("Sync command expected in this package but no Sync commands were found");            }            List responseCommands = processModifications(modifications);            if (log.isLoggable(Level.FINEST)) {                log.finest("responseCommands: " + responseCommands);            }            modifications.setIdGenerator(cmdIdGenerator);            modifications.setFlag(Flags.FLAG_ALL_RESPONSES_REQUIRED);            modifications.setClientModificationsStatus(                    (Status[]) filterCommands(                            responseCommands,                            new String[]{ Status.COMMAND_NAME }                    ).toArray(new Status[0])            );            // .setServerModifications sets all the modification commands            // required to be send to client from Server            // cannot block this whole code,as this code may be used            // by other DBS within same sync but differnt alert code.            AbstractCommand[] serverModifications =                    (AbstractCommand[]) filterCommands(                        responseCommands,                        new String[]{Sync.COMMAND_NAME}                    ).toArray(new AbstractCommand[0]);            syncState.setServerModifications(serverModifications);            //            //the server must be send all modification command only when the            //client has sent the last message            //            if (syncRequest.getSyncBody().isFinalMsg()) {                modifications.setServerModifications(syncState.getServerModifications());                modifications.setFlag(Flags.FLAG_FINAL_MESSAGE);            }            SyncML response = modifications.getResponse();            return response;        } catch (Sync4jException e) {            throw new ProtocolException(e);        }    }    /**     * Executes the given modifications and for each of them returns a status     * command. It forwards the execution to the synchronization engine.     *     * @param modifications synchronization commands containing the modifications     *                 that the client requires     *     * @return an array of command objects, each containig the result of     *         a modification or a modification itself     * @throws Sync4jException     */    private List processModifications(ClientModifications modifications)            throws Sync4jException {        SyncHdr    header           = modifications.getSyncHeader();        String     msgId            = header.getMsgID()            ;        boolean    headerNoResponse = header.isNoResp()            ;        ArrayList responseCommands = new ArrayList();        syncEngine.setCommandIdGenerator(cmdIdGenerator);        Sync[] syncCommands = modifications.getClientSyncCommands();        //        // Retrieves existing LUID-GUID mapping        //        getClientMappings();        //        // First of all prepare the memory sources with the modification commands        // receveid by the client        //        prepareMemorySources(syncCommands);        syncEngine.setClientMappings(clientMappings);        try {            syncEngine.sync(loggedPrincipal);        } catch (Sync4jException e) {            log.throwing(getClass().getName(), "processModifications", e);        }        //        // Status code for commands        //        if (headerNoResponse == false) {            //            // Sync commands            //            responseCommands.addAll(statusForSyncs(syncCommands));            //            // Status for server-side executed modification commands            //            Status[] operationStatus =                syncEngine.getModificationsStatusCommands(msgId);            for (int i=0; i<operationStatus.length; ++i) {                responseCommands.add(operationStatus[i]);            }        }        //        // SyncCommands sent back to the client        // No sync sent to client if ONE_WAY_FROM_CLIENT        //        Alert[] alertCommands = syncState.getClientAlerts();        Item[] alertItems = null;        ItemizedCommand[] commands = null;        String uri = null;        for (int k = 0; ((alertCommands != null) && (k < alertCommands.length)); ++k) {            //            // If the alert represents a client only action, just ignore it            //            if (AlertCode.isClientOnlyCode(alertCommands[k].getData())) {                continue;            }            alertItems = (Item[])alertCommands[k].getItems().toArray(new Item[0]);            for (int i=0; ((alertItems != null) && (i < alertItems.length)); ++i) {                uri = alertItems[i].getTarget().getLocURI();                for (int s=0; ((syncCommands != null) && s<syncCommands.length); s++) {                    if ((syncCommands[s].getTarget() != null) && !uri.equals(syncCommands[s].getTarget().getLocURI())) {                        continue;                    }                    for (int j = 0; ((syncEngine.getDbs() != null) && (j < syncEngine.getDbs().length)); ++j) {                        if ((syncEngine.getDbs())[j].getName().equals(uri)){                            SyncOperation[] operations = syncEngine.getSyncOperations(uri);                            commands = syncEngine.operationsToCommands(                                           (ClientMapping)clientMappings.get(uri),                                           operations,                                           uri                                       );                            responseCommands.add(                                    new Sync(                                            cmdIdGenerator.next(),                                            false,                                            null,                                            ProtocolUtil.source2Target(alertItems[i].getSource()),                                            ProtocolUtil.target2Source(alertItems[i].getTarget()),                                            null,                                            0,                                            commands                                    )                            );                            //                            // Now we can update the client-side LUID-GUID mappings                            //                            syncEngine.updateClientMappings(clientMappings, operations, slow);                        }                    }  // next j                }            } // next i        } // next k        //        // Resets client alerts so that they are considered processed        //        syncState.resetClientAlerts();        //        // And here we can update the server-side LUID-GUID mappings        //        syncEngine.updateServerMappings(clientMappings, slow);        return responseCommands;    }    /**     * Process the completion message from the client check status for sync     * command and update client mapping     * @param message     * @return the response message     * @throws ProtocolException     */    private SyncML processCompletionMessage(SyncML message)    throws ProtocolException {        if (log.isLoggable(Level.FINEST)) {            log.finest("processCompletionMessage");        }        SyncML ret = null;        try {            ClientCompletion clientCompletion =                 new ClientCompletion(message.getSyncHdr(),                                      message.getSyncBody()                                     );            clientCompletion.setIdGenerator(cmdIdGenerator);            clientCompletion.setFlag(Flags.FLAG_FINAL_MESSAGE);            //            // IF the client completion request contains MapCommand            //            if (clientCompletion.isMapCommandFind()) {                String uri = null;                ClientMapping mapping = null;                Map[] mapCommands = clientCompletion.getMapCommands();                MapItem[]    mapItems    = null                             ;                for (int j=0; ((mapCommands != null) && (j<mapCommands.length)); ++j) {                    uri = mapCommands[j].getTarget().getLocURI();                    mapItems =                        (MapItem[])mapCommands[j].getMapItems().toArray(                                                                new MapItem[0]);                    mapping = (ClientMapping)clientMappings.get(uri);                    if (mapping == null) {                        mapping = new ClientMapping(loggedPrincipal, uri);                        clientMappings.put(uri, mapping);                    }                    for (int i = 0; i < mapItems.length; i++) {                        MapItem mapItem = mapItems[i];                        //Adding item properties to the persistent mapping                        String GUID = mapItem.getTarget().getLocURI();                        String LUID = mapItem.getSource().getLocURI();                        mapping.updateMapping(LUID, GUID);                    }                }            }            ret = clientCompletion.getResponse();        } catch (Sync4jException e) {            log.severe("Error in process completion");            throw new ProtocolException(e);        }        return ret;    }    /**     * Makes a state transition. Very simple implementation at the moment: it     * changes the value of <i>currentState</i> to the given value.     *     * @param state the new state     */    private void moveTo(int state) {        if (log.isLoggable(Level.FINE)) {            log.fine("moving to state " + getStateName(state));        }        currentState = state;    }    /**     * Prepares the memory sources with the modification commands receveid     * by the client.     * <p>     * Note that if the requested synchronization is a slow sync, the items are     * inserted as "existing" items, regardless the command they belong to.     * (maybe this will change as soon as the specification becomes clearer)     *     * @param syncCommands the commands used to prepare the source     *     */    private void prepareMemorySources(Sync[] syncCommands) {        List sources = syncEngine.getClientSources();        //        // For efficiency: put the databases in a HashMap        //        HashMap dbMap = new HashMap();        for (int i=0; ((syncEngine.getDbs() != null) && (i<syncEngine.getDbs().length)); ++i) {            dbMap.put((syncEngine.getDbs())[i].getName(), (syncEngine.getDbs())[i]);        }        //        // First of all prepare the memory sources with the modification commands        // receveid by the client        //        int method;        slow = false;        Target target = null;        MemorySyncSource mss = null;        AbstractCommand[] modifications = null;        for (int i = sources.size(); i > 0; --i) {            if (log.isLoggable(Level.FINE)) {                log.fine("Preparing "                        + syncEngine.getClientSources().get(i - 1)                        + " with "                        + Arrays.asList(syncCommands)                );            }            mss = (MemorySyncSource) sources.get(i - 1);            String  uri = mss.getSourceURI();            modifications = new AbstractCommand[0];            for (int j = 0; ((syncCommands != null) && (j < syncCommands.length)); ++j) {                target = syncCommands[j].getTarget();                if ((target != null) && (uri.equals(target.getLocURI()))) {                    if (syncCommands[j].getCommands() != null) {                       modifications =                       (AbstractCommand[])syncCommands[j].getCommands().toArray(                                                        new AbstractCommand[0]);                    }                    break;                }            }            method = ((Database)dbMap.get(uri)).getMethod();            slow = ((method == AlertCode.SLOW) || (method == AlertCode.REFRESH_FROM_SERVER));            prepareMemorySource(mss, modifications, slow);        }    }    /**     * Prepares a source that represents the image of the client database. This     * is done combining the existing client mapping with the modifications sent     * by the client. Than this source can be compared with the server view of     * the database.     *     * @param source the e source to prepare     * @param commands the client modifications     * @param slowSync true if the preparation is for a slow sync, false     *                    otherwise     *     */    private void prepareMemorySource(MemorySyncSource  source  ,                                     AbstractCommand[] commands,                                     boolean           slowSync) {        ArrayList existing = new ArrayList();        ArrayList deleted  = new ArrayList();        ArrayList created  = new ArrayList();        ArrayList updated  = new ArrayList();        ClientMapping guidluid = null;        //        // First of all, in the case of fast sync, the items already mapped are        // added as existing items. Note that server ids are used.        // In the case of slow sync, the mappinngs are cleared so that they        // won't generate conflicts.        //        guidluid = (ClientMapping)clientMappings.get(source.getSourceURI());        if (slowSync) {            if (guidluid != null && finalMsg) {                guidluid.clearMappings();            }        } else {            if (guidluid != null) {                java.util.Map map = guidluid.getMapping();                Iterator i = map.keySet().iterator();                while (i.hasNext()) {                    existing.add(                        new SyncItemImpl(source, map.get(i.next()), SyncItemState.SYNCHRONIZED)                    );                }            }        }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -