xref: /AOO41X/main/xmerge/source/bridge/java/XMergeBridge.java (revision ff0525f24f03981d56b7579b645949f111420994)
1 /**************************************************************
2  *
3  * Licensed to the Apache Software Foundation (ASF) under one
4  * or more contributor license agreements.  See the NOTICE file
5  * distributed with this work for additional information
6  * regarding copyright ownership.  The ASF licenses this file
7  * to you under the Apache License, Version 2.0 (the
8  * "License"); you may not use this file except in compliance
9  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  *************************************************************/
21 
22 
23 
24 /** You can find more
25  * information on the following web page:
26  * http://api.openoffice.org/common/ref/com/sun/star/index.html
27  */
28 
29 
30 /*Java Uno Helper Classes*/
31 import com.sun.star.lib.uno.adapter.XInputStreamToInputStreamAdapter;
32 import com.sun.star.lib.uno.adapter.XOutputStreamToOutputStreamAdapter;
33 
34 /*StarOffice/Uno Classes*/
35 import com.sun.star.lang.XMultiServiceFactory;
36 import com.sun.star.lang.XServiceInfo;
37 import com.sun.star.lang.XTypeProvider;
38 import com.sun.star.uno.Type;
39 import com.sun.star.uno.UnoRuntime;
40 import com.sun.star.comp.loader.FactoryHelper;
41 import com.sun.star.lang.XServiceName;
42 import com.sun.star.lang.XSingleServiceFactory;
43 import com.sun.star.registry.XRegistryKey;
44 import com.sun.star.frame.XConfigManager;
45 import com.sun.star.xml.sax.InputSource;
46 import com.sun.star.xml.sax.XParser;
47 import com.sun.star.io.XInputStream;
48 import com.sun.star.io.XOutputStream;
49 import com.sun.star.xml.sax.XDocumentHandler;
50 import com.sun.star.uno.AnyConverter;
51 
52 /* Generated from Idls */
53 import com.sun.star.xml.XImportFilter;
54 import com.sun.star.xml.XExportFilter;
55 
56 /* XMerge Classes */
57 import org.openoffice.xmerge.util.registry.ConverterInfoReader;
58 import org.openoffice.xmerge.util.registry.ConverterInfo;
59 import org.openoffice.xmerge.util.registry.ConverterInfoMgr;
60 import org.openoffice.xmerge.Convert;
61 import org.openoffice.xmerge.ConverterFactory;
62 import org.openoffice.xmerge.Document;
63 import org.openoffice.xmerge.ConvertData;
64 import org.openoffice.xmerge.converter.xml.OfficeDocument;
65 /*Java Classes*/
66 import java.util.Enumeration;
67 import java.io.*;
68 import javax.xml.parsers.*;
69 import java.net.URI;
70 
71 
72 /** This outer class provides an inner class to implement the service
73  * description and a method to instantiate the
74  * component on demand (__getServiceFactory()).
75  */
76 public class XMergeBridge {
77 
78 
79     private static XMultiServiceFactory xMSF;
80     private static XDocumentHandler exportDocHandler=null;
81     private static XInputStream xInStream =null;
82     private static XOutputStream xOutStream=null;
83     private static String  udJarPath=null;
84     private static XOutputStream xos = null;
85     private static XOutputStreamToOutputStreamAdapter adaptedStream=null;
86     private static String offMime=null;
87     private static String sdMime=null;
88     private static String sFileName=null;
89     private static String sURL="";
90 
91     //private static FileOutputStream adaptedStream =null;
92 
93     /** This inner class provides the component as a concrete implementation
94      * of the service description. It implements the needed interfaces.
95      * @implements XTypeProvider
96      */
97     static public class _XMergeBridge implements
98                                                XImportFilter,
99      XExportFilter,
100         XServiceName,
101         XServiceInfo,
102     XDocumentHandler,
103         XTypeProvider {
104 
105         /** The component will be registered under this name.
106          */
107         static private final String __serviceName = "com.sun.star.documentconversion.XMergeBridge";
108 
109 
110 
111         public com.sun.star.uno.Type[] getTypes() {
112             Type[] typeReturn = {};
113 
114             try {
115                 typeReturn = new Type[] {
116                 new Type( XTypeProvider.class ),
117                 new Type( XImportFilter.class ),
118         new Type( XExportFilter.class ),
119                 new Type( XServiceName.class ),
120                 new Type( XServiceInfo.class ) };
121             }
122             catch( Exception exception ) {
123 
124             }
125 
126             return( typeReturn );
127         }
128 
129     String getFileName(String origName)
130     {
131         String name=null;
132         if (origName !=null)
133         {
134         if(origName.equalsIgnoreCase(""))
135             name = "OutFile";
136         else {
137             if (origName.lastIndexOf("/")>=0){
138                 origName=origName.substring(origName.lastIndexOf("/")+1,origName.length());
139             }
140             if (origName.lastIndexOf(".")>=0){
141             name = origName.substring(0,(origName.lastIndexOf(".")));
142             }
143             else{
144             name=origName;
145             }
146         }
147         }
148         else{
149         name = "OutFile";
150         }
151         return name;
152     }
153 
154 
155 
156     public boolean importer(com.sun.star.beans.PropertyValue[] aSourceData,
157                 com.sun.star.xml.sax.XDocumentHandler xDocHandler,
158                 java.lang.String[] msUserData) throws com.sun.star.uno.RuntimeException {
159                 /*
160         System.out.println("\nFound the Importer!\n");
161 
162         System.out.println("\n"+msUserData[0]);
163         System.out.println("\n"+msUserData[1]);
164         System.out.println("\n"+msUserData[2]);
165         System.out.println("\n"+msUserData[3]);
166         System.out.println("\n"+msUserData[4]);
167         System.out.println("\n"+msUserData[5]);
168         */
169         sFileName="";
170         sURL="";
171         String sDirectory = null;
172         String udConvertClass=msUserData[0];
173         udJarPath=msUserData[1];
174         String udImport =msUserData[2];
175         String udExport =msUserData[3];
176         offMime =msUserData[4];
177         sdMime = msUserData[5];
178         com.sun.star.io.XInputStream xis=null;
179         com.sun.star.beans.PropertyValue[] pValue = aSourceData;
180 
181         for  (int  i = 0 ; i < pValue.length; i++)
182         {
183 
184         //System.out.println("\n"+pValue[i].Name+" "+pValue[i].Value;
185 
186          try{
187              //System.out.println("\n"+pValue[i].Name+" "+pValue[i].Value);
188              if (pValue[i].Name.compareTo("InputStream")==0){
189             xis=(com.sun.star.io.XInputStream)AnyConverter.toObject(new Type(com.sun.star.io.XInputStream.class), pValue[i].Value);
190              }
191              if (pValue[i].Name.compareTo("FileName")==0){
192              sFileName=(String)AnyConverter.toObject(new Type(java.lang.String.class), pValue[i].Value);
193              }
194 
195          }
196          catch(com.sun.star.lang.IllegalArgumentException AnyExec){
197              System.out.println("\nIllegalArgumentException "+AnyExec);
198          }
199 
200 
201 
202         }
203 
204 
205         try{
206 
207         Object xCfgMgrObj=xMSF.createInstance("com.sun.star.config.SpecialConfigManager");
208          XConfigManager xCfgMgr = (XConfigManager) UnoRuntime.queryInterface(
209                                             XConfigManager.class , xCfgMgrObj );
210         String PathString=xCfgMgr.substituteVariables("$(progurl)" );
211         PathString= PathString.concat("/");
212         udJarPath= PathString.concat(udJarPath);
213 
214         Object xPipeObj=xMSF.createInstance("com.sun.star.io.Pipe");
215         xInStream = (XInputStream) UnoRuntime.queryInterface(
216                         XInputStream.class , xPipeObj );
217             xOutStream = (XOutputStream) UnoRuntime.queryInterface(
218                         XOutputStream.class , xPipeObj );
219         convert (xis,xOutStream,false,udJarPath,sFileName,offMime,sdMime);
220         Object xSaxParserObj=xMSF.createInstance("com.sun.star.xml.sax.Parser");
221 
222         XParser xParser = (XParser) UnoRuntime.queryInterface(
223                         XParser.class , xSaxParserObj );
224         if (xParser==null){
225             System.out.println("\nParser creation Failed");
226         }
227         xOutStream.closeOutput();
228         InputSource aInput = new InputSource();
229         if (sFileName==null){
230             sFileName="";
231             }
232         aInput.sSystemId = sFileName;
233         aInput.aInputStream =xInStream;
234                 xParser.setDocumentHandler ( xDocHandler );
235 
236         xParser.parseStream ( aInput );
237         xOutStream.closeOutput();
238         xInStream.closeInput();
239 
240         }
241         catch (IOException e){
242         //System.out.println("XMergeBridge IO Exception "+e.getMessage());
243           return false;
244         }
245          catch (Exception e){
246         //System.out.println("XMergeBridge Exception "+e+" "+e.getMessage());
247         return false;
248         }
249         return true;
250     }
251 
252        public boolean exporter(com.sun.star.beans.PropertyValue[] aSourceData,
253                    java.lang.String[] msUserData) throws com.sun.star.uno.RuntimeException{
254 
255                    /*
256         System.out.println("\nFound the Exporter!\n");
257 
258         System.out.println("\n"+msUserData[0]);
259         System.out.println("\n"+msUserData[1]);
260         System.out.println("\n"+msUserData[2]);
261         System.out.println("\n"+msUserData[3]);
262         System.out.println("\n"+msUserData[4]);
263         System.out.println("\n"+msUserData[5]);
264         */
265         sFileName=null;
266         sURL=null;
267         String sDirectory = null;
268         String title=null;
269         String udConvertClass=msUserData[0];
270         udJarPath=msUserData[1];
271         String udImport =msUserData[2];
272         String udExport =msUserData[3];
273         offMime =msUserData[4];
274         sdMime = msUserData[5];
275 
276         com.sun.star.beans.PropertyValue[] pValue = aSourceData;
277         for  (int  i = 0 ; i < pValue.length; i++)
278         {
279 
280         //System.out.println("\n"+pValue[i].Name+" "+pValue[i].Value);
281 
282 
283         try{
284             //System.out.println("\n"+pValue[i].Name+" "+pValue[i].Value);
285             if (pValue[i].Name.compareTo("OutputStream")==0){
286             xos=(com.sun.star.io.XOutputStream)AnyConverter.toObject(new Type(com.sun.star.io.XOutputStream.class), pValue[i].Value);
287             //  System.out.println(pValue[i].Name+" "+xos);
288             }
289             if (pValue[i].Name.compareTo("FileName")==0){
290             sFileName=(String)AnyConverter.toObject(new Type(java.lang.String.class), pValue[i].Value);
291             //System.out.println(pValue[i].Name+" "+sFileName);
292             }
293             if (pValue[i].Name.compareTo("URL")==0){
294             sURL=(String)AnyConverter.toObject(new Type(java.lang.String.class), pValue[i].Value);
295             // System.out.println("\nMediaDescriptor url "+pValue[i].Name+" "+sURL);
296 
297             }
298             if (pValue[i].Name.compareTo("Title")==0){
299 
300             title=(String)AnyConverter.toObject(new Type(java.lang.String.class), pValue[i].Value);
301             //System.out.println(pValue[i].Name+" "+title);
302             }
303         }
304         catch(com.sun.star.lang.IllegalArgumentException AnyExec){
305              System.out.println("\nIllegalArgumentException "+AnyExec);
306         }
307         }
308 
309 
310         if (sURL==null){
311         sURL="";
312         }
313 
314          try{
315 
316          Object xCfgMgrObj=xMSF.createInstance("com.sun.star.config.SpecialConfigManager");
317          XConfigManager xCfgMgr = (XConfigManager) UnoRuntime.queryInterface(
318                                             XConfigManager.class , xCfgMgrObj );
319 
320         String PathString=xCfgMgr.substituteVariables("$(progurl)" );
321         PathString= PathString.concat("/");
322         udJarPath= PathString.concat(udJarPath);
323 
324         Object xPipeObj=xMSF.createInstance("com.sun.star.io.Pipe");
325         xInStream = (XInputStream) UnoRuntime.queryInterface(
326                         XInputStream.class , xPipeObj );
327         xOutStream = (XOutputStream) UnoRuntime.queryInterface(
328                         XOutputStream.class , xPipeObj );
329            }
330           catch (Exception e){
331         System.out.println("Exception "+e);
332           return false;
333         }
334 
335         return true;
336        }
337 
338     public String replace(String origString, String origChar, String replaceChar){
339            String tmp="";
340            int index=origString.indexOf(origChar);
341            if(index !=-1){
342            while (index !=-1){
343                String first =origString.substring(0,index);
344                first=first.concat(replaceChar);
345                tmp=tmp.concat(first);
346                origString=origString.substring(index+1,origString.length());
347                index=origString.indexOf(origChar);
348                if(index==-1) {
349                tmp=tmp.concat(origString);
350                }
351 
352            }
353 
354            }
355            return tmp;
356     }
357 
358     public String needsMask(String origString){
359         if (origString.indexOf("&")!=-1){
360         origString=replace(origString,"&","&amp;");
361         }
362          if (origString.indexOf("\"")!=-1){
363         origString=replace(origString,"\"","&quot;");
364         }
365         if (origString.indexOf("<")!=-1){
366         origString=replace(origString,"<","&lt;");
367         }
368         if (origString.indexOf(">")!=-1){
369         origString=replace(origString,">","&gt;");
370         }
371         return origString;
372 
373     }
374 
375 
376 
377        public void  startDocument ()    {
378        //System.out.println("\nStart Document!");
379        }
380 
381     public void endDocument()throws com.sun.star.uno.RuntimeException
382     {
383 
384         try{
385         xOutStream.closeOutput();
386         convert (xInStream,xos,true,udJarPath,sURL,offMime,sdMime);
387 
388         }
389         catch (IOException e){
390         //System.out.println("Exception "+e);
391         throw new com.sun.star.uno.RuntimeException(e.getMessage());
392 
393         }
394          catch (Exception e){
395         //System.out.println("Exception "+e);
396         throw new com.sun.star.uno.RuntimeException("Xmerge Exception");
397 
398         }
399     }
400 
401 
402 
403     public void startElement (String str, com.sun.star.xml.sax.XAttributeList xattribs)
404     {
405 
406         str="<".concat(str);
407         if (xattribs !=null)
408         {
409         str= str.concat(" ");
410         int len=xattribs.getLength();
411         for (short i=0;i<len;i++)
412             {
413             str=str.concat(xattribs.getNameByIndex(i));
414             str=str.concat("=\"");
415             str=str.concat(needsMask(xattribs.getValueByIndex(i)));
416             str=str.concat("\" ");
417             }
418         }
419         str=str.concat(">");
420         // System.out.println(str);
421         try{
422          xOutStream.writeBytes(str.getBytes("UTF-8"));
423         }
424         catch (Exception e){
425         System.out.println("\n"+e);
426         }
427 
428     }
429 
430     public void endElement(String str){
431 
432         str="</".concat(str);
433         str=str.concat(">");
434         try{
435          xOutStream.writeBytes(str.getBytes("UTF-8"));
436 
437         }
438         catch (Exception e){
439         System.out.println("\n"+e);
440         }
441 
442 
443     }
444     public void characters(String str){
445         str=needsMask(str);
446         try{
447          xOutStream.writeBytes(str.getBytes("UTF-8"));
448         }
449        catch (Exception e){
450            System.out.println("\n"+e);
451        }
452 
453 
454     }
455 
456     public void ignorableWhitespace(String str){
457 
458 
459     }
460        public void processingInstruction(String aTarget, String aData){
461 
462        }
463 
464     public void setDocumentLocator(com.sun.star.xml.sax.XLocator xLocator){
465 
466     }
467 
468 
469 
470 
471 
472 
473     public void convert (com.sun.star.io.XInputStream xml,com.sun.star.io.XOutputStream device,
474              boolean convertFromOffice,String pluginUrl,String FileName,String offMime,String sdMime) throws com.sun.star.uno.RuntimeException, IOException {
475 
476          String jarName = pluginUrl;
477          String name= getFileName(FileName);
478 
479          ConverterInfo converterInfo = null;
480          Enumeration ciEnum= null;
481 
482          XInputStreamToInputStreamAdapter xis =new XInputStreamToInputStreamAdapter(xml);
483 
484 
485          XOutputStreamToOutputStreamAdapter newxos =new XOutputStreamToOutputStreamAdapter(device);
486          try{
487          ConverterInfoReader cir = new ConverterInfoReader(jarName,false);
488          ciEnum =cir.getConverterInfoEnumeration();
489          }
490          catch (ParserConfigurationException pexc){
491           System.out.println("Error:"+pexc);
492          }
493           catch ( org.xml.sax.SAXException pexc){
494           System.out.println("Error:"+pexc);
495          }
496          catch(Exception e){
497          System.out.println("Error:"+e);
498          }
499          ConverterInfoMgr. removeByJar(jarName);
500          if (convertFromOffice)
501          {
502 
503          try {
504 
505              //Check to see if jar contains a plugin Impl
506 
507                  ConverterInfoMgr.addPlugIn(ciEnum);
508              ConverterFactory cf = new ConverterFactory();
509 
510              Convert cv = cf.getConverter(ConverterInfoMgr.findConverterInfo(sdMime,offMime),false);
511              if (cv == null) {
512                  System.out.println("\nNo plug-in exists to convert from <staroffice/sxw> to <specified format> ");
513 
514              }
515              else
516              {
517                  cv.addInputStream(name,(InputStream)xis,false);
518                  ConvertData dataOut = cv.convert();
519 
520                  Enumeration docEnum = dataOut.getDocumentEnumeration();
521 
522                  if (docEnum.hasMoreElements()){
523                      Document docOut      = (Document)docEnum.nextElement();
524                      String fileName      = docOut.getFileName();
525                      docOut.write(newxos);
526 
527                      newxos.flush();
528                      newxos.close();
529 
530 
531                      int i=1;
532                      while (docEnum.hasMoreElements() && sURL.startsWith("file:")) {
533                      //URI uri=new URI(sFileName);
534                      URI uri=new URI(sURL);
535                      String  newFileName= getPath(uri);
536 
537 
538                      //System.out.println("\nURI: "+uri.getPath());
539                      File newFile=null;
540                      if (newFileName.lastIndexOf(".")!=-1){
541                          newFile =new File(newFileName.substring(0,newFileName.lastIndexOf("."))+String.valueOf(i)+newFileName.substring(newFileName.lastIndexOf(".")));
542                      }
543                      else{
544                         newFile =new File(newFileName.concat(String.valueOf(i)));
545                      }
546 
547                      FileOutputStream fos = new FileOutputStream(newFile);
548                      docOut      = (Document)docEnum.nextElement();
549                      fileName      = docOut.getFileName();
550                      docOut.write(fos);
551                      fos.flush();
552                      fos.close();
553                      i++;
554 
555                      }
556 
557                  }
558              }
559              ConverterInfoMgr.removeByJar(jarName);
560          }
561          catch (StackOverflowError sOE){
562              System.out.println("\nERROR : Stack OverFlow. \n Increase of the JRE by adding the following line to the end of the javarc file \n \"-Xss1m\"\n");
563 
564          }
565          catch (Exception e) {
566              System.out.println("Error:"+e);
567               throw new IOException("Xmerge Exception");
568              }
569          }
570          else{
571 
572          try {
573               //Check to see if jar contains a plugin Impl
574                  ConverterInfoMgr.addPlugIn(ciEnum);
575                  ConverterFactory cf = new ConverterFactory();
576              Convert cv = cf.getConverter(ConverterInfoMgr.findConverterInfo(sdMime,offMime),true);
577              if (cv == null) {
578                  System.out.println("\nNo plug-in exists to convert to <staroffice/sxw> from <specified format>");
579              }
580              else
581              {
582                              /*
583                              ByteArrayOutputStream bout = new ByteArrayOutputStream();
584                              byte[][] buf = new byte[1][4096];
585                              int n=0;
586                              while ((n=xml.readSomeBytes(buf, 4096))>0)
587                                  bout.write(buf[0], 0, n);
588                              ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
589                              cv.addInputStream(name, bin, false);
590                             */
591                  cv.addInputStream(name,(InputStream)xis,false);
592                  //System.out.println("\nConverting");
593                  ConvertData dataIn = cv.convert();
594                  //System.out.println("\nFinished Converting");
595                  Enumeration docEnum = dataIn.getDocumentEnumeration();
596                  while (docEnum.hasMoreElements()) {
597                  OfficeDocument docIn      = (OfficeDocument)docEnum.nextElement();
598 
599                  docIn.write(newxos,false);
600                  }
601                  //newxos.write(-1); //EOF character
602                                //newxos.flush();
603                  newxos.close();
604              }
605              ConverterInfoMgr.removeByJar(jarName);
606          }
607          catch (StackOverflowError sOE){
608               System.out.println("\nERROR : Stack OverFlow. \n Increase of the JRE by adding the following line to the end of the javarc file \n \"-Xss1m\"\n");
609          }
610          catch (Exception e) {
611              System.out.println("Error:"+e);
612              throw new IOException("Xmerge Exception");
613          }
614 
615 
616          }
617 
618     }
619 
620         private String getPath(URI uri){
621         String path = uri.getPath();
622         String opSys=System.getProperty("os.name");
623         if(opSys.indexOf("Windows")!=-1){
624         path= path.replace('/','\\');
625         path = path.substring(1);
626         }
627         return path;
628     }
629 
630 
631 
632 
633 
634 
635 
636         // Implement methods from interface XTypeProvider
637         public byte[] getImplementationId() {
638             byte[] byteReturn = {};
639 
640             byteReturn = new String( "" + this.hashCode() ).getBytes();
641 
642             return( byteReturn );
643         }
644 
645         // Implement method from interface XServiceName
646         public String getServiceName() {
647             return( __serviceName );
648         }
649 
650         // Implement methods from interface XServiceInfo
651         public boolean supportsService(String stringServiceName) {
652             return( stringServiceName.equals( __serviceName ) );
653         }
654 
655         public String getImplementationName() {
656             return( _XMergeBridge.class.getName() );
657         }
658 
659         public String[] getSupportedServiceNames() {
660             String[] stringSupportedServiceNames = { __serviceName };
661             return( stringSupportedServiceNames );
662         }
663     }
664 
665     /**
666      * Returns a factory for creating the service.
667      * This method is called by the <code>JavaLoader</code>
668      *
669      * @return  returns a <code>XSingleServiceFactory</code> for creating the
670      *          component
671      *
672      * @param   implName     the name of the implementation for which a
673      *                       service is desired
674      * @param   multiFactory the service manager to be used if needed
675      * @param   regKey       the registryKey
676      *
677      * @see                  com.sun.star.comp.loader.JavaLoader
678      */
679     public static XSingleServiceFactory __getServiceFactory(String implName,
680     XMultiServiceFactory multiFactory,
681     XRegistryKey regKey) {
682     xMSF= multiFactory;
683         XSingleServiceFactory xSingleServiceFactory = null;
684         if (implName.equals(_XMergeBridge.class.getName()) ) {
685             xSingleServiceFactory = FactoryHelper.getServiceFactory(_XMergeBridge.class,
686             _XMergeBridge.__serviceName,
687             multiFactory,
688             regKey);
689         }
690 
691         return xSingleServiceFactory;
692     }
693 }
694