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