KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > sync4j > framework > protocol > SyncInitialization


1 /**
2  * Copyright (C) 2003-2005 Funambol
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17  */

18 package sync4j.framework.protocol;
19
20 import java.util.Arrays JavaDoc;
21 import java.util.ArrayList JavaDoc;
22 import java.util.Iterator JavaDoc;
23 import java.util.List JavaDoc;
24 import java.util.Hashtable JavaDoc;
25
26 import sync4j.framework.core.*;
27 import sync4j.framework.database.Database;
28
29 import sync4j.framework.protocol.SyncPackage;
30 import sync4j.framework.protocol.ProtocolUtil;
31 import sync4j.framework.protocol.v11.InitializationRequirements;
32
33 import sync4j.framework.security.Sync4jPrincipal;
34
35 /**
36  * Represents the Initialization package of the SyncML protocol.
37  *
38  * Example:
39  * <pre>
40  * SyncInitialization syncInit = new SyncInitialization(header, body);
41  * ... do something ...
42  * syncInit.setServerCapabilities(serverCapabilities);
43  * syncInit.setAuthorizedStatusCode(StatusCode.AUTHENTICATION_ACCEPTED);
44  * syncInit.setClientCapabilitiesStatusCode(StatusCode.OK);
45  * ... other initializations ...
46  * Message response = syncInit.getResponse();
47  * </pre>
48  *
49  * @author Stefano Fornari @ Funambol
50  *
51  * @version $Id: SyncInitialization.java,v 1.46 2005/05/12 14:04:10 luigiafassina Exp $
52  *
53  * @see SyncPackage
54  */

55 public class SyncInitialization
56 extends SyncPackage
57 {
58     /**
59      * Contains the request for server capabilities sent by the client
60      * (null means capabilities not required)
61      */

62     private Get serverCapabilitiesRequest = null;
63
64     /**
65      * The device capabilities sent by the client.
66      */

67     private Put clientCapabilities = null;
68
69     public DevInf getClientDeviceInfo() throws ProtocolException {
70         if (clientCapabilities != null) {
71             DevInfItem item = (DevInfItem)this.clientCapabilities.getItems().get(0);
72             return item.getDevInfData().getDevInf();
73         }
74         return null;
75     }
76
77     /**
78      * Caches the commands sent by the client.It is set during the
79      * checking of the requirements.
80      */

81     private AbstractCommand[] clientCommands = null;
82
83     public AbstractCommand[] getClientCommands() {
84         return clientCommands;
85     }
86
87     /**
88      * Caches the alert command sent by the client. It is set during the
89      * checking of the requirements.
90      */

91     private Alert[] clientAlerts = null;
92
93     public Alert[] getClientAlerts() {
94         return clientAlerts;
95     }
96
97     /**
98      * Caches the sync command sent by the client to create Status in the case
99      * of client is not authenticated
100      */

101     private Sync[] clientSyncs = null;
102
103     /**
104      * Client Capabilities status code
105      */

106     private int clientCapabilitiesStatusCode = -1;
107
108     public int getClientCapabilitiesStatusCode() {
109         return this.clientCapabilitiesStatusCode;
110     }
111
112     public void setClientCapabilitiesStatusCode(int clientCapabilitiesStatusCode) {
113         this.clientCapabilitiesStatusCode = clientCapabilitiesStatusCode;
114     }
115
116     /**
117      * Server capabilities
118      */

119     private DevInf serverCapabilities = null;
120
121     public void setServerCapabilities(DevInf capabilities) {
122         this.serverCapabilities = capabilities;
123     }
124
125     public DevInf getServerCapabilities() {
126         return this.serverCapabilities;
127     }
128
129     /**
130      * Databases that the server wants to synchronized. They can be differnt
131      * from the databases the client has requested to be synchronized.
132      */

133     private Database[] databases = null;
134
135     public void setDatabases(Database[] databases) {
136         this.databases = databases;
137     }
138
139     public Database[] getDatabases() {
140         return this.databases;
141     }
142
143     /**
144      * Does the server require client capabilities?
145      */

146     private boolean clientCapabilitiesRequired = false;
147
148     public void setClientCapabilitiesRequired(boolean clientCapabilitiesRequired) {
149         this.clientCapabilitiesRequired = clientCapabilitiesRequired;
150     }
151
152     public boolean isClientCapabilitiesRequired() {
153         return this.clientCapabilitiesRequired;
154     }
155
156     /**
157      * Authorized status code - used in building response message
158      */

159     private int authorizedStatusCode = -1;
160
161     public void setAuthorizedStatusCode(int authorizedStatusCode) {
162         this.authorizedStatusCode = authorizedStatusCode;
163     }
164
165     /**
166      * Did the client challenge for authentication? If so, this property contains
167      * client Chal
168      */

169     private Chal clientChal = null;
170
171     /**
172      * Gets clientChal
173      *
174      * @return the given client Chal
175      */

176     public Chal getClientChal() {
177         return clientChal;
178     }
179
180     /**
181      * Server authentication type
182      */

183     private String JavaDoc clientAuth = null;
184
185     /**
186      * Sets server authentication type required to the client to authenticate it
187      *
188      * @param clientAuth server authentication type
189      */

190     public void setClientAuth(String JavaDoc clientAuth) {
191         this.clientAuth = clientAuth;
192     }
193
194     /**
195      * Next nonce for MD5 authentication
196      */

197     private NextNonce nextNonce = null;
198
199     /**
200      * Sets nextNonce
201      *
202      * @param nextNonce the next nonce
203      */

204     public void setNextNonce(NextNonce nextNonce) {
205         this.nextNonce = nextNonce;
206     }
207
208     /**
209      * Did the client challenge for authentication? If so, this property must
210      * contain server credentials.
211      */

212     private Cred serverCredentials;
213
214     /**
215      * Sets serverCredentials
216      *
217      * @param serverCredentials the new server credentials
218      */

219     public void setServerCredentials(Cred serverCredentials) {
220         this.serverCredentials = serverCredentials;
221     }
222
223     /**
224      * Gets serverCredentials
225      */

226     public Cred getServerCredentials() {
227         return serverCredentials;
228     }
229
230     // ---------------------------------------------------------- Command status
231

232     /**
233      * The map containing the status of the commands
234      */

235     private Hashtable JavaDoc commandStatus = new Hashtable JavaDoc();
236
237     /**
238      * Sets the status code for the given command.
239      *
240      * @param cmd the command
241      * @param statusCode the status code
242      */

243     public void setStatusCodeForCommand(AbstractCommand cmd, int statusCode) {
244         setStatusCodeForCommand(cmd.getCmdID().getCmdID(), statusCode);
245     }
246
247     /**
248      * Sets the status code for the command identified by the given id.
249      *
250      * @param cmdId the command id
251      * @param statusCode the status code
252      */

253     public void setStatusCodeForCommand(String JavaDoc cmdId, int statusCode) {
254         commandStatus.put(cmdId, new Integer JavaDoc(statusCode));
255     }
256
257     /**
258      * Returns the status code for the given command. The status code must be
259      * previously set with <i>setStatusCodeForCommand()</i>. If no status code
260      * is associated to the given command, the default status code is returned.
261      *
262      * @param cmd the command
263      * @param defaultCode the default status code
264      *
265      * @return the status code for the command if previously set, the default
266      * status code otherwise
267      */

268     public int getStatusCodeForCommand(AbstractCommand cmd, int defaultCode) {
269         String JavaDoc cmdId = cmd.getCmdID().getCmdID();
270
271         return getStatusCodeForCommand(cmdId, defaultCode);
272
273     }
274
275     /**
276      * The same as <i>getStatusCodeForCommand(AbstractCommand, int) but passing
277      * in the command id instead of the command.
278      *
279      * @param cmdId the command id
280      * @param defaultCode
281      *
282      * @return the status code for the command if previously set, the default
283      * status code otherwise
284      */

285     public int getStatusCodeForCommand(String JavaDoc cmdId, int defaultCode) {
286         Integer JavaDoc statusCode = (Integer JavaDoc)commandStatus.get(cmdId);
287
288         return (statusCode == null) ? defaultCode : statusCode.intValue();
289     }
290
291
292     // ------------------------------------------------------------ Constructors
293

294     /**
295       *
296       * @param syncHeader the header of the syncronization packet
297       * @param syncBody the body of the syncronization packet
298       *
299       * @throws ProtocolException
300       */

301     public SyncInitialization(final SyncHdr syncHeader,
302                               final SyncBody syncBody )
303     throws ProtocolException {
304         super(syncHeader, syncBody);
305         checkRequirements();
306     }
307
308     // ------------------------------------------------------ Public methods
309

310     /**
311      * Alerts specifying the database to be synchronized could be more
312      * then one. Each can contains more than one item, which specifies
313      * a single database. This method selects the items containing the
314      * databases regardless in what alert command they where included.
315      *
316      * @param principal the principal for which we want the databases
317      *
318      * @return an array of Database objects
319      */

320     public Database[] getDatabasesToBeSynchronized(Sync4jPrincipal principal) {
321         ArrayList JavaDoc dbList = new ArrayList JavaDoc();
322
323         Database db = null;
324         Item[] items = null;
325         Meta meta = null;
326         for (int i=0; ((clientAlerts != null) && (i < clientAlerts.length)); ++i) {
327             //
328
// Only database synchronization alerts are selected
329
//
330
if (!AlertCode.isInitializationCode(clientAlerts[i].getData())) {
331                 continue;
332             }
333
334             items = (Item[])clientAlerts[i].getItems().toArray(new Item[0]);
335             for (int j=0; ((items != null) && (j<items.length)); ++j) {
336                 meta = items[j].getMeta();
337                 Anchor anchor = meta.getAnchor();
338
339                 //
340
// If the anchor does not exists, the alert does not represent
341
// a database to be synchronized.
342
//
343
if (anchor == null) {
344                     continue;
345                 }
346
347                 //
348
// NOTE: the target becomes the database source and vice-versa
349
//
350
db = new Database(
351                          items[j].getTarget().getLocURI() ,
352                          null /* type */ ,
353                          ProtocolUtil.source2Target(items[j].getSource()),
354                          ProtocolUtil.target2Source(items[j].getTarget()),
355                          anchor ,
356                          principal
357                      );
358                 db.setMethod(clientAlerts[i].getData());
359                 db.setAlertCommand(clientAlerts[i]);
360
361                 dbList.add(db);
362             } // next j
363
} // next i
364

365         int dbSize = dbList.size();
366         Database[] dbArray = new Database[dbSize];
367         for (int i=0; i<dbSize; i++) {
368             dbArray[i] = (Database)dbList.get(i);
369         }
370         return dbArray;
371     }
372
373     // -------------------------------------------------------------------------
374

375     /**
376      * Checks that all requirements regarding the header of the initialization
377      * packet are respected.
378      *
379      * @throws ProtocolException
380      */

381     public void checkHeaderRequirements()
382     throws ProtocolException {
383         InitializationRequirements.checkDTDVersion (syncHeader.getVerDTD() );
384         InitializationRequirements.checkProtocolVersion(syncHeader.getVerProto());
385         InitializationRequirements.checkSessionId (syncHeader.getSessionID());
386         InitializationRequirements.checkMessageId (syncHeader.getMsgID() );
387         InitializationRequirements.checkTarget (syncHeader.getTarget() );
388         InitializationRequirements.checkSource (syncHeader.getSource() );
389     }
390
391     /**
392      * Checks that all requirements regarding the body of the initialization
393      * packet are respected.
394      *
395      * @throws ProtocolException
396      */

397     public void checkBodyRequirements()
398     throws ProtocolException {
399         ArrayList JavaDoc listAlerts = new ArrayList JavaDoc();
400         ArrayList JavaDoc mergedClientCommands = new ArrayList JavaDoc();
401
402         AbstractCommand[] allClientCommands =
403             (AbstractCommand[])syncBody.getCommands().toArray(
404                                                         new AbstractCommand[0]);
405
406         //
407
// Extracts and checks alert commands
408
//
409
ArrayList JavaDoc alertList = ProtocolUtil.filterCommands(allClientCommands ,
410                                                           Alert.class);
411         int size = alertList.size();
412         Alert[] alerts = new Alert[size];
413         for (int i=0; i < size; i++) {
414             alerts[i] = (Alert)alertList.get(i);
415
416             InitializationRequirements.checkAlertCommand(alerts[i]);
417
418             //
419
// Check if there are more Alert commands for the same syncsource because
420
// it must have a single Alert for SyncSource.
421
//
422
String JavaDoc locURI = ((Item)(alerts[i].getItems().get(0))).getTarget().getLocURI();
423             int sizeLA = listAlerts.size();
424             boolean isPresent = false;
425             for (int y=0; y < sizeLA; y++) {
426                 String JavaDoc locURICached =
427                     ((Item)(((Alert)listAlerts.get(y)).getItems().get(0))).getTarget().getLocURI();
428
429                 if (locURICached.equals(locURI)) {
430                     isPresent = true;
431                     //
432
// This is not a client Alert to process into sync, but
433
// its Status command must be created.
434
//
435
mergedClientCommands.add(alerts[i]);
436                     break;
437                 }
438             }
439             if (!isPresent) {
440             listAlerts.add(alerts[i]);
441          }
442          }
443
444         //
445
// All alerts are OK => they can be cached
446
//
447
clientAlerts = (Alert[])listAlerts.toArray(new Alert[0]);
448         mergedClientCommands.addAll(listAlerts);
449
450         ArrayList JavaDoc clientCapabilitiesList =
451             ProtocolUtil.filterCommands(allClientCommands, Put.class);
452
453         if ((clientCapabilities == null) && (clientCapabilitiesList.size()>0)) {
454             InitializationRequirements.checkCapabilities((Put)clientCapabilitiesList.get(0) ,
455                                                          InitializationRequirements.CLIENT_CAPABILITIES);
456             clientCapabilities = (Put)clientCapabilitiesList.get(0);
457         }
458         mergedClientCommands.addAll(clientCapabilitiesList);
459
460         ArrayList JavaDoc capabilitiesRequest =
461             ProtocolUtil.filterCommands(allClientCommands, Get.class);
462
463         if ((capabilitiesRequest != null) && (capabilitiesRequest.size()>0)) {
464             InitializationRequirements.checkCapabilitiesRequest((Get)capabilitiesRequest.get(0));
465             serverCapabilitiesRequest = (Get)capabilitiesRequest.get(0);
466         }
467         mergedClientCommands.addAll(capabilitiesRequest);
468
469         //
470
// Extracts Sync commands
471
//
472
ArrayList JavaDoc listSync = ProtocolUtil.filterCommands(allClientCommands, Sync.class);
473         clientSyncs = (Sync[])listSync.toArray(new Sync[0]);
474
475         clientCommands =
476             (AbstractCommand[])mergedClientCommands.toArray(new AbstractCommand[0]);
477
478     }
479
480
481     /**
482      * Constructs a proper response message.<br>
483      * NOTES
484      * <ul>
485      * <li> If server capabilities are not required, they are not sent (in
486      * the SyncML protocol the server MAY send not required capabilities)
487      * </ul>
488      *
489      * @param msgId the msg id of the response
490      * @return the response message
491      *
492      * @throws ProtocolException in case of error or inconsistency
493      */

494     public SyncML getResponseMessage(String JavaDoc msgId) throws ProtocolException {
495         SyncHdr responseHeader = getResponseHeader(msgId);
496         AbstractCommand[] commands =
497             (AbstractCommand[]) getResponseCommands(msgId).toArray(new AbstractCommand[0]);
498         SyncBody responseBody = new SyncBody(
499             commands,
500             isFlag(Flags.FLAG_FINAL_MESSAGE)
501         );
502
503         try {
504             return new SyncML(responseHeader, responseBody);
505         } catch (RepresentationException e) {
506             //
507
// It should never happen !!!!
508
//
509
throw new ProtocolException("Unexpected error", e);
510         }
511     }
512
513     /**
514      * Returns the response commands in response to the incoming initialization
515      * message.
516      *
517      * @param msgId the message id to use
518      *
519      * @return an array of AbstractCommand
520      *
521      * @throws ProtocolException in case of errors
522      */

523     public List JavaDoc getResponseCommands(String JavaDoc msgId)
524     throws ProtocolException {
525         ArrayList JavaDoc statusList = new ArrayList JavaDoc();
526         ArrayList JavaDoc commandList = new ArrayList JavaDoc();
527
528         //
529
// Constructs all required response commands.
530
//
531
// NOTE: if NoResp is specified in the header element, than no
532
// response commands must be returned regardless NoResp is
533
// specified or not in subsequent commands
534
//
535

536         if (syncHeader.isNoResp() == false) {
537             //
538
// Session authorization
539
//
540
TargetRef[] targetRefs = new TargetRef[] { new TargetRef(syncHeader.getTarget().getLocURI()) };
541             SourceRef[] sourceRefs = new SourceRef[] { new SourceRef(syncHeader.getSource().getLocURI()) };
542
543             //
544
// If the session is not authenticated, a Chal element must be returned
545
//
546
Chal chal = null;
547             if (authorizedStatusCode != StatusCode.AUTHENTICATION_ACCEPTED) {
548                 if (clientAuth.equalsIgnoreCase(Cred.AUTH_TYPE_BASIC)) {
549                     chal = Chal.getBasicChal();
550                 }
551             }
552
553             //
554
// The MD5 authentication always requires the chal element
555
//
556
if (clientAuth.equalsIgnoreCase(Cred.AUTH_TYPE_MD5)) {
557                 chal = Chal.getMD5Chal();
558                 chal.setNextNonce(nextNonce);
559             }
560             Status statusCommand = new Status(
561                                     idGenerator.next() ,
562                                     syncHeader.getMsgID() ,
563                                     "0" /* command ref */ ,
564                                     "SyncHdr" /* see SyncML specs */ ,
565                                     targetRefs ,
566                                     sourceRefs ,
567                                     null /* credential */ ,
568                                     chal ,
569                                     new Data(String.valueOf(authorizedStatusCode)),
570                                     new Item[0]
571                                    );
572
573             statusList.add(statusCommand);
574
575             //
576
// Status for each command that requested it (it is supposed each
577
// command has bean already checked).
578
//
579
for (int i=0; ((clientCommands != null) && (i < clientCommands.length)); ++i) {
580                 if (clientCommands[i].isNoResp()) {
581                     continue;
582                 }
583
584                 targetRefs = null;
585                 sourceRefs = null;
586                 if (clientCommands[i] instanceof ItemizedCommand) {
587                     Item[] items = (Item[])((ItemizedCommand)clientCommands[i]).getItems().toArray(new Item[0]);
588
589                     ArrayList JavaDoc trefs = new ArrayList JavaDoc();
590                     ArrayList JavaDoc srefs = new ArrayList JavaDoc();
591                     Target t;
592                     Source s;
593                     for (int j=0; j<items.length; ++j) {
594                         t = items[j].getTarget();
595                         s = items[j].getSource();
596
597                         if (t != null) {
598                             trefs.add(new TargetRef(t));
599                         }
600                         if (s != null) {
601                             srefs.add(new SourceRef(s));
602                         }
603                     } // next j
604

605                     if (trefs.size() > 0) {
606                         targetRefs = (TargetRef[])trefs.toArray(new TargetRef[trefs.size()]);
607                     }
608                     if (srefs.size() > 0) {
609                         sourceRefs = (SourceRef[])srefs.toArray(new SourceRef[srefs.size()]);
610                     }
611
612                 }
613
614                 String JavaDoc commandReference = clientCommands[i].getCmdID().getCmdID();
615                 int status = getStatusCodeForCommand(clientCommands[i], StatusCode.OK);
616
617                 Item[] items = new Item[0];
618
619                 //
620
// Within Response of Alert, Item must contain the NEXT Anchor.
621
// NOTE: a database represents the server point of view so that
622
// the target is the client database and the source the
623
// server database.
624
//
625
if (clientCommands[i] instanceof Alert) {
626                     for(int j=0; (databases != null) && (j<databases.length) ; ++j) {
627                         if((databases[j].getSource().getLocURI()).equals(targetRefs[0].getValue())){
628                             items = new Item[1];
629
630                             Anchor alertAnchor =
631                                        new Anchor(null, databases[j].getNext());
632
633                             ComplexData data = new ComplexData();
634                             data.setAnchor(alertAnchor);
635
636                             items[0] = new Item(
637                                null, // target
638
null, // source
639
null, // meta
640
data,
641                                false //MoreData
642
);
643
644                             break;
645                         }
646                     }
647                 }
648
649                 statusCommand = new Status(
650                                     idGenerator.next() ,
651                                     syncHeader.getMsgID() ,
652                                     commandReference ,
653                                     clientCommands[i].getName() ,
654                                     targetRefs ,
655                                     sourceRefs ,
656                                     null /* credential */ ,
657                                     null /* challenge */ ,
658                                     new Data(status) ,
659                                     items
660                                 );
661
662                 statusList.add(statusCommand);
663             } // next i
664

665             //
666
// If status is not Authorized then create status for all commands
667
// even if Sync command
668
//
669
if (authorizedStatusCode != StatusCode.AUTHENTICATION_ACCEPTED) {
670                 if (clientSyncs != null && clientSyncs.length > 0) {
671                     for (int y=0; y<clientSyncs.length; y++) {
672                         Sync sync = (Sync)clientSyncs[y];
673                         ArrayList JavaDoc al = sync.getCommands();
674
675                         String JavaDoc cmdRef = clientSyncs[y].getCmdID().getCmdID();
676                         TargetRef[] tRefs = null;
677                         if (clientSyncs[y].getTarget() != null) {
678                             tRefs = new TargetRef[] { new TargetRef(clientSyncs[y].getTarget().getLocURI()) };
679                         }
680
681                         SourceRef[] sRefs = null;
682                         if (clientSyncs[y].getSource() != null) {
683                             sRefs = new SourceRef[] { new SourceRef(clientSyncs[y].getSource().getLocURI()) };
684                         }
685
686                         statusCommand = new Status(
687                                             idGenerator.next() ,
688                                             syncHeader.getMsgID() ,
689                                             cmdRef ,
690                                             clientSyncs[y].getName() ,
691                                             tRefs ,
692                                             sRefs ,
693                                             null /* credential */ ,
694                                             null /* challenge */ ,
695                                             new Data(authorizedStatusCode) ,
696                                             new Item[0]
697                                         );
698
699                         statusList.add(statusCommand);
700
701                         if (al != null) {
702                             AbstractCommand[] absCmd = (AbstractCommand[])sync.getCommands().toArray(new AbstractCommand[0]);
703
704                             for (int z=0; absCmd != null && z<absCmd.length; z++) {
705                                 cmdRef = absCmd[z].getCmdID().getCmdID();
706
707                                 statusCommand = new Status(
708                                                 idGenerator.next() ,
709                                                 syncHeader.getMsgID() ,
710                                                 cmdRef ,
711                                                 absCmd[z].getName() ,
712                                                 tRefs ,
713                                                 sRefs ,
714                                                 null /* credential */ ,
715                                                 null /* challenge */ ,
716                                                 new Data(authorizedStatusCode),
717                                                 new Item[0]
718                                             );
719
720                                 statusList.add(statusCommand);
721                             }
722                         }
723                     }
724                 }
725             }
726         } // end if syncHeader.getNoResponse() == false
727

728         //
729
// sorting statuses by cmdref and adding the sorted statuses to commandList
730
//
731
AbstractCommand[] cmds = (AbstractCommand[])statusList.toArray(new AbstractCommand[0]);
732         ProtocolUtil.sortStatusCommand(cmds);
733         commandList.addAll(Arrays.asList(cmds));
734
735         //
736
// Server capabilities
737
//
738
if ((serverCapabilitiesRequest != null) && (authorizedStatusCode == StatusCode.AUTHENTICATION_ACCEPTED)) {
739             if (serverCapabilities == null) {
740                 throw new ProtocolException("Error in creating a response: server capabilities not set (use setServerCapabilities())");
741             }
742
743             String JavaDoc commandReference =
744                 serverCapabilitiesRequest.getCmdID().getCmdID();
745
746             Meta meta = serverCapabilitiesRequest.getMeta();
747             if (meta == null) {
748                 meta = new Meta();
749                 meta.setType(Constants.MIMETYPE_SYNCML_DEVICEINFO_XML);
750             }
751
752             ComplexData data = new ComplexData();
753             data.setDevInf(serverCapabilities);
754
755             Source source = ProtocolUtil.target2Source(
756                                   ((Item)(serverCapabilitiesRequest.getItems().get(0))).getTarget()
757                               );
758             Item[] capabilities = new Item[] { new Item(null, source, null, data, false) };
759
760             Results resultsCommand = new Results(
761                                                 idGenerator.next() ,
762                                                 syncHeader.getMsgID(),
763                                                 commandReference ,
764                                                 meta /* meta */ ,
765                                                 null /* target ref */,
766                                                 null /* source ref */,
767                                                 capabilities
768                                             );
769             commandList.add(resultsCommand);
770         }
771
772         //
773
// Alerts for each database to be synchronized
774
//
775
for (int i=0; (databases != null) &&
776                       (i<databases.length); ++i ) {
777
778             if (databases[i].isOkStatusCode()) {
779
780                 Alert alertCommand =
781                 ProtocolUtil.createAlertCommand(idGenerator.next(),
782                                                 false ,
783                                                 null ,
784                                                 databases[i] );
785                         Item item =
786                             (Item)databases[i].getAlertCommand().getItems().get(0);
787                         Long JavaDoc maxObjSize = item.getMeta().getMaxObjSize();
788                         ((Item)alertCommand.getItems().get(0)).getMeta().setMaxObjSize(maxObjSize);
789
790                 commandList.add(alertCommand);
791             }
792         }
793
794         //
795
// If client capabilities are required but not provided, a get command
796
// must be added.
797
//
798
if (clientCapabilitiesRequired && (clientCapabilities == null)) {
799             Meta meta = new Meta();
800             meta.setType(Constants.MIMETYPE_SYNCML_DEVICEINFO_XML);
801
802             Target target = new Target( InitializationRequirements.CAPABILITIES_TARGET,
803                                         InitializationRequirements.CAPABILITIES_TARGET);
804             Item[] items = new Item[1];
805
806             items[0] = new Item(
807                            target,
808                            null , /* source */
809                            null , /* meta */
810                            null , /* data */
811                            false /* moreData*/
812                            );
813             Get getCommand = new Get(
814                                 idGenerator.next() ,
815                                 false /* no response */,
816                                 null /* language */,
817                                 null /* credentials */,
818                                 meta ,
819                                 items
820                              );
821             commandList.add(getCommand);
822         }
823
824         Iterator JavaDoc i = commandList.iterator();
825         while (i.hasNext()) {
826             AbstractCommand c = (AbstractCommand)i.next();
827             if (authorizedStatusCode != StatusCode.AUTHENTICATION_ACCEPTED) {
828                 if (c instanceof Status) {
829                     ((Status)c).setData(new Data(String.valueOf(authorizedStatusCode)));
830                 }
831             }
832         }
833
834         return commandList;
835     }
836
837     /**
838      * Returns the response SyncHdr to return in response of the incoming SyncML
839      * message.
840      *
841      * @param msgId the message id to use
842      *
843      * @return the SyncHdr object
844      *
845      * @thorws ProtocolException in case of errors
846      */

847     public SyncHdr getResponseHeader(String JavaDoc msgId)
848     throws ProtocolException {
849         //
850
// Constructs return message
851
//
852
Target target = new Target(syncHeader.getSource().getLocURI(),
853                                    syncHeader.getSource().getLocName());
854         Source source = new Source(syncHeader.getTarget().getLocURI(),
855                                    syncHeader.getTarget().getLocName());
856         return new SyncHdr (
857                    getDTDVersion() ,
858                    getProtocolVersion() ,
859                    syncHeader.getSessionID(),
860                    msgId ,
861                    target ,
862                    source ,
863                    null /* response URI */ ,
864                    false ,
865                    serverCredentials ,
866                    null
867                 );
868     }
869 }
Popular Tags