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

📄 simplesessionhandler.java

📁 实现了SyncML无线同步协议
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
        String name = null;        for (int i = 0; ((commands != null) && (i < commands.length)); ++i) {            name = commands[i].getName();            if (slowSync && !Delete.COMMAND_NAME.equals(name)) {                existing.addAll(                    Arrays.asList(                            syncEngine.itemsToSyncItems(                                (ClientMapping)clientMappings.get(source.getSourceURI()),                                source,                                (ModificationCommand)commands[i],                                SyncItemState.SYNCHRONIZED,                                nextTimestamp.start                            )                    )                );                continue;            }            if (Add.COMMAND_NAME.equals(commands[i].getName())) {                created.addAll(                        Arrays.asList(                                syncEngine.itemsToSyncItems(                                    (ClientMapping)clientMappings.get(source.getSourceURI()),                                    source,                                    (ModificationCommand)commands[i],                                    SyncItemState.NEW,                                    nextTimestamp.start                                )                        )                );                continue;            }            if (Delete.COMMAND_NAME.equals(commands[i].getName())) {                deleted.addAll(                        Arrays.asList(                                syncEngine.itemsToSyncItems(                                    (ClientMapping)clientMappings.get(source.getSourceURI()),                                    source,                                    (ModificationCommand)commands[i],                                    SyncItemState.DELETED,                                    nextTimestamp.start                                )                        )                );                continue;            }            if (Replace.COMMAND_NAME.equals(commands[i].getName())) {                updated.addAll(                        Arrays.asList(                                syncEngine.itemsToSyncItems(                                    (ClientMapping)clientMappings.get(source.getSourceURI()),                                    source,                                    (ModificationCommand)commands[i],                                    SyncItemState.UPDATED,                                    nextTimestamp.start                                )                        )                );                continue;            }        }        source.initialize(existing, deleted, created, updated);    }    /**     * Filters a list of commands extracting the ones of the given types.     *     * @param commands the list of command to be filtered     * @param types the command types to extract     *     * @return an array of the selected commmands     */    private List filterCommands(List commands, String[] types) {        StringBuffer sb = new StringBuffer(",");        for (int i = 0; ((types != null) && (i < types.length)); ++i) {            sb.append(types[i]).append(',');        }        ArrayList selectedCommands = new ArrayList();        AbstractCommand command = null;        Iterator i = commands.iterator();        while (i.hasNext()) {            command = (AbstractCommand) i.next();            if (sb.indexOf(',' + command.getName() + ',') >= 0) {                selectedCommands.add(command);            }        }        return selectedCommands;    }    /**     * Create and return the status commands for the executed &lt;Sync&gt;s.     *     * @param syncCommands the Sync commands     *     * @return the status commands in a List collection     */    private List statusForSyncs(Sync[] syncCommands) {        ArrayList ret = new ArrayList();        String uri = null;        Target target = null;        Source source = null;        TargetRef targetRef = null;        SourceRef sourceRef = null;        int statusCode = StatusCode.OK;        for (int i = 0; (  (syncCommands     != null )                        && (i < syncCommands.length)); ++i) {            target = syncCommands[i].getTarget();            source = syncCommands[i].getSource();            //            // A Sync command can be empty....            //            uri = (target==null) ? null : target.getLocURI();            if ((uri == null) || (syncEngine.getClientSource(uri) != null)) {                statusCode = StatusCode.OK;            } else {                statusCode = StatusCode.NOT_FOUND;            }            targetRef = (target == null) ? null : new TargetRef(uri);            sourceRef = (source == null) ? null : new SourceRef(syncCommands[i].getSource());            ret.add(                new Status(                        cmdIdGenerator.next(),                        lastMsgIdFromClient,                        syncCommands[i].getCmdID().getCmdID(),                        syncCommands[i].COMMAND_NAME,                        targetRef,                        sourceRef,                        null,                        null,                        new Data(statusCode),                        new Item[0]                )            );        } // next i        return ret;    }    /**     * Checks that the credentials of the given message are allowed to start a     * session.     *     * @param credential the message     * @param deviceId the deviceId     */    private boolean login(Cred credential, String deviceId) {        //        // May be the credential is already logged in...        //        logout();        //        // If the credential is not specified, create a new "guest" credential        // but only if the property isGuestEnabled is true        //        if (credential == null) {            if (syncEngine.isGuestEnabled()) {                credential = Cred.getGuestCredential();            } else {                validCredentials = true;                guestEnabled = false;                return false;            }        }        Sync4jPrincipal p = Sync4jPrincipal.fromCredential(credential.getData(),                                                           credential.getType(),                                                           deviceId            );        if (syncEngine.login(credential)                && syncEngine.authorize(p, SecurityConstants.RESOURCE_SESSION)) {            loggedCredential = credential;            loggedPrincipal  = p         ;            validCredentials = true;            return true;        }        return false;    }    /**     * Logs out the logged in credential     */    private void logout() {        if (isAuthenticated()) {            syncEngine.logout(loggedCredential);        }        loggedCredential = null;        loggedPrincipal  = null;    }    /**     * Called by the <i>SyncBean</i> when the container release the session.     * It commit the change to the DB, logs out the credential and     * release aquired resources.     */    public void endSession() {        commit();        logout();    }    /**     *  Checks if the message uses a separate initialization or not.     *  If it contains &gt;Alert&lt; and &gt;Sync&lt; tag, it implies Sync with     *  Initialization..     *     *  @param message Message to be checked for Sync with Initialization.     *  @return TRUE (if syncWithInitialization) / FALSE (if not Sync with Init)     *  @throws ProtocolException    */    private boolean checkSyncInit(SyncML message)    throws ProtocolException{        // check for the message of the SyncPackage        // if it contains <alert> & <sync> tag, it implies Sync with Initialization..        // As the Initialization process is completed, only <sync> package is needed        // to be checked, but <alert> tag is also checked for Cross Verification.        AbstractCommand[] clientCommands =            (AbstractCommand[])message.getSyncBody().getCommands().toArray(                                                        new AbstractCommand[0]);        List syncs  = ProtocolUtil.filterCommands(clientCommands    ,                                                  Sync.class);        List alerts = ProtocolUtil.filterCommands(clientCommands    ,                                                  Alert.class);        return ((syncs.size() != 0) && (alerts.size() != 0));    }    /**     * Checks if a message require a response from the client.<p>     * A message requires a response if its body contains no commands other than     * status commands.     *     * @param msg the message to check - NOT NULL and properly constructed     *     * @return true if the message requires a response, false otherwise     *     */    private boolean noMoreResponse(SyncML msg) {        AbstractCommand[] commands =            (AbstractCommand[])msg.getSyncBody().getCommands().toArray(                                                        new AbstractCommand[0]);        for(int i=0; ((commands != null) && (i<commands.length)); ++i) {            if (!Status.COMMAND_NAME.equals(commands[i].getName())) {            return false;        }    }        return true;    }    /**     * Resets the clientMappings map.     */    private void resetClientMappings() {        clientMappings = new HashMap();    }    /**     * Retrieves the existing LUID-GUID mappings for the logged in principal.     * The mappings for all the databases involved in the synchronization are     * loaded.     *     * @return a new <i>ClientMapping</i> object containing the mapping for the     *         given client id     *     * @throws Sync4jException in case of error reading the mapping from the     *         persistent store.     */    private void getClientMappings()    throws Sync4jException {        resetClientMappings();        ClientMapping clientMapping = null;        String uri = null;        try {            PersistentStore ps = syncEngine.getStore();            for (int i = 0; ((syncEngine.getDbs() != null) && (i<syncEngine.getDbs().length)); ++i) {                uri = (syncEngine.getDbs())[i].getName();                clientMapping = new ClientMapping(loggedPrincipal, uri);                ps.read(clientMapping);                clientMappings.put(uri, clientMapping);            }        } catch (PersistentStoreException e) {            log.severe("Unable to read clientMappings from the persistent store");            throw new Sync4jException(e);        }    }    /**     * Stores the LUIG-GUID mappings into the database     *     * @throws Sync4jException in case of database error     */    private void storeClientMappings() throws Sync4jException {        if (clientMappings == null) {            return;        }        try {            PersistentStore ps = syncEngine.getStore();            ClientMapping cm = null;            Iterator i = clientMappings.keySet().iterator();            while (i.hasNext()) {                cm = (ClientMapping)clientMappings.get(i.next());                if (log.isLoggable(Level.FINE)) {                    log.fine("Saving client mapping: " + cm);                }                ps.store(cm);            }        } catch (PersistentStoreException e) {            log.severe("Unable to save clientMappings to the persistent store");            throw new Sync4jException(e);        }    }    /**     * Read the given principal from the store. The principal must be     * already configured with username and device. The current implementation     * reads the following additional informatioin:     * <ul>     *  <li>principal id     * </ul>     *     * @param principal the principal to be read     *     * @throws sync4j.framework.server.store.PersistentStoreException     */    private void readPrincipal(Sync4jPrincipal principal)    throws PersistentStoreException {        assert(principal               != null);        assert(principal.getUsername() != null);        assert(principal.getDeviceId() != null);        PersistentStore ps = syncEngine.getStore();        ps.read(principal);    }    private void readObject(java.io.ObjectInputStream in)    throws java.io.IOException, ClassNotFoundException {        in.defaultReadObject();        log = Sync4jLogger.getLogger();    }    private String getStateName(int state) {        String stateName = "STATE_UNKNOWN";        switch (state) {            case STATE_START                      : stateName = "STATE_START"                     ; break;            case STATE_END                        : stateName = "STATE_END"                       ; break;            case STATE_ERROR                      : stateName = "STATE_ERROR"                     ; break;            case STATE_INITIALIZATION_PROCESSING  : stateName = "STATE_INITIALIZATION_PROCESSING" ; break;            case STATE_INITIALIZATION_PROCESSED   : stateName = "STATE_INITIALIZATION_PROCESSED"  ; break;            case STATE_SYNCHRONIZATION_PROCESSING : stateName = "STATE_SYNCHRONIZATION_PROCESSING"; break;            case STATE_SYNCHRONIZATION_PROCESSED  : stateName = "STATE_SYNCHRONIZATION_PROCESSED" ; break;            case STATE_SYNCHRONIZATION_COMPLETION : stateName = "STATE_SYNCHRONIZATION_COMPLETION"; break;        }        return stateName;    }    public SyncState getSyncState() {        return this.syncState;    }    /**     * This class compare two StatusCommand object in according to     * the cmdRef     */    private static class StatusComparator implements java.util.Comparator {        private StatusComparator() {        }        public int compare(Object o1, Object o2) {            Object value1 = null;            Object value2 = null;            value1 = new Integer(((Status)o1).getCmdRef());            value2 = new Integer(((Status)o2).getCmdRef());            return ( (Integer)value1).compareTo((Integer)value2);        }    }}

⌨️ 快捷键说明

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