KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mmbase > applications > packaging > providerhandlers > HttpProvider


1 /*
2  * This software is OSI Certified Open Source Software.
3  * OSI Certified is a certification mark of the Open Source Initiative.
4  * The license (Mozilla version 1.0) can be read at the MMBase site.
5  * See http://www.MMBase.org/license
6  */

7 package org.mmbase.applications.packaging.providerhandlers;
8
9 import java.io.BufferedInputStream JavaDoc;
10 import java.io.BufferedOutputStream JavaDoc;
11 import java.io.BufferedReader JavaDoc;
12 import java.io.DataOutputStream JavaDoc;
13 import java.io.File JavaDoc;
14 import java.io.FileOutputStream JavaDoc;
15 import java.io.InputStreamReader JavaDoc;
16 import java.net.HttpURLConnection JavaDoc;
17 import java.net.URL JavaDoc;
18 import java.util.Iterator JavaDoc;
19 import java.util.jar.JarEntry JavaDoc;
20 import java.util.jar.JarFile JavaDoc;
21
22 import org.mmbase.applications.packaging.BundleManager;
23 import org.mmbase.applications.packaging.PackageManager;
24 import org.mmbase.applications.packaging.ShareManager;
25 import org.mmbase.applications.packaging.bundlehandlers.BundleInterface;
26 import org.mmbase.applications.packaging.packagehandlers.PackageInterface;
27 import org.mmbase.applications.packaging.projects.creators.CreatorInterface;
28 import org.mmbase.applications.packaging.util.ExtendedDocumentReader;
29 import org.mmbase.util.Encode;
30 import org.mmbase.util.XMLEntityResolver;
31 import org.mmbase.util.logging.Logger;
32 import org.mmbase.util.logging.Logging;
33 import org.w3c.dom.Element JavaDoc;
34 import org.w3c.dom.NamedNodeMap JavaDoc;
35 import org.xml.sax.InputSource JavaDoc;
36
37 /**
38  * HttpProvider, Handler for Http Providers. gets packages and bundles from
39  * the provider and feeds them to the package and bundle managers.
40  *
41  * @author Daniel Ockeloen (MMBased)
42  */

43 public class HttpProvider extends BasicProvider implements ProviderInterface {
44     private static Logger log = Logging.getLoggerInstance(HttpProvider.class);
45
46     private String JavaDoc name;
47     private String JavaDoc method;
48     private String JavaDoc maintainer;
49     private String JavaDoc account = "guest";
50     private String JavaDoc password = "guest";
51
52     /**
53      * DTD resource filename of the sharedpackages DTD version 1.0
54      */

55     public final static String JavaDoc DTD_SHAREDPACKAGES_1_0 = "sharedpackages_1_0.dtd";
56
57     /**
58      * Public ID of the sharedpackages DTD version 1.0
59      */

60     public final static String JavaDoc PUBLIC_ID_SHAREDPACKAGES_1_0 = "-//MMBase//DTD sharedpackages config 1.0//EN";
61
62
63     /**
64      * Register the Public Ids for DTDs used by DatabaseReader
65      * This method is called by XMLEntityResolver.
66      */

67     public static void registerPublicIDs() {
68         XMLEntityResolver.registerPublicID(PUBLIC_ID_SHAREDPACKAGES_1_0, DTD_SHAREDPACKAGES_1_0, HttpProvider.class);
69     }
70
71
72
73     /**
74      *Constructor for the HttpProvider object
75      */

76     public HttpProvider() { }
77
78
79     /**
80      * Description of the Method
81      *
82      * @param n Description of the Parameter
83      * @param name Description of the Parameter
84      * @param method Description of the Parameter
85      * @param maintainer Description of the Parameter
86      */

87     public void init(org.w3c.dom.Node JavaDoc n, String JavaDoc name, String JavaDoc method, String JavaDoc maintainer) {
88         super.init(n, name, method, maintainer);
89         org.w3c.dom.Node JavaDoc n2 = xmlnode.getFirstChild();
90         while (n2 != null) {
91             if (n2.getNodeName().equals("path")) {
92                 org.w3c.dom.Node JavaDoc n3 = n2.getFirstChild();
93                 path = n3.getNodeValue();
94             }
95             if (n2.getNodeName().equals("description")) {
96                 org.w3c.dom.Node JavaDoc n3 = n2.getFirstChild();
97                 if (n3 != null) {
98                     description = n3.getNodeValue();
99                 }
100             }
101             if (n2.getNodeName().equals("account")) {
102                 org.w3c.dom.Node JavaDoc n3 = n2.getFirstChild();
103                 account = n3.getNodeValue();
104             }
105             if (n2.getNodeName().equals("password")) {
106                 org.w3c.dom.Node JavaDoc n3 = n2.getFirstChild();
107                 password = n3.getNodeValue();
108             }
109             n2 = n2.getNextSibling();
110         }
111         baseScore = 2000;
112     }
113
114
115     /**
116      * Description of the Method
117      *
118      * @param name Description of the Parameter
119      * @param method Description of the Parameter
120      * @param maintainer Description of the Parameter
121      * @param path Description of the Parameter
122      */

123     public void init(String JavaDoc name, String JavaDoc method, String JavaDoc maintainer, String JavaDoc path) {
124         super.init(name, method, maintainer, path);
125         // this.account=account;
126
// this.password=password;
127
baseScore = 2000;
128     }
129
130
131     /**
132      * Sets the account attribute of the HttpProvider object
133      *
134      * @param account The new account value
135      */

136     public void setAccount(String JavaDoc account) {
137         this.account = account;
138     }
139
140
141     /**
142      * Gets the account attribute of the HttpProvider object
143      *
144      * @return The account value
145      */

146     public String JavaDoc getAccount() {
147         return account;
148     }
149
150
151     /**
152      * Sets the password attribute of the HttpProvider object
153      *
154      * @param password The new password value
155      */

156     public void setPassword(String JavaDoc password) {
157         this.password = password;
158     }
159
160
161     /**
162      * Gets the password attribute of the HttpProvider object
163      *
164      * @return The password value
165      */

166     public String JavaDoc getPassword() {
167         return password;
168     }
169
170
171     /**
172      * Gets the packages attribute of the HttpProvider object
173      */

174     public void getPackages() {
175         signalUpdate();
176
177         String JavaDoc url = path + "?user=" + account + "&password=" + password;
178         if (ShareManager.getCallbackUrl() != null) {
179             url += "&callbackurl=" + Encode.encode("ESCAPE_URL_PARAM",ShareManager.getCallbackUrl());
180         }
181         try {
182             URL JavaDoc includeURL = new URL JavaDoc(url);
183             HttpURLConnection JavaDoc connection = (HttpURLConnection JavaDoc) includeURL.openConnection();
184             BufferedInputStream JavaDoc input = new BufferedInputStream JavaDoc(connection.getInputStream());
185             ExtendedDocumentReader reader = new ExtendedDocumentReader(new InputSource JavaDoc(input), HttpProvider.class);
186             if (reader != null) {
187                 try {
188                     for (Iterator JavaDoc ns = reader.getChildElements("sharedpackages", "package"); ns.hasNext(); ) {
189                         Element JavaDoc e = (Element JavaDoc) ns.next();
190
191                         NamedNodeMap JavaDoc nm = e.getAttributes();
192                         if (nm != null) {
193                             String JavaDoc name = null;
194                             String JavaDoc type = null;
195                             String JavaDoc version = null;
196                             String JavaDoc date = null;
197
198                             // decode name
199
org.w3c.dom.Node JavaDoc n2 = nm.getNamedItem("name");
200                             if (n2 != null) {
201                                 name = n2.getNodeValue();
202                             }
203
204                             // decode the type
205
n2 = nm.getNamedItem("type");
206                             if (n2 != null) {
207                                 type = n2.getNodeValue();
208                             }
209
210                             // decode the maintainer
211
n2 = nm.getNamedItem("maintainer");
212                             if (n2 != null) {
213                                 maintainer = n2.getNodeValue();
214                             }
215
216                             // decode the version
217
n2 = nm.getNamedItem("version");
218                             if (n2 != null) {
219                                 version = n2.getNodeValue();
220                             }
221
222                             // decode the creation date
223
n2 = nm.getNamedItem("creation-date");
224                             if (n2 != null) {
225                                 date = n2.getNodeValue();
226                             }
227
228                             Element JavaDoc e2 = reader.getElementByPath(e, "package.path");
229                             org.w3c.dom.Node JavaDoc pathnode = e2.getFirstChild();
230                             String JavaDoc pkgpath = pathnode.getNodeValue();
231                             if (type.indexOf("bundle/") == 0) {
232                                 BundleInterface bun = BundleManager.foundBundle(this, e, name, type, maintainer, version, date, pkgpath);
233                                 // check for included packages in the bundle
234
findIncludedPackages(bun, e, pkgpath, date);
235                             } else {
236                                 PackageManager.foundPackage(this, e, name, type, maintainer, version, date, pkgpath);
237                             }
238                         }
239                     }
240                 } catch (Exception JavaDoc f) {
241                     log.error("something went wrong while decoding sharedpackagefile : " + url);
242                     f.printStackTrace();
243                 }
244             } else {
245                 log.error("can't get a valid reader for sharedpackagefile : " + url);
246             }
247             setState("up");
248         } catch (Exception JavaDoc e) {
249             // ignoring errors since well that servers are down is
250
// not a error in this concept.
251
log.error("can't get sharedpackagefile : " + url);
252             //e.printStackTrace();
253
setState("down");
254         }
255     }
256
257
258     /**
259      * Gets the includedPackageJarFile attribute of the HttpProvider object
260      *
261      * @param path Description of the Parameter
262      * @param id Description of the Parameter
263      * @param version Description of the Parameter
264      * @param packageid Description of the Parameter
265      * @param packageversion Description of the Parameter
266      * @return The includedPackageJarFile value
267      */

268     public JarFile JavaDoc getIncludedPackageJarFile(String JavaDoc path, String JavaDoc id, String JavaDoc version, String JavaDoc packageid, String JavaDoc packageversion) {
269         // well first the whole bundle
270
getJarFile(path, id, version);
271
272         // it should now be in our import dir for us to get the package from
273
try {
274             String JavaDoc localname = getImportPath() + id + "_" + version + ".mmb";
275             JarFile JavaDoc jarFile = new JarFile JavaDoc(localname);
276             JarEntry JavaDoc je = jarFile.getJarEntry(packageid + "_" + packageversion + ".mmp");
277             try {
278                 BufferedInputStream JavaDoc in = new BufferedInputStream JavaDoc(jarFile.getInputStream(je));
279                 BufferedOutputStream JavaDoc out = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(getImportPath() + ".temp_" + packageid + "_" + packageversion + ".mmp"));
280                 int val;
281                 while ((val = in.read()) != -1) {
282                     out.write(val);
283                 }
284                 out.close();
285             } catch (Exception JavaDoc e) {
286                 log.error("can't load : " + path);
287                 e.printStackTrace();
288             }
289             JarFile JavaDoc tmpjarfile = new JarFile JavaDoc(getImportPath() + ".temp_" + packageid + "_" + packageversion + ".mmp");
290             return tmpjarfile;
291         } catch (Exception JavaDoc e) {
292             log.error("can't load : " + path);
293             e.printStackTrace();
294         }
295         return null;
296     }
297
298
299     /**
300      * Gets the jarFile attribute of the HttpProvider object
301      *
302      * @param path Description of the Parameter
303      * @param id Description of the Parameter
304      * @param version Description of the Parameter
305      * @return The jarFile value
306      */

307     public JarFile JavaDoc getJarFile(String JavaDoc path, String JavaDoc id, String JavaDoc version) {
308         // since this needs to load a package from a remote site, it uses a url connection
309
// but since we don't want to reload it each time we create a copy in our
310
// import dir, this means if something fails on a install the next install
311
// will use the local copy instead of the remote copy keeping network
312
// traffic down.
313
try {
314             // create a new name in the import dir
315
String JavaDoc localname = getImportPath() + id + "_" + version + ".mmp";
316             // not a very nice way should we have sepr. extentions ?
317
if (id.indexOf("_bundle_") != -1) {
318                 localname = getImportPath() + id + "_" + version + ".mmb";
319             }
320
321         File JavaDoc checkfile = new File JavaDoc(localname);
322         if (!checkfile.exists()) {
323
324             URL JavaDoc includeURL = new URL JavaDoc(path);
325                 HttpURLConnection JavaDoc connection = (HttpURLConnection JavaDoc) includeURL.openConnection();
326                 BufferedInputStream JavaDoc in = new BufferedInputStream JavaDoc(connection.getInputStream());
327                 int buffersize = 10240;
328                 byte[] buffer = new byte[buffersize];
329
330
331                 BufferedOutputStream JavaDoc out = new BufferedOutputStream JavaDoc(new FileOutputStream JavaDoc(localname));
332                 StringBuffer JavaDoc string = new StringBuffer JavaDoc();
333                 int len;
334         int totallen = 0;
335                 while ((len = in.read(buffer, 0, buffersize)) != -1) {
336                     out.write(buffer, 0, len);
337                 if (getInstallStep()!=null) {
338             totallen+=len;
339             String JavaDoc lenp=" received ";
340             if (totallen<1024) {
341                 lenp+=""+totallen+" bytes";
342             } else if (totallen<(1024*1024)) {
343                 lenp+=""+((float)totallen/1024)+" KB";
344             } else {
345                 lenp+=""+((float)totallen/(1024*1024))+" MB";
346             }
347             getInstallStep().setUserFeedBack("getting the mmb bundle... "+lenp);
348             }
349                 }
350                 out.close();
351         }
352
353             JarFile JavaDoc jarFile = new JarFile JavaDoc(localname);
354             return jarFile;
355         } catch (Exception JavaDoc e) {
356             log.error("can't load : " + path + " because " + e);
357         }
358         return null;
359     }
360
361
362     /**
363      * Description of the Method
364      *
365      * @return Description of the Return Value
366      */

367     public boolean close() {
368         return super.close();
369     }
370
371
372     /**
373      * Description of the Method
374      *
375      * @param bun Description of the Parameter
376      * @param n Description of the Parameter
377      * @param realpath Description of the Parameter
378      * @param date Description of the Parameter
379      */

380     private void findIncludedPackages(BundleInterface bun, org.w3c.dom.Node JavaDoc n, String JavaDoc realpath, String JavaDoc date) {
381
382         org.w3c.dom.Node JavaDoc n2 = n.getFirstChild();
383         while (n2 != null) {
384             String JavaDoc name = n2.getNodeName();
385             // this should me one way defined (remote or local)
386
if (name.equals("includedpackages")) {
387                 org.w3c.dom.Node JavaDoc n3 = n2.getFirstChild();
388                 while (n3 != null) {
389                     name = n3.getNodeName();
390                     NamedNodeMap JavaDoc nm = n3.getAttributes();
391                     if (nm != null) {
392                         String JavaDoc maintainer = null;
393                         String JavaDoc type = null;
394                         String JavaDoc version = null;
395                         boolean packed = false;
396
397                         // decode name
398
org.w3c.dom.Node JavaDoc n5 = nm.getNamedItem("name");
399                         if (n5 != null) {
400                             name = n5.getNodeValue();
401                         }
402
403                         // decode the type
404
n5 = nm.getNamedItem("type");
405                         if (n5 != null) {
406                             type = n5.getNodeValue();
407                         }
408
409                         // decode the maintainer
410
n5 = nm.getNamedItem("maintainer");
411                         if (n5 != null) {
412                             maintainer = n5.getNodeValue();
413                         }
414
415                         // decode the version
416
n5 = nm.getNamedItem("version");
417                         if (n5 != null) {
418                             version = n5.getNodeValue();
419                         }
420
421                         // decode the included
422
n5 = nm.getNamedItem("packed");
423                         if (n5 != null) {
424                             if (n5.getNodeValue().equals("true")) {
425                                 packed = true;
426                             }
427                         }
428
429                         // done
430
if (packed) {
431                             PackageInterface pack = PackageManager.foundPackage(this, (Element JavaDoc) n3, name, type, maintainer, version, date, realpath);
432                             // returns a package if new one
433
if (pack != null) {
434                                 pack.setParentBundle(bun);
435                             }
436                         }
437                     }
438                     n3 = n3.getNextSibling();
439                 }
440             }
441             n2 = n2.getNextSibling();
442         }
443     }
444
445
446     /**
447      * Gets the importPath attribute of the HttpProvider object
448      *
449      * @return The importPath value
450      */

451     public String JavaDoc getImportPath() {
452         String JavaDoc path = PackageManager.getConfigPath() + File.separator + "packaging" + File.separator + "import" + File.separator;
453         File JavaDoc dir = new File JavaDoc(path);
454         if (!dir.exists()) {
455             dir.mkdir();
456         }
457         return path;
458     }
459
460
461     public boolean publish(CreatorInterface creator,PackageInterface pack,String JavaDoc sharepassword) {
462     // should be general code for all types once all is in
463
String JavaDoc filename=pack.getId()+"_"+pack.getVersion()+".mmp";
464
465     String JavaDoc posturl = getPath();
466     if (posturl.startsWith("http://")) {
467         posturl = posturl.substring(7);
468     }
469     int pos=posturl.indexOf("/");
470     if (pos!=-1) {
471         posturl = posturl.substring(0,pos);
472     }
473     posturl = "http://"+posturl + "/mmbase/packagemanager/upload/package.mmp";
474         try {
475         String JavaDoc boundary = "*5433***3243";
476     
477             // Send data
478
URL JavaDoc url = new URL JavaDoc(posturl);
479         HttpURLConnection JavaDoc conn = (HttpURLConnection JavaDoc) url.openConnection();
480         conn.setDoInput(true);
481             conn.setDoOutput(true);
482             conn.setUseCaches(false);
483             conn.setRequestMethod("POST");
484             conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
485
486        DataOutputStream JavaDoc out = new DataOutputStream JavaDoc(conn.getOutputStream());
487
488        out.writeBytes("--"+boundary+"\r\n");
489        out.writeBytes("Content-Disposition: form-data; name=\"filename\"\r\n\r\n");
490        out.writeBytes(filename+"\r\n");
491
492        out.writeBytes("--"+boundary+"\r\n");
493        out.writeBytes("Content-Disposition: form-data; name=\"account\"\r\n\r\n");
494        out.writeBytes(account+"\r\n");
495
496        out.writeBytes("--"+boundary+"\r\n");
497        out.writeBytes("Content-Disposition: form-data; name=\"password\"\r\n\r\n");
498        out.writeBytes(password+"\r\n");
499
500        out.writeBytes("--"+boundary+"\r\n");
501        out.writeBytes("Content-Disposition: form-data; name=\"sharepassword\"\r\n\r\n");
502        out.writeBytes(sharepassword+"\r\n");
503        out.writeBytes("--"+boundary+"\r\n");
504        out.writeBytes("Content-Disposition: form-data; name=\"handle\"; filename=\"" +"testname" +"\"\r\n\r\n");
505        String JavaDoc oldline="";
506            if (getPackageStep()!=null) { oldline = getPackageStep().getUserFeedBack(); }
507
508             try {
509                 BufferedInputStream JavaDoc in = new BufferedInputStream JavaDoc(pack.getJarStream());
510                 int val;
511         int totallen=0;
512                 while ((val = in.read()) != -1) {
513                     out.write(val);
514             totallen++;
515                 if (getPackageStep()!=null) {
516             String JavaDoc lenp=" send ";
517             if (totallen<1024) {
518                 lenp+=""+totallen+" bytes";
519             } else if (totallen<(1024*1024)) {
520                 lenp+=""+((float)totallen/1024)+" KB";
521             } else {
522                 lenp+=""+((float)totallen/(1024*1024))+" MB";
523             }
524             getPackageStep().setUserFeedBack(oldline+lenp);
525             }
526                 }
527             } catch (Exception JavaDoc e) {
528                 log.error("can't load : " + path);
529                 e.printStackTrace();
530             }
531         out.writeBytes("\r\n");
532         out.writeBytes("--"+boundary+"--\r\n");
533         out.flush();
534         out.close();
535
536             if (getPackageStep()!=null) getPackageStep().setUserFeedBack(oldline+" server processing");
537     
538             // Get the response
539
BufferedReader JavaDoc rd = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(conn.getInputStream()));
540             String JavaDoc line;
541             while ((line = rd.readLine()) != null) {
542                 // Process line...
543
}
544             rd.close();
545         } catch (Exception JavaDoc e) {
546         log.error("Publish upload problem to : "+posturl);
547         }
548     return true;
549     }
550
551     public boolean publish(CreatorInterface creator,BundleInterface bundle,String JavaDoc sharepassword) {
552     // should be general code for all types once all is in
553
String JavaDoc filename=bundle.getId()+"_"+bundle.getVersion()+".mmb";
554
555     String JavaDoc posturl = getPath();
556     if (posturl.startsWith("http://")) {
557         posturl = posturl.substring(7);
558     }
559     int pos=posturl.indexOf("/");
560     if (pos!=-1) {
561         posturl = posturl.substring(0,pos);
562     }
563     posturl = "http://"+posturl + "/mmbase/packagemanager/upload/package.mmp";
564         try {
565         String JavaDoc boundary = "*5433***3243";
566     
567             // Send data
568
URL JavaDoc url = new URL JavaDoc(posturl);
569         HttpURLConnection JavaDoc conn = (HttpURLConnection JavaDoc) url.openConnection();
570         conn.setDoInput(true);
571             conn.setDoOutput(true);
572             conn.setUseCaches(false);
573             conn.setRequestMethod("POST");
574             conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
575
576        DataOutputStream JavaDoc out = new DataOutputStream JavaDoc(conn.getOutputStream());
577
578        out.writeBytes("--"+boundary+"\r\n");
579        out.writeBytes("Content-Disposition: form-data; name=\"filename\"\r\n\r\n");
580        out.writeBytes(filename+"\r\n");
581
582        out.writeBytes("--"+boundary+"\r\n");
583        out.writeBytes("Content-Disposition: form-data; name=\"account\"\r\n\r\n");
584        out.writeBytes(account+"\r\n");
585
586        out.writeBytes("--"+boundary+"\r\n");
587        out.writeBytes("Content-Disposition: form-data; name=\"password\"\r\n\r\n");
588        out.writeBytes(password+"\r\n");
589
590        out.writeBytes("--"+boundary+"\r\n");
591        out.writeBytes("Content-Disposition: form-data; name=\"sharepassword\"\r\n\r\n");
592        out.writeBytes(sharepassword+"\r\n");
593        out.writeBytes("--"+boundary+"\r\n");
594        out.writeBytes("Content-Disposition: form-data; name=\"handle\"; filename=\"" +"testname" +"\"\r\n\r\n");
595        String JavaDoc oldline="";
596            if (getPackageStep()!=null) { oldline = getPackageStep().getUserFeedBack(); }
597
598             try {
599                 BufferedInputStream JavaDoc in = new BufferedInputStream JavaDoc(bundle.getJarStream());
600                 int val;
601         int totallen=0;
602                 while ((val = in.read()) != -1) {
603                     out.write(val);
604             totallen++;
605                 if (getPackageStep()!=null) {
606             String JavaDoc lenp=" send ";
607             if (totallen<1024) {
608                 lenp+=""+totallen+" bytes";
609             } else if (totallen<(1024*1024)) {
610                 lenp+=""+((float)totallen/1024)+" KB";
611             } else {
612                 lenp+=""+((float)totallen/(1024*1024))+" MB";
613             }
614             getPackageStep().setUserFeedBack(oldline+lenp);
615             }
616                 }
617             } catch (Exception JavaDoc e) {
618                 log.error("can't load : " + path);
619                 e.printStackTrace();
620             }
621         out.writeBytes("\r\n");
622         out.writeBytes("--"+boundary+"--\r\n");
623         out.flush();
624         out.close();
625     
626             if (getPackageStep()!=null) getPackageStep().setUserFeedBack(oldline+" server processing");
627
628             // Get the response
629
BufferedReader JavaDoc rd = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(conn.getInputStream()));
630             String JavaDoc line;
631             while ((line = rd.readLine()) != null) {
632                 // Process line...
633
}
634             rd.close();
635         } catch (Exception JavaDoc e) {
636         log.error("Publish upload problem to : "+posturl);
637         }
638     return true;
639     }
640 }
641
642
Popular Tags